use crate::error::*; #[derive(Eq, PartialEq, Copy, Clone, Debug)] pub enum Protocol { TokenError, Disconnect, AddressExhausted, Other(u8), } impl From for Protocol { fn from(value: u8) -> Self { match value { 1 => Self::TokenError, 2 => Self::Disconnect, 3 => Self::AddressExhausted, val => Self::Other(val), } } } impl Into for Protocol { fn into(self) -> u8 { match self { Protocol::TokenError => 1, Protocol::Disconnect => 2, Protocol::AddressExhausted => 3, Protocol::Other(val) => val, } } } pub enum InErrorPacket { TokenError, Disconnect, AddressExhausted, OtherError(ErrorPacket), } impl> InErrorPacket { pub fn new(protocol: u8, buffer: B) -> Result> { match Protocol::from(protocol) { Protocol::TokenError => Ok(InErrorPacket::TokenError), Protocol::Disconnect => Ok(InErrorPacket::Disconnect), Protocol::AddressExhausted => Ok(InErrorPacket::AddressExhausted), Protocol::Other(_) => Ok(InErrorPacket::OtherError(ErrorPacket::new(buffer)?)), } } } pub struct ErrorPacket { buffer: B, } impl> ErrorPacket { pub fn new(buffer: B) -> Result> { Ok(Self { buffer }) } } impl> ErrorPacket { pub fn message(&self) -> Result { match String::from_utf8(self.buffer.as_ref().to_vec()) { Ok(str) => Ok(str), Err(_) => Err(Error::InvalidPacket), } } } impl + AsMut<[u8]>> ErrorPacket { pub fn set_message(&mut self, message: &str) { self.buffer.as_mut().copy_from_slice(message.as_bytes()) } }