use std::fmt; use std::io; #[derive(Debug)] pub enum Error { Io(io::Error), /// Bad magic number in header. BadMagic(u16), /// Protocol version not supported. UnsupportedVersion(u8), /// Unknown message type byte. UnknownMessageType(u8), /// Packet or buffer too small for the operation. BufferTooSmall, /// Payload length doesn't match declared length. PayloadMismatch, /// Generic invalid message (malformed content). InvalidMessage, /// Not connected to the network. NotConnected, /// Operation timed out. Timeout, /// Signature verification failed. BadSignature, } impl fmt::Display for Error { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { match self { Error::Io(e) => write!(f, "I/O error: {e}"), Error::BadMagic(m) => { write!(f, "bad magic: 0x{m:04x}") } Error::UnsupportedVersion(v) => { write!(f, "unsupported version: {v}") } Error::UnknownMessageType(t) => { write!(f, "unknown message type: 0x{t:02x}") } Error::BufferTooSmall => { write!(f, "buffer too small") } Error::PayloadMismatch => { write!(f, "payload length mismatch") } Error::InvalidMessage => { write!(f, "invalid message") } Error::NotConnected => write!(f, "not connected"), Error::Timeout => write!(f, "timeout"), Error::BadSignature => { write!(f, "signature verification failed") } } } } impl std::error::Error for Error { fn source(&self) -> Option<&(dyn std::error::Error + 'static)> { match self { Error::Io(e) => Some(e), _ => None, } } } impl From for Error { fn from(e: io::Error) -> Self { Error::Io(e) } }