diff --git a/serialization-msgpack/src/commonMain/kotlin/com.ensarsarajcic.kotlinx.serialization.msgpack/stream/MsgPackDataBuffer.kt b/serialization-msgpack/src/commonMain/kotlin/com.ensarsarajcic.kotlinx.serialization.msgpack/stream/MsgPackDataBuffer.kt index aef7b15..aaf6c7e 100644 --- a/serialization-msgpack/src/commonMain/kotlin/com.ensarsarajcic.kotlinx.serialization.msgpack/stream/MsgPackDataBuffer.kt +++ b/serialization-msgpack/src/commonMain/kotlin/com.ensarsarajcic.kotlinx.serialization.msgpack/stream/MsgPackDataBuffer.kt @@ -5,15 +5,34 @@ interface MsgPackDataBuffer { } class MsgPackDataOutputBuffer() : MsgPackDataBuffer { - private val bytes = mutableListOf() + private val byteArrays = mutableListOf() - fun add(byte: Byte) = bytes.add(byte) + fun add(byte: Byte) { + byteArrays.add(ByteArray(1) { byte }) + } - fun addAll(bytes: List) = this.bytes.addAll(bytes) + fun addAll(bytes: List) { + if (bytes.isNotEmpty()) { + byteArrays.add(bytes.toByteArray()) + } + } - fun addAll(bytes: ByteArray) = this.bytes.addAll(bytes.toList()) + fun addAll(bytes: ByteArray) { + if (bytes.isNotEmpty()) { + byteArrays.add(bytes) + } + } - override fun toByteArray() = bytes.toByteArray() + override fun toByteArray(): ByteArray { + val totalSize = byteArrays.sumOf { it.size } + val outputArray = ByteArray(totalSize) + var currentIndex = 0 + byteArrays.forEach { + it.copyInto(outputArray, currentIndex) + currentIndex += it.size + } + return outputArray + } } class MsgPackDataInputBuffer(private val byteArray: ByteArray) : MsgPackDataBuffer {