getByteString

fun ByteBuffer.getByteString(length: Int = remaining()): ByteString(source)

Reads length bytes of data from this ByteBuffer starting from the current position and wraps them into a new ByteString.

Upon successful execution, current position will advance by length.

Throws

when length has negative value or its value exceeds ByteBuffer.remaining

Samples

import kotlinx.io.bytestring.*
import java.nio.ByteBuffer
import java.nio.ReadOnlyBufferException
import kotlin.test.*

fun main() { 
   //sampleStart 
   val buffer = ByteBuffer.wrap("Hello World".encodeToByteArray())

// Consume the whole buffer
val byteString = buffer.getByteString()
assertEquals(0, buffer.remaining())
assertEquals("Hello World".encodeToByteString(), byteString)

// Reset the buffer
buffer.flip()
// Consume only first 5 bytes from the buffer
assertEquals("Hello".encodeToByteString(), buffer.getByteString(length = 5)) 
   //sampleEnd
}

Reads length bytes of data from this ByteBuffer starting from at index and wraps them into a new ByteString.

This function does not update ByteBuffer.position.

Throws

when at is negative, greater or equal to ByteBuffer.limit or at + length exceeds ByteBuffer.limit.

Samples

import kotlinx.io.bytestring.*
import java.nio.ByteBuffer
import java.nio.ReadOnlyBufferException
import kotlin.test.*

fun main() { 
   //sampleStart 
   val buffer = ByteBuffer.wrap("Hello World".encodeToByteArray())

// Read 2 bytes starting from offset 6
val byteString = buffer.getByteString(at = 6, length = 2)
// Buffer's position is not affected
assertEquals(11, buffer.remaining())
assertEquals(byteString, "Wo".encodeToByteString()) 
   //sampleEnd
}