Scoop API

scoop:scoop.asyncio:0.1.0

src/read_all.scoop

Selected production source · src/read_all.scoop

1package scoop.asyncio
3import scoop.bytes.ByteArrayBuilder
4import scoop.platform.memory.NativeByteBuffer
6/**
7 * Reports that collection would exceed an explicit input byte limit.
8 */
9public 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 input
18 * exceeds maxBytes; the unlimited overload has no explicit byte limit.
19 */
20public suspend fun AsyncByteSource.readAllBytes(): Array<Byte> = collectBytes(this, None)
22/**
23 * Collects the remaining input until EOF. The limited overload throws ReadLimitException if input
24 * exceeds maxBytes; the unlimited overload has no explicit byte limit.
25 */
26public 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))
31private 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 8192L
35 val buffer = NativeByteBuffer.allocate(capacity)
36 try {
37 while (true) {
38 ensureActive()
39 buffer.clear()
40 var requested = capacity
41 if (maxBytes != None && maxBytes!! - bytes.size < requested)
42 requested = maxBytes!! - bytes.size + 1L
43 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() }