Permalink
Browse files

Fixed handling of third-party variant types

  • Loading branch information...
djspiewak committed Apr 18, 2008
1 parent be9ea18 commit bb9a0adf3011455b30490ba4e21a45037c5bab87
Showing with 40 additions and 0 deletions.
  1. +40 −0 src/com/googlecode/jbencode/Parser.java
@@ -13,6 +13,9 @@
import com.googlecode.jbencode.composite.DictionaryValue;
import com.googlecode.jbencode.composite.ListValue;
import com.googlecode.jbencode.primitive.IntegerValue;
import com.googlecode.jbencode.primitive.StringValue;
import com.googlecode.jbencode.primitive.VariantValue;
import com.googlecode.jbencode.util.SubStream;
/**
* @author Daniel Spiewak
@@ -41,6 +44,25 @@ public final void addValue(Class<? extends Value<?>> value) {
}
public static final <T extends Value<?>> T createValue(Class<T> type, Parser p, InputStream is) {
boolean isVariant = true;
try {
type.asSubclass(VariantValue.class);
} catch (ClassCastException e) {
isVariant = false;
}
if (isVariant && !type.equals(StringValue.class)) { // string is special
try {
return readVariant(type, p, is, 0);
} catch (IOException e) {
return null;
}
}
return createValueImpl(type, p, is);
}
private static final <T extends Value<?>> T createValueImpl(Class<T> type, Parser p, InputStream is) {
try {
return type.getConstructor(Parser.class, InputStream.class).newInstance(p, is);
} catch (IllegalArgumentException e) {
@@ -54,6 +76,24 @@ public final void addValue(Class<? extends Value<?>> value) {
return null;
}
private static final <T extends Value<?>> T readVariant(Class<T> type, Parser parser, InputStream is, long length) throws IOException {
int i = is.read();
if (i >= 0) {
byte b = (byte) i;
if (b == ':') {
return createValueImpl(type, parser, new SubStream(is, length));
} else if (b >= '0' && b <= '9') {
return readVariant(type, parser, is, (length * 10) + b - '0');
} else {
throw new IOException("Unexpected character in variant value: " + Character.forDigit(i, 10));
}
}
throw new IOException("Unexpected end of stream in variant value");
}
private static final class DelegateComposite extends CompositeValue<DelegateComposite, Value<?>> {
private boolean exhausted = false;

0 comments on commit bb9a0ad

Please sign in to comment.