write
fun Sink.write(byteString: ByteString, startIndex: Int = 0, endIndex: Int = byteString.size)(source)
Writes subsequence of data from byteString starting at startIndex and ending at endIndex into a sink.
Parameters
byteString
the byte string whose subsequence should be written to a sink.
startIndex
the first index (inclusive) to copy data from the byteString.
endIndex
the last index (exclusive) to copy data from the byteString
Throws
when startIndex or endIndex is out of range of byteString indices.
when startIndex > endIndex
.
if the sink is closed.
Samples
import kotlinx.io.*
import kotlinx.io.bytestring.ByteString
import kotlinx.io.bytestring.encodeToByteString
import kotlin.test.Test
import kotlin.test.assertEquals
import kotlin.test.assertTrue
fun main() {
//sampleStart
val buffer = Buffer()
buffer.write(ByteString(1, 2, 3, 4))
assertEquals(4, buffer.size)
//sampleEnd
}
Read byteCount bytes from input into this buffer. Throws an exception when input is exhausted before reading byteCount bytes.
Parameters
input
the stream to read data from.
byteCount
the number of bytes read from input.
Throws
when byteCount is negative.
Samples
import kotlinx.io.*
import java.io.ByteArrayInputStream
import java.io.ByteArrayOutputStream
import java.nio.ByteBuffer
import java.util.zip.GZIPInputStream
import java.util.zip.GZIPOutputStream
import kotlin.test.Test
import kotlin.test.assertContentEquals
import kotlin.test.assertEquals
import kotlin.test.assertTrue
fun main() {
//sampleStart
val inputStream = ByteArrayInputStream("hello!".encodeToByteArray())
val buffer = Buffer()
buffer.write(inputStream, 5)
assertEquals("hello", buffer.readString())
//sampleEnd
}
Writes data from the source into this sink and returns the number of bytes written.
Parameters
source
the source to read from.
Throws
when the sink is closed.
Samples
import kotlinx.io.*
import java.io.ByteArrayInputStream
import java.io.ByteArrayOutputStream
import java.nio.ByteBuffer
import java.util.zip.GZIPInputStream
import java.util.zip.GZIPOutputStream
import kotlin.test.Test
import kotlin.test.assertContentEquals
import kotlin.test.assertEquals
import kotlin.test.assertTrue
fun main() {
//sampleStart
val buffer = Buffer()
val nioByteBuffer = ByteBuffer.allocate(1024)
buffer.writeString("hello")
val bytesRead = buffer.readAtMostTo(nioByteBuffer)
assertEquals(5, bytesRead)
assertEquals(5, nioByteBuffer.capacity() - nioByteBuffer.remaining())
nioByteBuffer.position(0)
nioByteBuffer.limit(5)
val bytesWrite = buffer.write(nioByteBuffer)
assertEquals(5, bytesWrite)
assertEquals("hello", buffer.readString())
//sampleEnd
}