Open
Description
It is similar to ByteArray.inputStream()
in kotlin.io
package. It is commonly used, maybe it should be built into kotlinx-io
.
A simple implementation:
import kotlinx.io.Buffer
import kotlinx.io.RawSource
fun ByteArray.source(): RawSource = ByteArraySource(this)
internal class ByteArraySource(private val bytes: ByteArray) : RawSource {
private var position = 0
override fun readAtMostTo(sink: Buffer, byteCount: Long): Long {
if (byteCount == 0L) return 0L
require(byteCount >= 0) { "byteCount ($byteCount) < 0" }
val endPositionLong = minOf(position + byteCount, bytes.size.toLong())
val readByteCount = endPositionLong - position
if (readByteCount == 0L) return -1
val endPosition = endPositionLong.toInt()
sink.write(bytes, position, endPosition)
position = endPosition
return readByteCount
}
override fun close() {}
}
import kotlinx.io.Buffer
import kotlinx.io.RawSource
import kotlinx.io.bytestring.ByteString
import kotlinx.io.write
fun ByteString.source(): RawSource = ByteStringSource(this)
internal class ByteStringSource(private val byteString: ByteString) : RawSource {
private var position = 0
override fun readAtMostTo(sink: Buffer, byteCount: Long): Long {
if (byteCount == 0L) return 0L
require(byteCount >= 0) { "byteCount ($byteCount) < 0" }
val endPositionLong = minOf(position + byteCount, byteString.size.toLong())
val readByteCount = endPositionLong - position
if (readByteCount == 0L) return -1
val endPosition = endPositionLong.toInt()
sink.write(byteString, position, endPosition)
position = endPosition
return readByteCount
}
override fun close() {}
}