|
| 1 | +use { |
| 2 | + crate::{Backend, CloseFrame, Message}, |
| 3 | + bytes::Bytes, |
| 4 | + tokio::io::{AsyncRead, AsyncWrite}, |
| 5 | + tokio_tungstenite::WebSocketStream, |
| 6 | + tungstenite::{ |
| 7 | + Error as NativeError, |
| 8 | + Message as NativeMessage, |
| 9 | + Utf8Bytes, |
| 10 | + protocol::CloseFrame as NativeCloseFrame, |
| 11 | + }, |
| 12 | +}; |
| 13 | + |
| 14 | +impl<T> Backend for WebSocketStream<T> |
| 15 | +where |
| 16 | + T: AsyncRead + AsyncWrite + Unpin + Send + 'static, |
| 17 | +{ |
| 18 | + type Error = NativeError; |
| 19 | + type Message = NativeMessage; |
| 20 | + type Transport = Self; |
| 21 | + |
| 22 | + fn into_transport(self) -> Self::Transport { |
| 23 | + self |
| 24 | + } |
| 25 | + |
| 26 | + fn encode_message(msg: Message) -> Self::Message { |
| 27 | + match msg { |
| 28 | + Message::Binary(data) => NativeMessage::binary(data), |
| 29 | + Message::Text(data) => NativeMessage::text(data), |
| 30 | + Message::Ping(data) => NativeMessage::Ping(data), |
| 31 | + Message::Pong(data) => NativeMessage::Pong(data), |
| 32 | + Message::Close(msg) => { |
| 33 | + let frame = msg.map(|frame| NativeCloseFrame { |
| 34 | + code: frame.code.into(), |
| 35 | + reason: frame.reason.into(), |
| 36 | + }); |
| 37 | + |
| 38 | + NativeMessage::Close(frame) |
| 39 | + } |
| 40 | + } |
| 41 | + } |
| 42 | + |
| 43 | + fn decode_message(msg: Self::Message) -> Message { |
| 44 | + match msg { |
| 45 | + NativeMessage::Binary(data) => Message::Binary(data), |
| 46 | + NativeMessage::Text(data) => Message::Text(bytes_to_string(data)), |
| 47 | + NativeMessage::Ping(data) => Message::Ping(data), |
| 48 | + NativeMessage::Pong(data) => Message::Pong(data), |
| 49 | + NativeMessage::Close(frame) => { |
| 50 | + let frame = frame.map(|frame| CloseFrame { |
| 51 | + code: frame.code.into(), |
| 52 | + reason: bytes_to_string(frame.reason), |
| 53 | + }); |
| 54 | + |
| 55 | + Message::Close(frame) |
| 56 | + } |
| 57 | + NativeMessage::Frame(_) => Message::Close(None), |
| 58 | + } |
| 59 | + } |
| 60 | +} |
| 61 | + |
| 62 | +fn bytes_to_string(data: Utf8Bytes) -> String { |
| 63 | + String::from_utf8(Bytes::from(data).into()).unwrap_or_default() |
| 64 | +} |
0 commit comments