Skip to main content

rfid_silion_compat/
error.rs

1use core::fmt;
2
3/// Errors returned by this crate.
4#[derive(Debug, Clone, PartialEq, Eq)]
5pub enum ProtocolError {
6    /// Packet is too short to be valid.
7    PacketTooShort,
8    /// Packet does not start with 0xFF.
9    InvalidHeader(u8),
10    /// Data length field does not match packet size.
11    LengthMismatch {
12        /// Length declared in packet.
13        declared: usize,
14        /// Actual observed payload length.
15        actual: usize,
16    },
17    /// The CRC in packet does not match computed CRC.
18    InvalidCrc {
19        /// CRC computed from packet bytes.
20        expected: u16,
21        /// CRC read from packet bytes.
22        actual: u16,
23    },
24    /// Host command data exceeded 255 bytes.
25    DataTooLong(usize),
26    /// A command-specific argument is invalid.
27    InvalidArgument(&'static str),
28    /// Reader response had an unexpected format.
29    InvalidResponse(&'static str),
30}
31
32impl fmt::Display for ProtocolError {
33    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
34        match self {
35            Self::PacketTooShort => write!(f, "packet too short"),
36            Self::InvalidHeader(h) => write!(f, "invalid header 0x{h:02X}"),
37            Self::LengthMismatch { declared, actual } => {
38                write!(f, "length mismatch: declared={declared}, actual={actual}")
39            }
40            Self::InvalidCrc { expected, actual } => {
41                write!(
42                    f,
43                    "invalid CRC: expected=0x{expected:04X}, actual=0x{actual:04X}"
44                )
45            }
46            Self::DataTooLong(n) => write!(f, "data length {n} exceeds 255 bytes"),
47            Self::InvalidArgument(msg) => write!(f, "invalid argument: {msg}"),
48            Self::InvalidResponse(msg) => write!(f, "invalid response: {msg}"),
49        }
50    }
51}
52
53impl std::error::Error for ProtocolError {}