require

abstract fun require(byteCount: Long)(source)

Attempts to fill the buffer with at least byteCount bytes of data from the underlying source and throw EOFException when the source is exhausted before fulfilling the requirement.

If the buffer already contains required number of bytes then there will be no requests to the underlying source.

Parameters

byteCount

the number of bytes that the buffer should contain.

Throws

when the source is exhausted before the required bytes count could be read.

when the source is closed.

Samples

import kotlinx.io.*
import kotlin.test.*

fun main() { 
   //sampleStart 
   val singleByteSource = object : RawSource {
    private var exhausted = false
    override fun readAtMostTo(sink: Buffer, byteCount: Long): Long = when {
        byteCount == 0L -> 0L
        exhausted -> -1L
        else -> {
            exhausted = true
            sink.writeByte(42)
            1L
        }
    }

    override fun close() = Unit
}

val source = singleByteSource.buffered()

source.require(1)
// The require call already soaked all the data from the source
assertEquals(-1, singleByteSource.readAtMostTo(Buffer(), 1))
// There is only one byte, so we can't request more
assertFailsWith<EOFException> { source.require(2) }
// But we didn't consume single byte yet, so require(1) will succeed
source.require(1)
assertEquals(42, source.readByte())
assertFailsWith<EOFException> { source.require(1) } 
   //sampleEnd
}