Scoop API

scoop:scoop.http.server:0.1.0

src/common.scoop

Selected production source · src/common.scoop

1package scoop.http.server
3import scoop.http.HttpField
5// Copies share the atomic state without another heap wrapper.
6internal struct ServerLock(val held: AtomicBoolean = AtomicBoolean(false)) {
7 private fun acquire() {
8 while (!held.compareAndSet(false, true, MemoryOrder.Acquire, MemoryOrder.Relaxed)) {}
9 }
11 private fun unlock() {
12 held.store(false, MemoryOrder.Release)
13 }
15 fun <T> withLock(block: () -> T): T {
16 acquire()
17 try {
18 return block()
19 }
20 finally {
21 unlock()
22 }
23 }
26internal fun field(name: String, value: String): HttpField =
27 HttpField(name.toByteArray(), value.toByteArray())
29internal fun <T> present(value: T?): Boolean =
30 when (value) {
31 case Some(_) -> true
32 case None -> false
33 }
35internal fun sameBytes(a: List<Byte>, b: List<Byte>): Boolean {
36 if (a.size != b.size)
37 return false
38 var index = 0L
39 while (index < a.size) {
40 if (a[index] != b[index])
41 return false
42 index += 1L
43 }
44 return true
47internal fun inputText(bytes: List<Byte>, location: String): String =
48 String.fromUtf8OrNone(bytes) ?: reject(400U, location + " must be UTF-8")
50internal fun reject(status: UInt, detail: String): Nothing =
51 throw HttpRejection(text(detail, status))
53/** An expected request rejection carrying the response selected by the application or extractor. */
54public class HttpRejection public constructor(
55 /** The response to execute in the current request pipeline. */
56 public val result: HttpResult,
57 /** The original input failure, when this rejection was produced by a decoder. */
58 public val cause: Throwable? = None
59): Exception(Some("HTTP request rejected"))
61/** A suspending endpoint returning a response description. */
62public typealias HttpHandler = suspend (HttpContext) -> HttpResult
64/** A single-use continuation that waits for the entire downstream response. */
65public typealias HttpNext = suspend () -> Unit
67/** A request middleware that either delegates once, responds, or throws. */
68public typealias HttpMiddleware = suspend (HttpContext, HttpNext) -> Unit