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
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
//! Abstraction over WebSocket implementations.
//!
//! Use the [`fastwebsockets`] implementation of these traits as an example for implementing them
//! for other WebSocket implementations.
//!
//! [`fastwebsockets`]: https://github.com/MercuryWorkshop/epoxy-tls/blob/multiplexed/wisp/src/fastwebsockets.rs
use std::{ops::Deref, sync::Arc};

use crate::WispError;
use async_trait::async_trait;
use bytes::{Buf, BytesMut};
use futures::lock::Mutex;

/// Payload of the websocket frame.
#[derive(Debug)]
pub enum Payload<'a> {
	/// Borrowed payload. Currently used when writing data.
	Borrowed(&'a [u8]),
	/// BytesMut payload. Currently used when reading data.
	Bytes(BytesMut),
}

impl From<BytesMut> for Payload<'static> {
	fn from(value: BytesMut) -> Self {
		Self::Bytes(value)
	}
}

impl<'a> From<&'a [u8]> for Payload<'a> {
	fn from(value: &'a [u8]) -> Self {
		Self::Borrowed(value)
	}
}

impl Payload<'_> {
	/// Turn a Payload<'a> into a Payload<'static> by copying the data.
	pub fn into_owned(self) -> Self {
		match self {
			Self::Bytes(x) => Self::Bytes(x),
			Self::Borrowed(x) => Self::Bytes(BytesMut::from(x)),
		}
	}
}

impl From<Payload<'_>> for BytesMut {
	fn from(value: Payload<'_>) -> Self {
		match value {
			Payload::Bytes(x) => x,
			Payload::Borrowed(x) => x.into(),
		}
	}
}

impl Deref for Payload<'_> {
	type Target = [u8];
	fn deref(&self) -> &Self::Target {
		match self {
			Self::Bytes(x) => x.deref(),
			Self::Borrowed(x) => x,
		}
	}
}

impl Clone for Payload<'_> {
	fn clone(&self) -> Self {
		match self {
			Self::Bytes(x) => Self::Bytes(x.clone()),
			Self::Borrowed(x) => Self::Bytes(BytesMut::from(*x)),
		}
	}
}

impl Buf for Payload<'_> {
	fn remaining(&self) -> usize {
		match self {
			Self::Bytes(x) => x.remaining(),
			Self::Borrowed(x) => x.remaining(),
		}
	}

	fn chunk(&self) -> &[u8] {
		match self {
			Self::Bytes(x) => x.chunk(),
			Self::Borrowed(x) => x.chunk(),
		}
	}

	fn advance(&mut self, cnt: usize) {
		match self {
			Self::Bytes(x) => x.advance(cnt),
			Self::Borrowed(x) => x.advance(cnt),
		}
	}
}

/// Opcode of the WebSocket frame.
#[derive(Debug, PartialEq, Clone, Copy)]
pub enum OpCode {
	/// Text frame.
	Text,
	/// Binary frame.
	Binary,
	/// Close frame.
	Close,
	/// Ping frame.
	Ping,
	/// Pong frame.
	Pong,
}

/// WebSocket frame.
#[derive(Debug, Clone)]
pub struct Frame<'a> {
	/// Whether the frame is finished or not.
	pub finished: bool,
	/// Opcode of the WebSocket frame.
	pub opcode: OpCode,
	/// Payload of the WebSocket frame.
	pub payload: Payload<'a>,
}

impl<'a> Frame<'a> {
	/// Create a new text frame.
	pub fn text(payload: Payload<'a>) -> Self {
		Self {
			finished: true,
			opcode: OpCode::Text,
			payload,
		}
	}

	/// Create a new binary frame.
	pub fn binary(payload: Payload<'a>) -> Self {
		Self {
			finished: true,
			opcode: OpCode::Binary,
			payload,
		}
	}

	/// Create a new close frame.
	pub fn close(payload: Payload<'a>) -> Self {
		Self {
			finished: true,
			opcode: OpCode::Close,
			payload,
		}
	}
}

/// Generic WebSocket read trait.
#[async_trait]
pub trait WebSocketRead {
	/// Read a frame from the socket.
	async fn wisp_read_frame(
		&mut self,
		tx: &LockedWebSocketWrite,
	) -> Result<Frame<'static>, WispError>;

	/// Read a split frame from the socket.
	async fn wisp_read_split(
		&mut self,
		tx: &LockedWebSocketWrite,
	) -> Result<(Frame<'static>, Option<Frame<'static>>), WispError> {
		self.wisp_read_frame(tx).await.map(|x| (x, None))
	}
}

/// Generic WebSocket write trait.
#[async_trait]
pub trait WebSocketWrite {
	/// Write a frame to the socket.
	async fn wisp_write_frame(&mut self, frame: Frame<'_>) -> Result<(), WispError>;

	/// Close the socket.
	async fn wisp_close(&mut self) -> Result<(), WispError>;

	/// Write a split frame to the socket.
	async fn wisp_write_split(
		&mut self,
		header: Frame<'_>,
		body: Frame<'_>,
	) -> Result<(), WispError> {
		let mut payload = BytesMut::from(header.payload);
		payload.extend_from_slice(&body.payload);
		self.wisp_write_frame(Frame::binary(Payload::Bytes(payload)))
			.await
	}
}

/// Locked WebSocket.
#[derive(Clone)]
pub struct LockedWebSocketWrite(Arc<Mutex<Box<dyn WebSocketWrite + Send>>>);

impl LockedWebSocketWrite {
	/// Create a new locked websocket.
	pub fn new(ws: Box<dyn WebSocketWrite + Send>) -> Self {
		Self(Mutex::new(ws).into())
	}

	/// Write a frame to the websocket.
	pub async fn write_frame(&self, frame: Frame<'_>) -> Result<(), WispError> {
		self.0.lock().await.wisp_write_frame(frame).await
	}

	pub(crate) async fn write_split(
		&self,
		header: Frame<'_>,
		body: Frame<'_>,
	) -> Result<(), WispError> {
		self.0.lock().await.wisp_write_split(header, body).await
	}

	/// Close the websocket.
	pub async fn close(&self) -> Result<(), WispError> {
		self.0.lock().await.wisp_close().await
	}
}

pub(crate) struct AppendingWebSocketRead<R>(pub Option<Frame<'static>>, pub R)
where
	R: WebSocketRead + Send;

#[async_trait]
impl<R> WebSocketRead for AppendingWebSocketRead<R>
where
	R: WebSocketRead + Send,
{
	async fn wisp_read_frame(
		&mut self,
		tx: &LockedWebSocketWrite,
	) -> Result<Frame<'static>, WispError> {
		if let Some(x) = self.0.take() {
			return Ok(x);
		}
		self.1.wisp_read_frame(tx).await
	}

	async fn wisp_read_split(
		&mut self,
		tx: &LockedWebSocketWrite,
	) -> Result<(Frame<'static>, Option<Frame<'static>>), WispError> {
		if let Some(x) = self.0.take() {
			return Ok((x, None));
		}
		self.1.wisp_read_split(tx).await
	}
}