Skip to content

Commit c8a6665

Browse files
authored
Remove encode conditions by using a consumer pattern (#26)
1 parent 843b8b4 commit c8a6665

File tree

1 file changed

+12
-13
lines changed

1 file changed

+12
-13
lines changed

src/main/java/com/dampcake/bencode/Bencode.java

Lines changed: 12 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -17,6 +17,7 @@
1717

1818
import java.io.ByteArrayInputStream;
1919
import java.io.ByteArrayOutputStream;
20+
import java.io.IOException;
2021
import java.nio.charset.Charset;
2122
import java.util.Map;
2223

@@ -176,7 +177,7 @@ public <T> T decode(final byte[] bytes, final Type<T> type) {
176177
public byte[] encode(final String s) {
177178
if (s == null) throw new NullPointerException("s cannot be null");
178179

179-
return encode(s, Type.STRING);
180+
return encode(bencode -> bencode.writeString(s));
180181
}
181182

182183
/**
@@ -194,7 +195,7 @@ public byte[] encode(final String s) {
194195
public byte[] encode(final Number n) {
195196
if (n == null) throw new NullPointerException("n cannot be null");
196197

197-
return encode(n, Type.NUMBER);
198+
return encode(bencode -> bencode.writeNumber(n));
198199
}
199200

200201
/**
@@ -214,7 +215,7 @@ public byte[] encode(final Number n) {
214215
public byte[] encode(final Iterable<?> l) {
215216
if (l == null) throw new NullPointerException("l cannot be null");
216217

217-
return encode(l, Type.LIST);
218+
return encode(bencode -> bencode.writeList(l));
218219
}
219220

220221
/**
@@ -234,25 +235,23 @@ public byte[] encode(final Iterable<?> l) {
234235
public byte[] encode(final Map<?, ?> m) {
235236
if (m == null) throw new NullPointerException("m cannot be null");
236237

237-
return encode(m, Type.DICTIONARY);
238+
return encode(bencode -> bencode.writeDictionary(m));
238239
}
239240

240-
private byte[] encode(final Object o, final Type type) {
241+
private byte[] encode(final ThrowingConsumer<BencodeOutputStream> function) {
241242
ByteArrayOutputStream out = new ByteArrayOutputStream();
242243

243244
try (BencodeOutputStream bencode = new BencodeOutputStream(out, charset)) {
244-
if (type == Type.STRING)
245-
bencode.writeString((String) o);
246-
else if (type == Type.NUMBER)
247-
bencode.writeNumber((Number) o);
248-
else if (type == Type.LIST)
249-
bencode.writeList((Iterable) o);
250-
else if (type == Type.DICTIONARY)
251-
bencode.writeDictionary((Map) o);
245+
function.accept(bencode);
252246
} catch (Throwable t) {
253247
throw new BencodeException("Exception thrown during encoding", t);
254248
}
255249

256250
return out.toByteArray();
257251
}
252+
253+
@FunctionalInterface
254+
public interface ThrowingConsumer<T> {
255+
public void accept(T t) throws IOException;
256+
}
258257
}

0 commit comments

Comments
 (0)