Skip to content

Commit 1a40ecc

Browse files
committed
Skipped encoding of empty packed collections in protobuf
Resolves #2906
1 parent f9f160a commit 1a40ecc

File tree

2 files changed

+38
-0
lines changed

2 files changed

+38
-0
lines changed

formats/protobuf/commonMain/src/kotlinx/serialization/protobuf/internal/PackedArrayEncoder.kt

+6
Original file line numberDiff line numberDiff line change
@@ -25,6 +25,12 @@ internal class PackedArrayEncoder(
2525
throw SerializationException("Packing only supports primitive number types")
2626
}
2727

28+
override fun endEncode(descriptor: SerialDescriptor) {
29+
if (stream.size() > 0) {
30+
super.endEncode(descriptor)
31+
}
32+
}
33+
2834
override fun encodeTaggedString(tag: ProtoDesc, value: String) {
2935
throw SerializationException("Packing only supports primitive number types")
3036
}

formats/protobuf/commonTest/src/kotlinx/serialization/protobuf/PackedArraySerializerTest.kt

+32
Original file line numberDiff line numberDiff line change
@@ -51,6 +51,12 @@ class PackedArraySerializerTest {
5151
val s: List<String>
5252
)
5353

54+
@Serializable
55+
data class PackedIntCarrier(
56+
@ProtoPacked
57+
val i: List<Int>
58+
)
59+
5460
/**
5561
* Test that when packing is specified the array is encoded as packed
5662
*/
@@ -132,4 +138,30 @@ class PackedArraySerializerTest {
132138
assertEquals(listData, decoded)
133139
}
134140

141+
/**
142+
* Test that empty packed repeated field is not presented in a message.
143+
*/
144+
@Test
145+
fun testEncodeEmptyPackedList() {
146+
val obj = PackedIntCarrier(emptyList())
147+
val encoded = ProtoBuf.encodeToHexString(obj)
148+
assertEquals("", encoded)
149+
}
150+
151+
/**
152+
* Test that absence of packed field and explicit presence with a length 0 are decoded an empty list.
153+
*/
154+
@Test
155+
fun testDecodeEmptyPackedList() {
156+
val explicitlyEmpty = "0a00"
157+
158+
val obj = PackedIntCarrier(emptyList())
159+
160+
val decodedExplicitEmpty = ProtoBuf.decodeFromHexString<PackedIntCarrier>(explicitlyEmpty)
161+
val decodedAbsentField = ProtoBuf.decodeFromHexString<PackedIntCarrier>("")
162+
163+
assertEquals(obj, decodedExplicitEmpty)
164+
assertEquals(obj, decodedAbsentField)
165+
}
166+
135167
}

0 commit comments

Comments
 (0)