Hello! Can `RawSource.readAtMostTo(sink, byteCount...
# io
z
Hello! Can
RawSource.readAtMostTo(sink, byteCount)
read at most 8192 bytes at a time? How to read more at once?
I created a function to do this. Is there a simpler way?
Copy code
fun RawSource.readRecursivelyAtMostTo(sink: Buffer, byteCount: Long): Long {
    var read = 0L
    while (read != byteCount) {
        val count = readAtMostTo(sink, byteCount)
        read += count
        if (count == -1L) {
            if (read == 0L)
                return -1L
            break
        }
    }
    return read
}
f
Hi! If you need to work with
RawSource
, there's no way to do that out of the box. I don't think a simpler way exists (however,
read
should only be incremented only after checking
count
value, otherwise for a source containing only a single byte, the implementation may return
-1
). Could you please elaborate on your particular use case? In scenarios where I personally stumbled the lack of a more exhaustive reading routine, it was usually fine to wrap a
RawSource
into a
Source
by calling
buffered()
, then fill the buffer using
require(byteCount)
and then processing data out of `Source`'s buffer.
z
@Filipp Zhinkin Use case:
Copy code
val path = Path("D:\\Pictures\\Pixiv\\73597952_p0.jpg")
val source = SystemFileSystem.source(path).buffered()
val buffer = Buffer()

val count = source.readAtMostTo(buffer, 16384)
println(count)
val count2 = source.readAtMostTo(buffer, 16384)
println(count2)

// 8192
// 8192
I expected to get 16384 bytes in one go, but it only returns 8192 every time. This is different from
FileInputStream.readNBytes(len)
and confuses me. Based on your reply, I discovered the
require()
and
request()
functions, which can solve this problem, thank you!
f
Thank you for details!
This is different from
FileInputStream.readNBytes(len)
and confuses me.
Perhaps,
kotlinx-io
should provide similar extension for reading into a buffer, especially given the readByteArray overload with
exactly N bytes
semantics is already there.