Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Cbor encoder/decoder treats Unit as an empty array #2926

Open
tomaszbabiuk opened this issue Feb 10, 2025 · 1 comment
Open

Cbor encoder/decoder treats Unit as an empty array #2926

tomaszbabiuk opened this issue Feb 10, 2025 · 1 comment

Comments

@tomaszbabiuk
Copy link

tomaszbabiuk commented Feb 10, 2025

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
@sandwwraith
Copy link
Member

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?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

2 participants