Scoop API

scoop:scoop.http:0.1.0

src/sse/encoder.scoop

Selected production source · src/sse/encoder.scoop

1package scoop.http
3import scoop.platform.memory.NativeByteBuffer
5/** An incremental encoder for one SSE message or comment block, with bounded output state. */
6public class SseEncoder private constructor(private val output: SseOutput) : Closeable {
7 /** Retains an already validated message and begins before its first output byte. */
8 public constructor(message: SseMessage) : this(SseOutput(sseMessageFields(message))) {}
10 /** Constructs comment encoders without creating a dispatched data event. */
11 public companion object {
12 /** Encodes each normalized text line as a comment, followed by a blank line. */
13 public fun comment(text: String): SseEncoder =
14 SseEncoder(SseOutput([SseOutputField(": ".toByteArray(), text)]))
15 }
17 private val busy: AtomicBoolean = AtomicBoolean(false)
18 private var closed: Boolean = false
19 private var failed: Boolean = false
21 /** Whether every byte of the complete block has been written. */
22 public val isFinished: Boolean get() = output.finished
23 /** Whether local state has been explicitly released. */
24 public val isClosed: Boolean get() = closed
26 /** Writes a bounded prefix, allowing a short output even inside a UTF-8 scalar. */
27 public fun writeInto(buffer: NativeByteBuffer, count: Long = buffer.writableBytes): Long = withUse {
28 if (closed || failed) throw IllegalStateException(Some("SSE encoder is closed or failed"))
29 if (count < 0L) throw IllegalArgumentException(Some("negative SSE output count"))
30 if (count > buffer.writableBytes) throw IndexOutOfBoundsException()
31 if (count == 0L || output.finished) return@withUse 0L
32 @Unsafe {
33 val borrow = buffer.borrowWritable(count)
34 var written = 0L
35 try {
36 val pointer = borrow.pointer()!!
37 while (written < count) {
38 val value = output.nextByte()
39 if (value == None) break
40 pointer.store(written, value!!)
41 written += 1L
42 }
43 return@withUse written
44 } catch (error: Throwable) { failed = true; throw error }
45 finally { borrow.complete(written) }
46 }
47 }
49 /** Drops retained text without emitting bytes or closing the caller's buffer. */
50 public override fun close() { withUse { closed = true; output.close() } }
52 private fun <T> withUse(block: () -> T): T {
53 if (!busy.compareAndSet(false, true)) throw IllegalStateException(Some("SSE encoder is already in use"))
54 try { return block() }
55 finally { busy.store(false) }
56 }