Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- package me.rabrg.bencode;
- import java.io.IOException;
- import java.io.InputStream;
- import java.nio.charset.Charset;
- public final class BencodeDecoder {
- private static final Charset CHARSET = Charset.forName("US-ASCII");
- private final byte[] buffer;
- private int pos = 0;
- public BencodeDecoder(final InputStream inputStream) throws IOException {
- buffer = new byte[inputStream.available()];
- inputStream.read(buffer);
- }
- public BencodeDecoder(final String string) {
- buffer = string.getBytes(CHARSET);
- }
- public BencodeDecoder(final byte[] bytes) {
- buffer = bytes;
- }
- public Object read() {
- if (buffer[pos] >= '0' && buffer[pos] <= '9') {
- return readString();
- } else if (buffer[pos] == 'i') {
- return readInteger();
- }
- throw new IllegalStateException("the byte " + buffer[pos] + " (char " + (char) buffer[pos] + ") is not a valid key");
- }
- private int readInteger() {
- final int start = ++pos;
- while (buffer[pos] != 'e') {
- pos++;
- }
- return Integer.parseInt(new String(buffer, start, pos++ - start, CHARSET));
- }
- private String readString() {
- final int start = pos++;
- while (buffer[pos++] != ':') {
- }
- final String string = new String(buffer, pos, Integer.parseInt(new String(buffer, start, pos - start - 1, CHARSET)), CHARSET);
- pos += string.length();
- return string;
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement