Skip to content

Commit

Permalink
fix: optimizations reducing heap usage in MsgPackDataOutputBuffer
Browse files Browse the repository at this point in the history
  • Loading branch information
martin-dd authored and esensar committed Dec 23, 2024
1 parent 5fa52b3 commit d52440d
Showing 1 changed file with 24 additions and 5 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -5,15 +5,34 @@ interface MsgPackDataBuffer {
}

class MsgPackDataOutputBuffer() : MsgPackDataBuffer {
private val bytes = mutableListOf<Byte>()
private val byteArrays = mutableListOf<ByteArray>()

fun add(byte: Byte) = bytes.add(byte)
fun add(byte: Byte) {
byteArrays.add(ByteArray(1) { byte })
}

fun addAll(bytes: List<Byte>) = this.bytes.addAll(bytes)
fun addAll(bytes: List<Byte>) {
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 {
Expand Down

0 comments on commit d52440d

Please sign in to comment.