Scoop API

scoop:scoop.http:0.1.0

src/ndjson/state.scoop

Selected production source · src/ndjson/state.scoop

1package scoop.http
3import scoop.bytes.ByteArrayBuilder
5internal class NdjsonState(private val maximum: Long) {
6 private var bytes = ByteArrayBuilder()
7 private var carriageReturn = false
8 var pending: String? = None
9 var ended = false
10 val hasPending: Boolean get() = pending != None
12 fun accept(byte: Byte) {
13 if (carriageReturn && byte != 10.toByte())
14 throw NdjsonFramingException(LineEnding, bytes.size, "NDJSON carriage return requires a following line feed")
15 if (byte == 10.toByte()) { finishRecord(); return }
16 if (byte == 13.toByte()) { carriageReturn = true; return }
17 if (bytes.size == maximum) throw NdjsonFramingException(RecordBytes, bytes.size, "NDJSON record exceeds " + maximum.toString() + " bytes")
18 bytes.append(byte)
19 }
21 fun endInput() {
22 if (ended) return
23 if (carriageReturn) throw NdjsonFramingException(LineEnding, bytes.size, "NDJSON input ended after a carriage return")
24 if (bytes.size != 0L) finishRecord()
25 ended = true
26 }
28 fun discard() {
29 bytes = ByteArrayBuilder()
30 carriageReturn = false
31 pending = None
32 }
34 private fun finishRecord() {
35 pending = Some(String.fromUtf8(bytes.toByteArray()))
36 bytes.clear()
37 carriageReturn = false
38 }