Skip to content

Commit 5be24d6

Browse files
committed
allow empty strings to be written to protobuf
1 parent a27cc63 commit 5be24d6

File tree

2 files changed

+57
-1
lines changed

2 files changed

+57
-1
lines changed

exporters/common/src/main/java/io/opentelemetry/exporter/internal/marshal/Serializer.java

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -254,7 +254,11 @@ public void serializeRepeatedString(ProtoFieldInfo field, byte[][] utf8Bytes) th
254254
*/
255255
public void serializeStringWithContext(
256256
ProtoFieldInfo field, @Nullable String string, MarshalerContext context) throws IOException {
257-
if (string == null || string.isEmpty()) {
257+
if (string == null) {
258+
return;
259+
}
260+
if (string.isEmpty()) {
261+
writeString(field, string, 0, context);
258262
return;
259263
}
260264
if (context.marshalStringNoAllocation()) {
Lines changed: 52 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,52 @@
1+
package io.opentelemetry.exporter.internal.marshal;
2+
3+
import static java.nio.charset.StandardCharsets.UTF_8;
4+
import static org.assertj.core.api.AssertionsForClassTypes.assertThat;
5+
6+
import java.io.ByteArrayOutputStream;
7+
import org.junit.jupiter.api.Test;
8+
9+
class ProtoSerializerTest {
10+
11+
@Test
12+
void testSerializeStringWithContext() throws Exception {
13+
String value = "mystring";
14+
ByteArrayOutputStream out = new ByteArrayOutputStream();
15+
16+
ProtoSerializer serializer = new ProtoSerializer(out);
17+
18+
ProtoFieldInfo field = ProtoFieldInfo.create(1, 10, "stringValue");
19+
MarshalerContext context = new MarshalerContext();
20+
context.setSize(0, value.length());
21+
serializer.serializeStringWithContext(field, value, context);
22+
serializer.close();
23+
24+
byte[] result = out.toByteArray();
25+
assertThat(result.length).isEqualTo(10); // one byte tag, one byte length, rest string
26+
assertThat((int)result[0]).isEqualTo(field.getTag());
27+
assertThat((int)result[1]).isEqualTo(value.length());
28+
assertThat(new String(result, 2, result.length-2, UTF_8)).isEqualTo(value);
29+
}
30+
31+
@Test
32+
void testSerializeEmptyStringWithContext() throws Exception {
33+
String value = "";
34+
ByteArrayOutputStream out = new ByteArrayOutputStream();
35+
36+
ProtoSerializer serializer = new ProtoSerializer(out);
37+
38+
ProtoFieldInfo field = ProtoFieldInfo.create(1, 10, "stringValue");
39+
MarshalerContext context = new MarshalerContext();
40+
context.setSize(0, 0);
41+
42+
serializer.serializeStringWithContext(field, value, context);
43+
serializer.close();
44+
45+
byte[] result = out.toByteArray();
46+
47+
assertThat(result.length).isEqualTo(2);
48+
assertThat((int)result[0]).isEqualTo(field.getTag());
49+
assertThat((int)result[1]).isEqualTo(0);
50+
}
51+
52+
}

0 commit comments

Comments
 (0)