Skip to content

Commit 5981de5

Browse files
Properly encode multibyte codepoints (#12)
1 parent 6bf4039 commit 5981de5

File tree

2 files changed

+16
-2
lines changed

2 files changed

+16
-2
lines changed

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

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -144,9 +144,10 @@ private byte[] encode(final String s) throws IOException {
144144
if (s == null) throw new NullPointerException("s cannot be null");
145145

146146
ByteArrayOutputStream buffer = new ByteArrayOutputStream();
147-
buffer.write(Integer.toString(s.length()).getBytes(charset));
147+
byte[] bytes = s.getBytes(charset);
148+
buffer.write(Integer.toString(bytes.length).getBytes(charset));
148149
buffer.write(Bencode.SEPARATOR);
149-
buffer.write(s.getBytes(charset));
150+
buffer.write(bytes);
150151

151152
return buffer.toByteArray();
152153
}

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

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -127,6 +127,13 @@ public void testDecodeString() {
127127
assertEquals("Hello World!", decoded);
128128
}
129129

130+
@Test
131+
public void testDecodeStringMultiByteCodePoints() {
132+
String decoded = instance.decode("7:Garçon".getBytes(), Type.STRING);
133+
134+
assertEquals("Garçon", decoded);
135+
}
136+
130137
@Test
131138
public void testDecodeEmptyString() {
132139
String decoded = instance.decode("0:123".getBytes(), Type.STRING);
@@ -319,6 +326,12 @@ public void testWriteString() throws Exception {
319326
assertEquals("12:Hello World!", new String(encoded, instance.getCharset()));
320327
}
321328

329+
@Test
330+
public void testWriteStringMultiByteCodePoints() throws Exception {
331+
byte[] encoded = instance.encode("Garçon");
332+
333+
assertEquals("7:Garçon", new String(encoded, instance.getCharset()));
334+
}
322335
@Test
323336
public void testWriteStringEmpty() throws Exception {
324337
byte[] encoded = instance.encode("");

0 commit comments

Comments
 (0)