Skip to content

Commit

Permalink
Skipped encoding of empty packed collections in protobuf
Browse files Browse the repository at this point in the history
Resolves #2906
  • Loading branch information
shanshin committed Jan 21, 2025
1 parent f9f160a commit 1a40ecc
Show file tree
Hide file tree
Showing 2 changed files with 38 additions and 0 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,12 @@ internal class PackedArrayEncoder(
throw SerializationException("Packing only supports primitive number types")
}

override fun endEncode(descriptor: SerialDescriptor) {
if (stream.size() > 0) {
super.endEncode(descriptor)
}
}

override fun encodeTaggedString(tag: ProtoDesc, value: String) {
throw SerializationException("Packing only supports primitive number types")
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -51,6 +51,12 @@ class PackedArraySerializerTest {
val s: List<String>
)

@Serializable
data class PackedIntCarrier(
@ProtoPacked
val i: List<Int>
)

/**
* Test that when packing is specified the array is encoded as packed
*/
Expand Down Expand Up @@ -132,4 +138,30 @@ class PackedArraySerializerTest {
assertEquals(listData, decoded)
}

/**
* Test that empty packed repeated field is not presented in a message.
*/
@Test
fun testEncodeEmptyPackedList() {
val obj = PackedIntCarrier(emptyList())
val encoded = ProtoBuf.encodeToHexString(obj)
assertEquals("", encoded)
}

/**
* Test that absence of packed field and explicit presence with a length 0 are decoded an empty list.
*/
@Test
fun testDecodeEmptyPackedList() {
val explicitlyEmpty = "0a00"

val obj = PackedIntCarrier(emptyList())

val decodedExplicitEmpty = ProtoBuf.decodeFromHexString<PackedIntCarrier>(explicitlyEmpty)
val decodedAbsentField = ProtoBuf.decodeFromHexString<PackedIntCarrier>("")

assertEquals(obj, decodedExplicitEmpty)
assertEquals(obj, decodedAbsentField)
}

}

0 comments on commit 1a40ecc

Please sign in to comment.