Skip to content

Commit c01e04e

Browse files
feat: unrecognized enum values null/default bug (#738)
Signed-off-by: Anthony Petrov <anthony@swirldslabs.com>
1 parent b8a49b0 commit c01e04e

File tree

2 files changed

+18
-1
lines changed

2 files changed

+18
-1
lines changed

pbj-core/pbj-compiler/src/main/java/com/hedera/pbj/compiler/impl/generators/EnumGenerator.java

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -234,7 +234,10 @@ public String protoName() {
234234
* @return enum for matching ordinal, or UNRECOGNIZED/UNSET value
235235
*/
236236
public static $enumName fromObject(Object obj) {
237-
if (obj instanceof $enumName pbjEnum) {
237+
if (obj == null) {
238+
// Per protobuf spec, must return the default (protoOrdinal 0) when unset (null):
239+
return fromProtobufOrdinal(0);
240+
} else if (obj instanceof $enumName pbjEnum) {
238241
return pbjEnum;
239242
} else {
240243
return $enumName.$unknownValue;

pbj-integration-tests/src/test/java/com/hedera/pbj/integration/test/UnrecognizedEnumTest.java

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -54,4 +54,18 @@ public void unrecognizedEnumListTest() throws Exception {
5454
assertEquals(
5555
List.of(PbjEnumUnrecognized2.A2, PbjEnumUnrecognized2.D2, PbjEnumUnrecognized2.B2), m22.enumList());
5656
}
57+
58+
@Test
59+
public void testDefaultValue() throws Exception {
60+
// This initializes the enum value in the model to be literally `null` rather than the default:
61+
final MessageWithUnrecognizedEnum1 msg =
62+
MessageWithUnrecognizedEnum1.newBuilder().enumValue(null).build();
63+
64+
// However, reading it from the model MUST return the "protobuf default" value, which is at the protoOrdinal 0:
65+
assertEquals(PbjEnumUnrecognized1.A1, msg.enumValue());
66+
67+
// Play the same trick using the ctor:
68+
final MessageWithUnrecognizedEnum1 msg2 = new MessageWithUnrecognizedEnum1(null, null);
69+
assertEquals(PbjEnumUnrecognized1.A1, msg2.enumValue());
70+
}
5771
}

0 commit comments

Comments
 (0)