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
use std::ops::Deref;

use async_trait::async_trait;
use bytes::BytesMut;
use fastwebsockets::{
	CloseCode, FragmentCollectorRead, Frame, OpCode, Payload, WebSocketError, WebSocketRead,
	WebSocketWrite,
};
use tokio::io::{AsyncRead, AsyncWrite};

use crate::{ws::LockedWebSocketWrite, WispError};

fn match_payload(payload: Payload<'_>) -> crate::ws::Payload<'_> {
	match payload {
		Payload::Bytes(x) => crate::ws::Payload::Bytes(x),
		Payload::Owned(x) => crate::ws::Payload::Bytes(BytesMut::from(x.deref())),
		Payload::BorrowedMut(x) => crate::ws::Payload::Borrowed(&*x),
		Payload::Borrowed(x) => crate::ws::Payload::Borrowed(x),
	}
}

fn match_payload_reverse(payload: crate::ws::Payload<'_>) -> Payload<'_> {
	match payload {
		crate::ws::Payload::Bytes(x) => Payload::Bytes(x),
		crate::ws::Payload::Borrowed(x) => Payload::Borrowed(x),
	}
}

impl From<OpCode> for crate::ws::OpCode {
	fn from(opcode: OpCode) -> Self {
		use OpCode::*;
		match opcode {
			Continuation => {
				unreachable!("continuation should never be recieved when using a fragmentcollector")
			}
			Text => Self::Text,
			Binary => Self::Binary,
			Close => Self::Close,
			Ping => Self::Ping,
			Pong => Self::Pong,
		}
	}
}

impl<'a> From<Frame<'a>> for crate::ws::Frame<'a> {
	fn from(frame: Frame<'a>) -> Self {
		Self {
			finished: frame.fin,
			opcode: frame.opcode.into(),
			payload: match_payload(frame.payload),
		}
	}
}

impl<'a> From<crate::ws::Frame<'a>> for Frame<'a> {
	fn from(frame: crate::ws::Frame<'a>) -> Self {
		use crate::ws::OpCode::*;
		let payload = match_payload_reverse(frame.payload);
		match frame.opcode {
			Text => Self::text(payload),
			Binary => Self::binary(payload),
			Close => Self::close_raw(payload),
			Ping => Self::new(true, OpCode::Ping, None, payload),
			Pong => Self::pong(payload),
		}
	}
}

impl From<WebSocketError> for crate::WispError {
	fn from(err: WebSocketError) -> Self {
		if let WebSocketError::ConnectionClosed = err {
			Self::WsImplSocketClosed
		} else {
			Self::WsImplError(Box::new(err))
		}
	}
}

#[async_trait]
impl<S: AsyncRead + Unpin + Send> crate::ws::WebSocketRead for FragmentCollectorRead<S> {
	async fn wisp_read_frame(
		&mut self,
		tx: &LockedWebSocketWrite,
	) -> Result<crate::ws::Frame<'static>, WispError> {
		Ok(self
			.read_frame(&mut |frame| async { tx.write_frame(frame.into()).await })
			.await?
			.into())
	}
}

#[async_trait]
impl<S: AsyncRead + Unpin + Send> crate::ws::WebSocketRead for WebSocketRead<S> {
	async fn wisp_read_frame(
		&mut self,
		tx: &LockedWebSocketWrite,
	) -> Result<crate::ws::Frame<'static>, WispError> {
		let mut frame = self
			.read_frame(&mut |frame| async { tx.write_frame(frame.into()).await })
			.await?;

		if frame.opcode == OpCode::Continuation {
			return Err(WispError::WsImplError(Box::new(
				WebSocketError::InvalidContinuationFrame,
			)));
		}

		let mut buf = BytesMut::from(frame.payload);
		let opcode = frame.opcode;

		while !frame.fin {
			frame = self
				.read_frame(&mut |frame| async { tx.write_frame(frame.into()).await })
				.await?;

			if frame.opcode != OpCode::Continuation {
				return Err(WispError::WsImplError(Box::new(
					WebSocketError::InvalidContinuationFrame,
				)));
			}

			buf.extend_from_slice(&frame.payload);
		}

		Ok(crate::ws::Frame {
			opcode: opcode.into(),
			payload: crate::ws::Payload::Bytes(buf),
			finished: frame.fin,
		})
	}

	async fn wisp_read_split(
		&mut self,
		tx: &LockedWebSocketWrite,
	) -> Result<(crate::ws::Frame<'static>, Option<crate::ws::Frame<'static>>), WispError> {
		let mut frame_cnt = 1;
		let mut frame = self
			.read_frame(&mut |frame| async { tx.write_frame(frame.into()).await })
			.await?;
		let mut extra_frame = None;

		if frame.opcode == OpCode::Continuation {
			return Err(WispError::WsImplError(Box::new(
				WebSocketError::InvalidContinuationFrame,
			)));
		}

		let mut buf = BytesMut::from(frame.payload);
		let opcode = frame.opcode;

		while !frame.fin {
			frame = self
				.read_frame(&mut |frame| async { tx.write_frame(frame.into()).await })
				.await?;

			if frame.opcode != OpCode::Continuation {
				return Err(WispError::WsImplError(Box::new(
					WebSocketError::InvalidContinuationFrame,
				)));
			}
			if frame_cnt == 1 {
				let payload = BytesMut::from(frame.payload);
				extra_frame = Some(crate::ws::Frame {
					opcode: opcode.into(),
					payload: crate::ws::Payload::Bytes(payload),
					finished: true,
				});
			} else if frame_cnt == 2 {
				let extra_payload = extra_frame.take().unwrap().payload;
				buf.extend_from_slice(&extra_payload);
				buf.extend_from_slice(&frame.payload);
			} else {
				buf.extend_from_slice(&frame.payload);
			}
			frame_cnt += 1;
		}

		Ok((
			crate::ws::Frame {
				opcode: opcode.into(),
				payload: crate::ws::Payload::Bytes(buf),
				finished: frame.fin,
			},
			extra_frame,
		))
	}
}

#[async_trait]
impl<S: AsyncWrite + Unpin + Send> crate::ws::WebSocketWrite for WebSocketWrite<S> {
	async fn wisp_write_frame(&mut self, frame: crate::ws::Frame<'_>) -> Result<(), WispError> {
		self.write_frame(frame.into()).await.map_err(|e| e.into())
	}

	async fn wisp_write_split(
		&mut self,
		header: crate::ws::Frame<'_>,
		body: crate::ws::Frame<'_>,
	) -> Result<(), WispError> {
		let mut header = Frame::from(header);
		header.fin = false;
		self.write_frame(header).await?;

		let mut body = Frame::from(body);
		body.opcode = OpCode::Continuation;
		self.write_frame(body).await?;

		Ok(())
	}

	async fn wisp_close(&mut self) -> Result<(), WispError> {
		self.write_frame(Frame::close(CloseCode::Normal.into(), b""))
			.await
			.map_err(|e| e.into())
	}
}