I've got a few classes that are essentially wrappe...
# serialization
i
I've got a few classes that are essentially wrappers around `ByteArray`s, which I understand ProtoBuf serialization can serialize efficiently (rather than treating them as a list of bytes as the CBOR and Json do). I've been trying to create a custom KSerializer that will do this but keep getting runtime errors. In this case the wrapper class is called
ByteArraySegment
- this is what I've tried (I suspect the issue may be the
descriptor
I'm using, but I'm not sure how I should be doing it):
Copy code
@Serializer(forClass = ByteArraySegment::class)
companion object : KSerializer<ByteArraySegment> {
    override val descriptor: SerialDescriptor
        get() = ByteArraySerializer().descriptor

    override fun serialize(encoder: Encoder, value: ByteArraySegment) {
        encoder.encode(ByteArraySerializer(), value.asArray)
    }

    override fun deserialize(decoder: Decoder): ByteArraySegment {
        return ByteArraySegment(decoder.decode(ByteArraySerializer()))
    }
}
I've explained the problem in more detail on Reddit but nobody has been able to suggest a solution yet, would greatly appreciate any suggestions.
t
In CBOR, a
ByteArray
may be serialized as a "CBOR byte string": https://github.com/Kotlin/kotlinx.serialization/blob/master/docs/formats.md#byte-arrays-and-cbor-data-types It is written all at once rather than byte-by-byte. It is driven by an annotation. Perhaps a similar approach could be followed for what you're trying to accomplish? https://github.com/Kotlin/kotlinx.serialization/pull/898 It was integrated directly into the CBOR serialization, not sure how well it will translate to your custom serializer approach; but might provide some hints to help unblock you?