Scoop API

scoop:scoop.http.asyncio:0.1.0

src/ndjson/reader.scoop

Selected production source · src/ndjson/reader.scoop

1package scoop.http.asyncio
3import scoop.asyncio.*
4import scoop.http.NdjsonDecoder
5import scoop.platform.memory.NativeByteBuffer
7internal class NdjsonReader(source: AsyncByteSource, owner: AsyncCloseable?, loop: EventLoop,
8 val decoder: NdjsonDecoder, val input: NativeByteBuffer) {
9 val io = MessageIo<AsyncByteSource>(source, owner, loop) {
10 var failure = messageCleanup(None) { input.close() }
11 failure = messageCleanup(failure) { decoder.close() }
12 when (failure) { case Some(val error) -> throw error; case None -> {} }
13 }
15 suspend fun next(): String? = io.run({}) suspend { source -> readNext(source) }
17 private suspend fun readNext(source: AsyncByteSource): String? {
18 while (true) {
19 ensureActive()
20 when (decoder.nextRecord()) { case Some(val record) -> return Some(record); case None -> {} }
21 if (decoder.isFinished) return None
22 if (input.readableBytes > 0L) decoder.receive(input)
23 else {
24 input.clear()
25 val requested = input.writableBytes
26 val count = source.readInto(input, requested)
27 httpProgress(count, requested)
28 if (input.writePosition != count || input.readPosition != 0L)
29 throw IllegalStateException(Some("inconsistent NDJSON source progress"))
30 if (count == 0L) decoder.endInput()
31 }
32 }
33 }