Skip to content

Function wrapping ByteArray/ByteString as RawSource #439

@zhangzih4n

Description

@zhangzih4n

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() {}
}

Metadata

Metadata

Assignees

No one assigned

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions