scoop:scoop.http:0.1.0
src/websocket/frames/close.scoop
Selected production source · src/websocket/frames/close.scoop
1
package scoop.http3
import scoop.bytes.ByteArrayBuilder4
import scoop.charset.*6
/**7
* A validated optional close status and UTF-8 reason. Serialization enforces legal wire codes and8
* the control-frame payload limit.9
*/10
public class WebSocketClose public constructor(11
/**12
* The optional wire close status code.13
*/14
public val code: UInt? = None,15
/**16
* The close reason text, requiring a status code when nonempty.17
*/18
public val reason: String = "") {19
init {20
if (code == None && reason.byteLength > 0L)21
throw IllegalArgumentException(Some("WebSocket close reason requires a code"))22
if (code != None && !webSocketCloseCode(code!!)) throw IllegalArgumentException(Some("invalid WebSocket close code"))23
if (reason.byteLength > 123L) throw IllegalArgumentException(Some("WebSocket close reason exceeds 123 UTF-8 bytes"))24
}26
/**27
* Serializes a legal status and UTF-8 reason within the control-frame payload limit.28
*/29
public fun toByteArray(): Array<Byte> {30
val result = ByteArrayBuilder()31
when (code) {32
case Some(val value) -> {33
result.append((value shr 8L).toByte()).append((value and 255U).toByte())34
result.append(reason.toByteArray())35
}36
case None -> {}37
}38
return result.toByteArray()39
}41
/**42
* Parsing validated close-frame payloads.43
*/44
public companion object {45
/**46
* Validates payload length, close code, and UTF-8 reason, then returns the decoded close47
* value.48
*/49
public fun parse(data: List<Byte>): WebSocketClose {50
val bytes = data.toArray()51
if (bytes.size == 0L) return WebSocketClose()52
if (bytes.size == 1L || bytes.size > 125L) webSocketFrameError("invalid Close payload length")53
val code = (bytes[0L].toUByte().toUInt() shl 8L) or bytes[1L].toUByte().toUInt()54
val reason = try {55
Charset.Utf8.decode(Array<Byte>(bytes.size - 2L) { index -> bytes[index + 2L] },56
CharsetDecodeOptions(bom = CharsetBomPolicy.Preserve))57
} catch (error: CharsetException) { throw WebSocketFrameException(1007U, "invalid Close reason UTF-8", cause = Some(error)) }58
try { return WebSocketClose(Some(code), reason) }59
catch (_: IllegalArgumentException) { webSocketFrameError("invalid Close status code") }60
}61
}62
}64
private fun webSocketCloseCode(code: UInt): Boolean =65
(code >= 3000U && code <= 4999U) || code == 1000U || code == 1001U || code == 1002U || code == 1003U ||66
(code >= 1007U && code <= 1014U)