Skip to content

Commit 6a1b6f8

Browse files
committed
Issue #35 - printToString doesn't encode to bytes
For any AbstractCharBasedFormatter, printToString can print directly to a String and not have to convert to bytes and back again. This avoids call to ByteArrayOutputStream.toString() at ProtobufFormatter:91 which uses JVM default encoding instead of ProtobufFormatter.defaultCharset. (I discovered this issue when trying to create JSON with a broad range of unicode characters on a machine where the default Charset did not cover the full Unicode range.
1 parent 44651c6 commit 6a1b6f8

File tree

2 files changed

+24
-0
lines changed

2 files changed

+24
-0
lines changed

src/main/java/com/googlecode/protobuf/format/AbstractCharBasedFormatter.java

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -46,6 +46,18 @@ public void print(UnknownFieldSet fields, OutputStream output, Charset cs)
4646

4747
abstract public void print(UnknownFieldSet fields, Appendable output) throws IOException;
4848

49+
@Override
50+
public String printToString(Message message) {
51+
StringBuilder output = new StringBuilder();
52+
try {
53+
print(message, output);
54+
} catch (IOException e) {
55+
throw new RuntimeException("Writing to a StringBuilder threw an IOException (should never happen).",
56+
e);
57+
}
58+
return output.toString();
59+
}
60+
4961
@Override
5062
public void merge(InputStream input, Charset cs,
5163
ExtensionRegistry extensionRegistry, Builder builder) throws IOException {

src/test/java/com/googlecode/protobuf/format/JsonFormatTest.java

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -9,6 +9,7 @@
99
import org.testng.annotations.Test;
1010
import org.testng.reporters.Files;
1111
import protobuf_unittest.UnittestProto;
12+
import protobuf_unittest.UnittestProto.OneString;
1213
import sun.nio.cs.StandardCharsets;
1314

1415
import java.io.IOException;
@@ -86,4 +87,15 @@ public void testDeserializeNullFieldFromJson() throws Exception {
8687
System.out.println(actual);
8788
assertThat(actual, equalTo(UnittestProto.TestNullField.newBuilder().build()));
8889
}
90+
91+
@Test
92+
public void testSerializeToStringDoesNotRequireAnyEncoding() {
93+
String aChineseCharacter = "\u2F76";
94+
Charset encodingThatDoesntSupportChineseCharacters = Charset.forName("ASCII");
95+
JsonFormat jsonFomat = new JsonFormat();
96+
jsonFomat.setDefaultCharset(encodingThatDoesntSupportChineseCharacters);
97+
OneString message = OneString.newBuilder().setData(aChineseCharacter).build();
98+
99+
assertThat(jsonFomat.printToString(message), is("{\"data\": \""+aChineseCharacter + "\"}"));
100+
}
89101
}

0 commit comments

Comments
 (0)