ByteStringBuilder
A helper class facilitating ByteString construction.
A builder is characterized by the capacity - the number of bytes that an instance of builder can receive before extending an underlying byte sequence, and size - the number of bytes being written to the builder.
The builder avoids additional copies and allocations when size == capacity
when toByteString called, thus it's recommended to specify expected ByteString size as initialCapacity
when creating a builder.
When a builder runs out of available capacity, a new byte sequence with extended capacity will be allocated and previously written data will be copied into it.
Parameters
the initial size of an underlying byte sequence.
Samples
import kotlinx.io.bytestring.*
import kotlin.test.*
fun main() {
//sampleStart
val byteString = buildByteString {
append("hello".encodeToByteArray())
append(' '.code.toByte())
append("world".encodeToByteArray())
}
assertEquals("hello world".encodeToByteString(), byteString)
//sampleEnd
}
import kotlinx.io.bytestring.*
import kotlin.test.*
fun main() {
//sampleStart
val array = byteArrayOf(1, 2, 3, 4, 5, 6, 7)
val byteString = buildByteString(4) {
append(array, startIndex = 2, endIndex = 6)
// When the capacity (4 in this case) matches the number of bytes appended,
// then a ByteString will wrap builder's backing array without copying it.
assertEquals(capacity, size)
}
assertEquals(ByteString(3, 4, 5, 6), byteString)
//sampleEnd
}
Properties
Functions
Appends bytes to this builder.
Appends unsigned byte to this builder.
Appends a byte string to this builder.
Returns a new ByteString wrapping all bytes written to this builder.