scoop:scoop.asyncio:0.1.0
src/read_all.scoop
Selected production source · src/read_all.scoop
1
package scoop.asyncio3
import scoop.bytes.ByteArrayBuilder4
import scoop.platform.memory.NativeByteBuffer6
/**7
* Reports that collection would exceed an explicit input byte limit.8
*/9
public class ReadLimitException public constructor(10
/**11
* The caller-supplied maximum number of collected bytes.12
*/13
public val maxBytes: Long) :14
Exception(Some("input exceeds its explicit byte limit")) {}16
/**17
* Collects the remaining input until EOF. The limited overload throws ReadLimitException if input18
* exceeds maxBytes; the unlimited overload has no explicit byte limit.19
*/20
public suspend fun AsyncByteSource.readAllBytes(): Array<Byte> = collectBytes(this, None)22
/**23
* Collects the remaining input until EOF. The limited overload throws ReadLimitException if input24
* exceeds maxBytes; the unlimited overload has no explicit byte limit.25
*/26
public suspend fun AsyncByteSource.readAllBytes(maxBytes: Long): Array<Byte> {27
if (maxBytes < 0L) throw IllegalArgumentException(Some("negative input byte limit"))28
return collectBytes(this, Some(maxBytes))29
}31
private suspend fun collectBytes(source: AsyncByteSource, maxBytes: Long?): Array<Byte> {32
ensureActive()33
val bytes = ByteArrayBuilder()34
val capacity = if (maxBytes != None && maxBytes!! < 8192L) maxBytes!! + 1L else 8192L35
val buffer = NativeByteBuffer.allocate(capacity)36
try {37
while (true) {38
ensureActive()39
buffer.clear()40
var requested = capacity41
if (maxBytes != None && maxBytes!! - bytes.size < requested)42
requested = maxBytes!! - bytes.size + 1L43
val count = source.readInto(buffer, requested)44
requireProgress(count, requested)45
ensureActive()46
if (count == 0L) return bytes.toByteArray()47
if (maxBytes != None && count > maxBytes!! - bytes.size) throw ReadLimitException(maxBytes!!)48
bytes.append(buffer.readBytes(count))49
}50
} finally { buffer.close() }51
}