ByteStringBuilder

class ByteStringBuilder(initialCapacity: Int = 0)(source)

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

initialCapacity

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
}

Constructors

Link copied to clipboard
constructor(initialCapacity: Int = 0)

Properties

Link copied to clipboard

The number of bytes this builder can store without an extension of an internal buffer.

Link copied to clipboard
val size: Int

The number of bytes being written to this builder.

Functions

Link copied to clipboard
fun append(byte: Byte)

Append a single byte to this builder.

fun append(array: ByteArray, startIndex: Int = 0, endIndex: Int = array.size)

Appends a subarray of array starting at startIndex and ending at endIndex to this builder.

Link copied to clipboard
fun ByteStringBuilder.append(vararg bytes: Byte)

Appends bytes to this builder.

Appends unsigned byte to this builder.

Appends a byte string to this builder.

Link copied to clipboard

Returns a new ByteString wrapping all bytes written to this builder.