use std::{convert::TryFrom, fmt};
use crate::connection::CloseReason;
#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub enum Incoming<'a> {
Data(Data),
Pong(&'a [u8]),
Closed(CloseReason),
}
impl Incoming<'_> {
pub fn is_data(&self) -> bool {
if let Incoming::Data(_) = self {
true
} else {
false
}
}
pub fn is_pong(&self) -> bool {
if let Incoming::Pong(_) = self {
true
} else {
false
}
}
pub fn is_text(&self) -> bool {
if let Incoming::Data(d) = self {
d.is_text()
} else {
false
}
}
pub fn is_binary(&self) -> bool {
if let Incoming::Data(d) = self {
d.is_binary()
} else {
false
}
}
}
#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub enum Data {
Text(usize),
Binary(usize),
}
impl Data {
pub fn is_text(&self) -> bool {
if let Data::Text(_) = self {
true
} else {
false
}
}
pub fn is_binary(&self) -> bool {
if let Data::Binary(_) = self {
true
} else {
false
}
}
pub fn len(&self) -> usize {
match self {
Data::Text(n) => *n,
Data::Binary(n) => *n,
}
}
}
#[derive(Debug)]
pub struct ByteSlice125<'a>(&'a [u8]);
#[derive(Clone, Debug)]
pub struct SliceTooLarge(());
impl fmt::Display for SliceTooLarge {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
f.write_str("Slice larger than 125 bytes")
}
}
impl std::error::Error for SliceTooLarge {}
impl<'a> TryFrom<&'a [u8]> for ByteSlice125<'a> {
type Error = SliceTooLarge;
fn try_from(value: &'a [u8]) -> Result<Self, Self::Error> {
if value.len() > 125 {
Err(SliceTooLarge(()))
} else {
Ok(ByteSlice125(value))
}
}
}
impl AsRef<[u8]> for ByteSlice125<'_> {
fn as_ref(&self) -> &[u8] {
self.0
}
}