Scoop API

scoop:scoop.http:0.1.0

src/sse/output.scoop

Selected production source · src/sse/output.scoop

1package scoop.http
3internal enum SseOutputPhase { Prefix, Value, NextField, End, Finished }
5internal class SseOutput(private var fields: Array<SseOutputField>) {
6 private var phase: SseOutputPhase = if (fields.size == 0L) SseOutputPhase.End else SseOutputPhase.Prefix
7 private var field: Long = 0L
8 private var prefixAt: Long = 0L
9 private var input: Iterator<Char>? = if (fields.size == 0L) None else Some(fields[0L].value.iterator())
10 private var skipLf: Boolean = false
11 private var pending: Array<Byte> = []
12 private var pendingAt: Long = 0L
13 val finished: Boolean get() = phase == SseOutputPhase.Finished && pendingAt == pending.size
15 fun nextByte(): Byte? {
16 if (pendingAt < pending.size) { val value = pending[pendingAt]; pendingAt += 1L; return Some(value) }
17 while (true) {
18 when (phase) {
19 case Prefix -> {
20 val prefix = fields[field].prefix
21 if (prefixAt < prefix.size) { val value = prefix[prefixAt]; prefixAt += 1L; return Some(value) }
22 phase = SseOutputPhase.Value
23 }
24 case Value -> {
25 val next = input!!.next()
26 if (next == None) { phase = SseOutputPhase.NextField; return Some(10.toByte()) }
27 val value = next!!
28 if (skipLf) { skipLf = false; if (value == '\n') continue }
29 if (value == '\r' || value == '\n') {
30 skipLf = value == '\r'
31 prefixAt = 0L
32 phase = SseOutputPhase.Prefix
33 return Some(10.toByte())
34 }
35 if (value.code < 128) return Some(value.code.toByte())
36 pending = value.toString().toByteArray()
37 pendingAt = 1L
38 return Some(pending[0L])
39 }
40 case NextField -> {
41 field += 1L
42 if (field == fields.size) phase = SseOutputPhase.End
43 else {
44 input = Some(fields[field].value.iterator())
45 prefixAt = 0L; skipLf = false
46 phase = SseOutputPhase.Prefix
47 }
48 }
49 case End -> { phase = SseOutputPhase.Finished; return Some(10.toByte()) }
50 case Finished -> return None
51 }
52 }
53 }
55 fun close() { fields = []; input = None; pending = []; pendingAt = 0L }