Avoid extra allocations while encoding data as CBOR, using kotlinx.serialization

23 Views Asked by At

When using kotlinx.serialization and encoding data as JSON, it's possible to write serialized data directly into an OutputStream, via Json.encodeToStream(SerializationStrategy<T>, T, OutputStream).

Yet, with CBOR:

        <dependency>
            <groupId>org.jetbrains.kotlinx</groupId>
            <artifactId>kotlinx-serialization-cbor</artifactId>
        </dependency>

— only writing to or reading from a ByteArray (byte[] JVM type) seems possible (Cbor.encodeToByteArray(SerializationStrategy<T>, T): ByteArray), and the byte array returned gets allocated by the library itself, can't be supplied externally, nor can it be reused.

This leads to extra allocations and frequent OutOfMemoryError's when encoding large data hierarchies as CBOR, which never happens with JSON.

Using kotlinx.serialization, how do I encode my data into an OutputStream or a pre-allocated ByteBuffer?

0

There are 0 best solutions below