Skip to content

Instantly share code, notes, and snippets.

@elazarl
Created February 1, 2012 17:00
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save elazarl/1718032 to your computer and use it in GitHub Desktop.
Save elazarl/1718032 to your computer and use it in GitHub Desktop.
A simple bencode encoder that can handle streaming data
class BencodeWriter {
static class SizedInputStream {
public InputStream stream;
public int size;
public SizedInputStream(InputStream _stream,int _size) {stream = _stream;size = _size;}
}
public static class BencodeProducer {
private OutputStream out;
public BencodeProducer(OutputStream o) {out = o;}
public void put(Object o) throws IOException {
// Java's poor man's pattern matching
if (o instanceof SizedInputStream) {
final SizedInputStream input = ((SizedInputStream) o);
out.write((input.size +":").getBytes());
ByteStreams.copy(input.stream,out);
} else if (o instanceof Integer) {
Integer i = (Integer) o;
out.write(("i"+i+"e").getBytes());
} else if (o instanceof Iterable) {
Iterable iterable = (Iterable) o;
for (Object o2 : iterable) {
put(o2);
}
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment