Created
February 1, 2012 17:00
-
-
Save elazarl/1718032 to your computer and use it in GitHub Desktop.
A simple bencode encoder that can handle streaming data
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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