Skip to content

Commit

Permalink
Fix negative enums in protobuf not serializing & de-serializing (#2400)
Browse files Browse the repository at this point in the history
From language guide:

Enumerator constants must be in the range of a 32-bit integer. Since enum values use varint encoding on the wire, negative values are inefficient and thus not recommended (but still possible).
  • Loading branch information
Dogacel authored Aug 14, 2023
1 parent 1e88d42 commit a7109d8
Show file tree
Hide file tree
Showing 3 changed files with 4 additions and 3 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -80,7 +80,7 @@ internal open class ProtobufDecoder(

private fun findIndexByTag(descriptor: SerialDescriptor, protoTag: Int): Int {
// Fast-path: tags are incremental, 1-based
if (protoTag < descriptor.elementsCount) {
if (protoTag < descriptor.elementsCount && protoTag >= 0) {
val protoId = extractProtoId(descriptor, protoTag, true)
if (protoId == protoTag) return protoTag
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -162,11 +162,11 @@ class RandomTest : ShouldSpec() {
}
}

enum class KCoffee { AMERICANO, LATTE, CAPPUCCINO }
enum class KCoffee(val value: Int) { AMERICANO(0), LATTE(1), CAPPUCCINO(2), @ProtoNumber(-1) NO_COFFEE(-1) }

@Serializable
data class KTestEnum(@ProtoNumber(1) val a: KCoffee): IMessage {
override fun toProtobufMessage() = TestEnum.newBuilder().setA(TestEnum.Coffee.forNumber(a.ordinal)).build()
override fun toProtobufMessage() = TestEnum.newBuilder().setA(TestEnum.Coffee.forNumber(a.value)).build()

companion object : Gen<KTestEnum> {
override fun generate(): KTestEnum = KTestEnum(Gen.oneOf<KCoffee>().generate())
Expand Down
1 change: 1 addition & 0 deletions formats/protobuf/testProto/test_data.proto
Original file line number Diff line number Diff line change
Expand Up @@ -59,6 +59,7 @@ message TestEnum {
Americano = 0;
Latte = 1;
Capuccino = 2;
NoCoffee = -1;
}
required Coffee a = 1;
}
Expand Down

0 comments on commit a7109d8

Please sign in to comment.