edenman
12/06/2024, 7:02 PMedenman
12/06/2024, 7:03 PMedenman
12/06/2024, 7:20 PMedenman
12/06/2024, 7:39 PMprivate fun readChunk(from: Source, buffer: Buffer, chunkSize: Long): ByteArray? {
var numBytesRead = 0L
while (numBytesRead != -1L && numBytesRead != chunkSize && !from.exhausted()) {
val read = from.readAtMostTo(sink = buffer, byteCount = chunkSize - numBytesRead)
if (read == -1L) {
return null
}
numBytesRead += read
}
if (from.exhausted() && numBytesRead == 0L) {
return null
}
return buffer.readByteArray()
}
edenman
12/06/2024, 7:39 PMFilipp Zhinkin
12/06/2024, 9:07 PMSource
has readTo function which reads exactly N bytes into a sink (which could be a Buffer
).
And if all you need is an array of bytes, readByteArray(byteCount: Int) should also read exactly byteCount
bytes.
You can always combine them with Source.request(byteCount: Long) to make sure that the source has the whole chunk. Something like:
private fun readChunk(from: Source, chunkSize: Long): ByteArray? {
require(chunkSize in 0..Int.MAX_VALUE)
return when {
from.request(chunkSize) -> from.readByteArray(chunkSize.toInt())
from.exhausted() -> null
else -> from.readByteArray()
}
}
edenman
12/06/2024, 9:19 PMedenman
12/06/2024, 9:19 PM