move the wisp logic into wisp lib

This commit is contained in:
Toshit Chawda 2024-01-27 18:57:04 -08:00
parent 379e07d643
commit 2a5684192a
No known key found for this signature in database
GPG key ID: 91480ED99E2B3D9D
8 changed files with 314 additions and 198 deletions

View file

@ -1,30 +1,30 @@
use bytes::Bytes;
use fastwebsockets::{Payload, Frame, OpCode};
use fastwebsockets::{
FragmentCollectorRead, Frame, OpCode, Payload, WebSocketError, WebSocketWrite,
};
use tokio::io::{AsyncRead, AsyncWrite};
impl TryFrom<OpCode> for crate::ws::OpCode {
type Error = crate::WispError;
fn try_from(opcode: OpCode) -> Result<Self, Self::Error> {
impl From<OpCode> for crate::ws::OpCode {
fn from(opcode: OpCode) -> Self {
use OpCode::*;
match opcode {
Continuation => Err(Self::Error::WsImplNotSupported),
Text => Ok(Self::Text),
Binary => Ok(Self::Binary),
Close => Ok(Self::Close),
Ping => Err(Self::Error::WsImplNotSupported),
Pong => Err(Self::Error::WsImplNotSupported),
Continuation => unreachable!(),
Text => Self::Text,
Binary => Self::Binary,
Close => Self::Close,
Ping => Self::Ping,
Pong => Self::Pong,
}
}
}
impl TryFrom<Frame<'_>> for crate::ws::Frame {
type Error = crate::WispError;
fn try_from(mut frame: Frame) -> Result<Self, Self::Error> {
let opcode = frame.opcode.try_into()?;
Ok(Self {
impl From<Frame<'_>> for crate::ws::Frame {
fn from(mut frame: Frame) -> Self {
Self {
finished: frame.fin,
opcode,
opcode: frame.opcode.into(),
payload: Bytes::copy_from_slice(frame.payload.to_mut()),
})
}
}
}
@ -34,7 +34,38 @@ impl From<crate::ws::Frame> for Frame<'_> {
match frame.opcode {
Text => Self::text(Payload::Owned(frame.payload.to_vec())),
Binary => Self::binary(Payload::Owned(frame.payload.to_vec())),
Close => Self::close_raw(Payload::Owned(frame.payload.to_vec()))
Close => Self::close_raw(Payload::Owned(frame.payload.to_vec())),
Ping => Self::new(
true,
OpCode::Ping,
None,
Payload::Owned(frame.payload.to_vec()),
),
Pong => Self::pong(Payload::Owned(frame.payload.to_vec())),
}
}
}
impl From<WebSocketError> for crate::WispError {
fn from(err: WebSocketError) -> Self {
Self::WsImplError(Box::new(err))
}
}
impl<S: AsyncRead + Unpin> crate::ws::WebSocketRead for FragmentCollectorRead<S> {
async fn wisp_read_frame(
&mut self,
tx: &mut crate::ws::LockedWebSocketWrite<impl crate::ws::WebSocketWrite>,
) -> Result<crate::ws::Frame, crate::WispError> {
Ok(self
.read_frame(&mut |frame| async { tx.write_frame(frame.into()).await })
.await?
.into())
}
}
impl<S: AsyncWrite + Unpin> crate::ws::WebSocketWrite for WebSocketWrite<S> {
async fn wisp_write_frame(&mut self, frame: crate::ws::Frame) -> Result<(), crate::WispError> {
self.write_frame(frame.into()).await.map_err(|e| e.into())
}
}