Scoop API

scoop:scoop.http:0.1.0

src/websocket/frames/utf8.scoop

Selected production source · src/websocket/frames/utf8.scoop

1package scoop.http
3import scoop.charset.*
4import scoop.platform.memory.NativeByteBuffer
6internal class WebSocketUtf8 private constructor(
7 private val engine: CharsetTranscoder, private val input: NativeByteBuffer, private val output: NativeByteBuffer
8) : Closeable {
9 fun receive(bytes: Array<Byte>) {
10 var offset = 0L
11 while (offset < bytes.size) {
12 input.clear()
13 val count = if (bytes.size - offset < input.capacity) bytes.size - offset else input.capacity
14 input.writeBytes(bytes, offset, count)
15 transfer(false)
16 if (input.readableBytes != 0L) throw IllegalStateException(Some("UTF-8 validator left unconsumed input"))
17 offset += count
18 }
19 }
21 fun finish() { input.clear(); transfer(true) }
23 private fun transfer(ending: Boolean) {
24 try {
25 while (true) {
26 output.clear()
27 val step = engine.process(input, output, ending)
28 if (step.state != CharsetState.NeedOutput) return
29 }
30 } catch (error: CharsetException) {
31 throw WebSocketFrameException(1007U, "invalid message UTF-8", cause = Some(error))
32 }
33 }
35 public override fun close() {
36 try { engine.close() }
37 finally { try { input.close() } finally { output.close() } }
38 }
40 companion object {
41 fun create(): WebSocketUtf8 {
42 val input = NativeByteBuffer.allocate(4096L)
43 try {
44 val output = NativeByteBuffer.allocate(4096L)
45 try {
46 val engine = CharsetTranscoder(Charset.Utf8, Charset.Utf8,
47 CharsetTranscodeOptions(decode = CharsetDecodeOptions(bom = CharsetBomPolicy.Preserve)))
48 return WebSocketUtf8(engine, input, output)
49 } catch (error: Throwable) { output.close(); throw error }
50 } catch (error: Throwable) { input.close(); throw error }
51 }
52 }