Skip to content

Commit 55f1192

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 e70bb5a commit 55f1192

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;
@@ -75,4 +76,15 @@ public void testIssue23() throws Exception {
7576
JSON_FORMATTER.merge(message, extensionRegistry, issue23Builder);
7677
assertThat("No unknown field 4", issue23Builder.getUnknownFields().hasField(4));
7778
}
79+
80+
@Test
81+
public void testSerializeToStringDoesNotRequireAnyEncoding() {
82+
String aChineseCharacter = "\u2F76";
83+
Charset encodingThatDoesntSupportChineseCharacters = Charset.forName("ASCII");
84+
JsonFormat jsonFomat = new JsonFormat();
85+
jsonFomat.setDefaultCharset(encodingThatDoesntSupportChineseCharacters);
86+
OneString message = OneString.newBuilder().setData(aChineseCharacter).build();
87+
88+
assertThat(jsonFomat.printToString(message), is("{\"data\": \""+aChineseCharacter + "\"}"));
89+
}
7890
}

0 commit comments

Comments
 (0)