Scoop API

scoop:scoop.http:0.1.0

src/ndjson/decoder.scoop

Selected production source · src/ndjson/decoder.scoop

1package scoop.http
3import scoop.platform.memory.NativeByteBuffer
5/** Incremental UTF-8 NDJSON record framing; JSON interpretation belongs to the caller. */
6public class NdjsonDecoder public constructor(maxRecordBytes: Long = 1048576L) : Closeable {
7 private val state = NdjsonState(maxRecordBytes)
8 private val busy = AtomicBoolean(false)
9 private var closed = false
10 private var parseFailure: Throwable? = None
12 init { if (maxRecordBytes < 0L) throw IllegalArgumentException(Some("negative NDJSON record limit")) }
14 public val isClosed: Boolean get() = closed
15 public val isFinished: Boolean get() = state.ended && !state.hasPending
16 public val failure: Throwable? get() = parseFailure
18 /** Consumes a prefix, stopping as soon as one record is ready to be removed. */
19 public fun receive(buffer: NativeByteBuffer, count: Long = buffer.readableBytes): Long = withUse {
20 requireOpen()
21 if (state.ended) throw IllegalStateException(Some("NDJSON input has ended"))
22 if (count < 0L) throw IllegalArgumentException(Some("negative NDJSON input count"))
23 if (count > buffer.readableBytes) throw IndexOutOfBoundsException()
24 if (count == 0L || state.hasPending) return@withUse 0L
25 @Unsafe {
26 val borrow = buffer.borrowReadable(count)
27 var consumed = 0L
28 try {
29 val pointer = borrow.pointer()!!
30 while (consumed < count && !state.hasPending) {
31 val byte = pointer.load(consumed)
32 consumed += 1L
33 state.accept(byte)
34 }
35 return@withUse consumed
36 } catch (error: Throwable) { fail(error); throw error }
37 finally { borrow.complete(consumed) }
38 }
39 }
41 /** Returns an exact record, including an empty string for an empty line. */
42 public fun nextRecord(): String? = withUse {
43 requireOpen()
44 val result = state.pending
45 state.pending = None
46 result
47 }
49 /** Delivers a final nonempty line even without a trailing LF; invalid UTF-8 still fails. */
50 public fun endInput() {
51 withUse {
52 requireOpen()
53 try { state.endInput() }
54 catch (error: Throwable) { fail(error); throw error }
55 Unit
56 }
57 }
59 public override fun close() {
60 withUse {
61 if (!closed) { closed = true; state.discard() }
62 Unit
63 }
64 }
66 private fun fail(error: Throwable) { parseFailure = Some(error); state.discard() }
68 private fun requireOpen() {
69 if (closed) throw IllegalStateException(Some("NDJSON decoder is closed"))
70 when (parseFailure) { case Some(_) -> throw IllegalStateException(Some("NDJSON decoder has failed")); case None -> {} }
71 }
73 private fun <T> withUse(block: () -> T): T {
74 if (!busy.compareAndSet(false, true)) throw IllegalStateException(Some("NDJSON decoder is already in use"))
75 try { return block() }
76 finally { busy.store(false) }
77 }