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.

when some I/O error occurs.

Samples

import kotlinx.io.*
import kotlinx.io.bytestring.ByteString
import kotlinx.io.bytestring.encodeToByteString
import kotlin.test.*

fun main() { 
   //sampleStart 
   val buffer = Buffer()

buffer.write(ByteString(1, 2, 3, 4))
assertEquals(4, buffer.size) 
   //sampleEnd
}
fun Buffer.write(input: InputStream, byteCount: Long): Buffer(source)

Reads 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 input exhausted before reading byteCount bytes from it.

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.*

fun main() { 
   //sampleStart 
   val inputStream = ByteArrayInputStream("hello!".encodeToByteArray())
val buffer = Buffer()

buffer.write(inputStream, 5)
assertEquals("hello", buffer.readString()) 
   //sampleEnd
}

fun Sink.write(source: ByteBuffer): Int(source)

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.

when some I/O error occurs.

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.*

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
}