/
WebSocketInboundStream.swift
64 lines (57 loc) · 1.88 KB
/
WebSocketInboundStream.swift
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
//===----------------------------------------------------------------------===//
//
// This source file is part of the Hummingbird server framework project
//
// Copyright (c) 2023-2024 the Hummingbird authors
// Licensed under Apache License v2.0
//
// See LICENSE.txt for license information
// See hummingbird/CONTRIBUTORS.txt for the list of Hummingbird authors
//
// SPDX-License-Identifier: Apache-2.0
//
//===----------------------------------------------------------------------===//
import AsyncAlgorithms
import NIOCore
import NIOWebSocket
/// Inbound websocket data AsyncSequence
public typealias WebSocketInboundStream = AsyncChannel<WebSocketDataFrame>
/// Enumeration holding WebSocket data
public enum WebSocketDataFrame: Equatable, Sendable, CustomStringConvertible, CustomDebugStringConvertible {
case text(String)
case binary(ByteBuffer)
init?(frame: WebSocketFrame) {
switch frame.opcode {
case .text:
self = .text(String(buffer: frame.unmaskedData))
case .binary:
self = .binary(frame.unmaskedData)
default:
return nil
}
}
public var webSocketFrame: WebSocketFrame {
switch self {
case .text(let string):
return .init(fin: true, opcode: .text, data: ByteBuffer(string: string))
case .binary(let buffer):
return .init(fin: true, opcode: .binary, data: buffer)
}
}
public var description: String {
switch self {
case .text(let string):
return "string(\"\(string)\")"
case .binary(let buffer):
return "binary(\(buffer.description))"
}
}
public var debugDescription: String {
switch self {
case .text(let string):
return "string(\"\(string)\")"
case .binary(let buffer):
return "binary(\(buffer.debugDescription))"
}
}
}