kotlinx.serialization icon indicating copy to clipboard operation
kotlinx.serialization copied to clipboard

Cbor encoder/decoder treats Unit as an empty array

Open tomaszbabiuk opened this issue 10 months ago • 1 comments

Describe the bug Cbor encoder/decoder treats Unit as an empty array. That means you get an empty array output every time a unit appears in the serialization chain. It is problematic when using the kotlin-encoded payloads with other CBOR libraries.

To Reproduce

`@OptIn(ExperimentalStdlibApi::class, ExperimentalSerializationApi::class)
@Test
fun `Cbor handles unit when definite length encoding is enabled`() {
    val cborWithByteString = Cbor {
        useDefiniteLengthEncoding = true

    }
    val encoded = cborWithByteString.encodeToByteArray(Unit.serializer(), Unit).toHexString()
    assertEquals("", encoded) //error: actual is a0
}

@OptIn(ExperimentalStdlibApi::class, ExperimentalSerializationApi::class)
@Test
fun `Cbor handles unit when definite length encoding is disabled`() {
    val cborWithByteString = Cbor {
        useDefiniteLengthEncoding = false
    }
    val encoded = cborWithByteString.encodeToByteArray(Unit.serializer(), Unit).toHexString()
    assertEquals("", encoded) //error: actual is bfff
}`

Expected behavior The CBOR encoder should encode Unit as an empty bytestring. The CBOR decoder should decode UNIT from an empty bytestring.

Environment

  • Kotlin version: 2.1.10
  • Library version: 1.8.0
  • Kotlin platforms: JVM
  • Gradle version: 8.10
  • IDE version (if bug is related to the IDE) - n/A
  • Other relevant context [e.g. OS version, JRE version, ... ] - n/A

tomaszbabiuk avatar Feb 10 '25 09:02 tomaszbabiuk

Any object in Kotlin is encoded as beginStructure + endStructure, so the same empty array would be produced for e.g. @Serializable object Foo. It is required to determine whether the object was present in the input — if we have @Serializable class Bar(val foo: Foo), and we get the empty input, should we report an error about missing the foo property or deserialize successfully?

sandwwraith avatar Feb 13 '25 11:02 sandwwraith