size
The number of readable bytes contained in 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
// Decode unsigned integer encoded using unsigned LEB128 format:
// https://en.wikipedia.org/wiki/LEB128#Unsigned_LEB128
fun Buffer.readULEB128UInt(): UInt {
var result = 0u
var shift = 0
var finished = false
while (!finished) { // Read until a number is fully fetched
if (exhausted()) throw EOFException()
// Pick the first segment and read from it either until the segment exhausted,
// or the number if finished.
UnsafeBufferOperations.readFromHead(this) { readCtx, segment ->
// Iterate over every byte contained in the segment
for (offset in 0..< segment.size) {
if (shift > 28) throw NumberFormatException("Overflow")
// Read the byte at the offset
val b = readCtx.getUnchecked(segment, offset)
val lsb = b.toUInt() and 0x7fu
result = result or (lsb shl shift)
shift += 7
if (b >= 0) {
finished = true
// We're done, return how many bytes were consumed from the segment
return@readFromHead offset + 1
}
}
// We read all the data from segment, but not finished yet.
// Return segment.size to indicate that the head segment was consumed in full.
segment.size
}
}
return result
}
val buffer = Buffer().also { it.write(ByteString(0xe5.toByte(), 0x8e.toByte(), 0x26)) }
assertEquals(624485u, buffer.readULEB128UInt())
assertTrue(buffer.exhausted())
buffer.write(ByteArray(8191))
buffer.write(ByteString(0xe5.toByte(), 0x8e.toByte(), 0x26))
buffer.skip(8191)
assertEquals(624485u, buffer.readULEB128UInt())
assertTrue(buffer.exhausted())
//sampleEnd
}