use core::fmt;
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum ProtocolError {
EmptyFrame,
UnknownMessageType(u8),
InvalidLength {
message_type: u8,
expected: usize,
actual: usize,
},
InvalidHandSide(u8),
}
impl fmt::Display for ProtocolError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
Self::EmptyFrame => f.write_str("received an empty WebSocket frame"),
Self::UnknownMessageType(tag) => {
write!(f, "unknown message type byte 0x{tag:02x}")
}
Self::InvalidLength {
message_type,
expected,
actual,
} => write!(
f,
"message type 0x{message_type:02x}: expected {expected} payload bytes, got {actual}"
),
Self::InvalidHandSide(byte) => {
write!(f, "invalid hand-side byte {byte} (expected 0 or 1)")
}
}
}
}
#[cfg(feature = "std")]
impl std::error::Error for ProtocolError {}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn display_is_human_readable() {
assert_eq!(
ProtocolError::EmptyFrame.to_string(),
"received an empty WebSocket frame"
);
assert_eq!(
ProtocolError::UnknownMessageType(0xAB).to_string(),
"unknown message type byte 0xab"
);
assert_eq!(
ProtocolError::InvalidHandSide(7).to_string(),
"invalid hand-side byte 7 (expected 0 or 1)"
);
}
}