remainingCapacity
The number of bytes that could be written into this segment.
Samples
import kotlinx.io.*
import kotlinx.io.bytestring.ByteString
import kotlinx.io.unsafe.UnsafeBufferOperations
import kotlinx.io.unsafe.withData
import kotlin.io.encoding.Base64
import kotlin.io.encoding.ExperimentalEncodingApi
import kotlin.math.min
import kotlin.random.Random
import kotlin.test.*
fun main() {
//sampleStart
// Encode multiple unsigned integers using unsigned LEB128 format:
// https://en.wikipedia.org/wiki/LEB128#Unsigned_LEB128
fun Buffer.writeULEB128(data: UIntArray) {
// Encode array length
writeULEB128(data.size.toUInt())
var index = 0
while (index < data.size) {
val value = data[index++]
// optimize small values encoding: anything below 127 will be encoded using a single byte anyway
if (value < 0x80u) {
// we need a space for a single byte, but if there's more - we'll try to fill it
UnsafeBufferOperations.writeToTail(this, 1) { ctx, seg ->
var bytesWritten = 0
ctx.setUnchecked(seg, bytesWritten++, value.toByte())
// let's save as much succeeding small values as possible
val remainingDataLength = data.size - index
val remainingCapacity = seg.remainingCapacity - 1
for (i in 0 until min(remainingDataLength, remainingCapacity)) {
val b = data[index]
if (b >= 0x80u) break
ctx.setUnchecked(seg, bytesWritten++, b.toByte())
index++
}
bytesWritten
}
} else {
writeULEB128(value)
}
}
}
val buffer = Buffer()
val data = UIntArray(10) { it.toUInt() }
buffer.writeULEB128(data)
assertEquals(ByteString(10, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9), buffer.readByteString())
//sampleEnd
}