use async_tungstenite::tungstenite;
#[derive(Clone, Debug)]
pub enum Message {
Text(String),
Binary(Vec<u8>),
Ping(Vec<u8>),
Pong(Vec<u8>),
Close {
code: CloseCode,
reason: Option<String>,
},
}
impl From<String> for Message {
#[inline]
fn from(value: String) -> Self {
Self::Text(value)
}
}
impl From<&str> for Message {
#[inline]
fn from(value: &str) -> Self {
Self::from(value.to_owned())
}
}
impl From<Vec<u8>> for Message {
#[inline]
fn from(value: Vec<u8>) -> Self {
Self::Binary(value)
}
}
impl From<&[u8]> for Message {
#[inline]
fn from(value: &[u8]) -> Self {
Self::from(value.to_vec())
}
}
#[derive(Debug, Default, Eq, PartialEq, Clone, Copy)]
#[non_exhaustive]
pub enum CloseCode {
#[default]
Normal,
Away,
Protocol,
Unsupported,
Status,
Abnormal,
Invalid,
Policy,
Size,
Extension,
Error,
Restart,
Again,
Tls,
Reserved(u16),
Iana(u16),
Library(u16),
Bad(u16),
}
impl CloseCode {
#[must_use]
pub const fn is_allowed(self) -> bool {
!matches!(
self,
Self::Bad(_) | Self::Reserved(_) | Self::Status | Self::Abnormal | Self::Tls
)
}
}
impl std::fmt::Display for CloseCode {
fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
let code: u16 = (*self).into();
write!(f, "{code}")
}
}
impl From<CloseCode> for u16 {
fn from(code: CloseCode) -> Self {
match code {
CloseCode::Normal => 1000,
CloseCode::Away => 1001,
CloseCode::Protocol => 1002,
CloseCode::Unsupported => 1003,
CloseCode::Status => 1005,
CloseCode::Abnormal => 1006,
CloseCode::Invalid => 1007,
CloseCode::Policy => 1008,
CloseCode::Size => 1009,
CloseCode::Extension => 1010,
CloseCode::Error => 1011,
CloseCode::Restart => 1012,
CloseCode::Again => 1013,
CloseCode::Tls => 1015,
CloseCode::Reserved(code)
| CloseCode::Iana(code)
| CloseCode::Library(code)
| CloseCode::Bad(code) => code,
}
}
}
impl From<u16> for CloseCode {
fn from(code: u16) -> Self {
match code {
1000 => Self::Normal,
1001 => Self::Away,
1002 => Self::Protocol,
1003 => Self::Unsupported,
1005 => Self::Status,
1006 => Self::Abnormal,
1007 => Self::Invalid,
1008 => Self::Policy,
1009 => Self::Size,
1010 => Self::Extension,
1011 => Self::Error,
1012 => Self::Restart,
1013 => Self::Again,
1015 => Self::Tls,
1016..=2999 => Self::Reserved(code),
3000..=3999 => Self::Iana(code),
4000..=4999 => Self::Library(code),
_ => Self::Bad(code),
}
}
}
impl From<tungstenite::protocol::frame::coding::CloseCode> for CloseCode {
fn from(value: tungstenite::protocol::frame::coding::CloseCode) -> Self {
u16::from(value).into()
}
}
impl From<CloseCode> for tungstenite::protocol::frame::coding::CloseCode {
fn from(value: CloseCode) -> Self {
u16::from(value).into()
}
}