Skip to content

Commit b9216ca

Browse files
authored
Dictionaries keys must be appear in sorted order (required by bencode spec) (#11)
1 parent 6916cab commit b9216ca

File tree

3 files changed

+12
-4
lines changed

3 files changed

+12
-4
lines changed

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

Lines changed: 10 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -22,6 +22,8 @@
2222
import java.nio.ByteBuffer;
2323
import java.nio.charset.Charset;
2424
import java.util.Map;
25+
import java.util.SortedMap;
26+
import java.util.TreeMap;
2527

2628
/**
2729
* OutputStream for writing bencoded data.
@@ -184,8 +186,14 @@ private byte[] encode(final Iterable<?> l) throws IOException {
184186
return buffer.toByteArray();
185187
}
186188

187-
private byte[] encode(final Map<?, ?> map) throws IOException {
188-
if (map == null) throw new NullPointerException("map cannot be null");
189+
private byte[] encode(final Map<?, ?> m) throws IOException {
190+
if (m == null) throw new NullPointerException("m cannot be null");
191+
192+
Map<?, ?> map;
193+
if (!(m instanceof SortedMap<?, ?>))
194+
map = new TreeMap<>(m);
195+
else
196+
map = m;
189197

190198
ByteArrayOutputStream buffer = new ByteArrayOutputStream();
191199
buffer.write(Bencode.DICTIONARY);

src/test/java/com/dampcake/bencode/BencodeOutputStreamTest.java

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -181,7 +181,7 @@ public void testWriteDictionary() throws Exception {
181181
}});
182182
}});
183183

184-
assertEquals("d6:string5:value6:numberi123456e4:listl11:list-item-111:list-item-2e4:dictd3:1234:test3:4565:thingee",
184+
assertEquals("d4:dictd3:1234:test3:4565:thinge4:listl11:list-item-111:list-item-2e6:numberi123456e6:string5:valuee",
185185
new String(out.toByteArray(), instance.getCharset()));
186186
}
187187

src/test/java/com/dampcake/bencode/BencodeTest.java

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -415,7 +415,7 @@ public void testWriteDictionary() throws Exception {
415415
}});
416416
}});
417417

418-
assertEquals("d6:string5:value6:numberi123456e4:listl11:list-item-111:list-item-2e4:dictd3:1234:test3:4565:thingee",
418+
assertEquals("d4:dictd3:1234:test3:4565:thinge4:listl11:list-item-111:list-item-2e6:numberi123456e6:string5:valuee",
419419
new String(encoded, instance.getCharset()));
420420
}
421421

0 commit comments

Comments
 (0)