Skip to content

Commit e194003

Browse files
committed
Bugfix: Handle empty messages correctly.
1 parent d6cccd6 commit e194003

2 files changed

Lines changed: 18 additions & 1 deletion

File tree

src/main/java/com/muukong/protobuf/PBMessage.java

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -57,7 +57,7 @@ public String prettyPrint(String indent) {
5757
public byte[] serializeValue() {
5858

5959
if ( fields.size() == 0 ) { // Empty message
60-
return new byte[] { 0, 0, 0, 0, 0 };
60+
return new byte[0];
6161
}
6262

6363
List<Byte> result = new ArrayList<>();

src/test/java/com/muukong/protobuf/PBDisassemblerTest.java

Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -85,6 +85,23 @@ void emptyInput_producesEmptyMessage() {
8585
assertEquals("", pp(new byte[0]));
8686
}
8787

88+
@Test
89+
void emptyMessage_serializesToZeroBytes() {
90+
PBMessage empty = new PBDisassembler(new byte[0]).disassemble();
91+
assertArrayEquals(new byte[0], empty.serializeValue());
92+
}
93+
94+
@Test
95+
void emptySubMessage_roundTrip() {
96+
// A LEN field whose payload is an empty protobuf message (0 bytes).
97+
// Before the fix, PBMessage.serializeValue() returned 5 zero bytes for
98+
// empty messages, so this round-trip would produce a 5-byte payload instead.
99+
byte[] input = lenField(1, new byte[0]); // field 1, length 0 → empty string {""}
100+
// The disassembler treats a zero-length LEN as an empty string.
101+
// Serialising that PBString back must reproduce the original 2-byte encoding.
102+
assertArrayEquals(input, new PBDisassembler(input).disassemble().serializeValue());
103+
}
104+
88105
// -----------------------------------------------------------------------
89106
// VARINT fields
90107
// -----------------------------------------------------------------------

0 commit comments

Comments
 (0)