Zhang Zihan
05/12/2024, 5:19 PMRawSource.readAtMostTo(sink, byteCount)
read at most 8192 bytes at a time? How to read more at once?Zhang Zihan
05/13/2024, 7:33 AMfun 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
}
Filipp Zhinkin
05/13/2024, 7:58 AMRawSource
, 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.Zhang Zihan
05/13/2024, 8:19 AMval 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!Filipp Zhinkin
05/13/2024, 9:00 AMThis is different fromPerhaps,and confuses me.FileInputStream.readNBytes(len)
kotlinx-io
should provide similar extension for reading into a buffer, especially given the readByteArray overload with exactly N bytes
semantics is already there.