#[derive(Debug, Clone)]
pub enum WebsocketMessage {
Text(String),
Binary(Vec<u8>),
Ping,
Pong,
}
impl WebsocketMessage {
pub fn new_binary<T>(payload: T) -> Self
where
T: Into<Vec<u8>>,
{
Self::Binary(payload.into())
}
pub fn new_text(str: impl ToString) -> Self {
Self::Text(str.to_string())
}
pub fn is_text(&self) -> bool {
matches!(self, Self::Text(_))
}
pub fn text(&self) -> Option<&str> {
match self {
WebsocketMessage::Text(txt) => Some(txt),
WebsocketMessage::Binary(bin) => std::str::from_utf8(bin.as_slice()).ok(),
_ => None,
}
}
pub fn bytes(&self) -> Option<&[u8]> {
match self {
WebsocketMessage::Text(txt) => Some(txt.as_bytes()),
WebsocketMessage::Binary(bin) => Some(bin.as_slice()),
WebsocketMessage::Ping => None,
WebsocketMessage::Pong => None,
}
}
}