Skip to main content

zendo_protocol/
error.rs

1//! The protocol decoding error type.
2
3use core::fmt;
4
5/// Why a binary frame could not be decoded.
6///
7/// This is a small, copyable enum so downstream crates can match on the exact
8/// failure without string parsing.
9#[derive(Clone, Copy, Debug, PartialEq, Eq)]
10pub enum ProtocolError {
11    /// The frame had no bytes, so it carried no type tag.
12    EmptyFrame,
13    /// The type tag did not correspond to any known message.
14    UnknownMessageType(u8),
15    /// The payload length did not match what the message type requires.
16    InvalidLength {
17        message_type: u8,
18        expected: usize,
19        actual: usize,
20    },
21    /// A hand frame carried a side byte that was neither right (0) nor left (1).
22    InvalidHandSide(u8),
23}
24
25impl fmt::Display for ProtocolError {
26    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
27        match self {
28            Self::EmptyFrame => f.write_str("received an empty WebSocket frame"),
29            Self::UnknownMessageType(tag) => {
30                write!(f, "unknown message type byte 0x{tag:02x}")
31            }
32            Self::InvalidLength {
33                message_type,
34                expected,
35                actual,
36            } => write!(
37                f,
38                "message type 0x{message_type:02x}: expected {expected} payload bytes, got {actual}"
39            ),
40            Self::InvalidHandSide(byte) => {
41                write!(f, "invalid hand-side byte {byte} (expected 0 or 1)")
42            }
43        }
44    }
45}
46
47#[cfg(feature = "std")]
48impl std::error::Error for ProtocolError {}
49
50#[cfg(test)]
51mod tests {
52    use super::*;
53
54    #[test]
55    fn display_is_human_readable() {
56        // Arrange / Act / Assert
57        assert_eq!(
58            ProtocolError::EmptyFrame.to_string(),
59            "received an empty WebSocket frame"
60        );
61        assert_eq!(
62            ProtocolError::UnknownMessageType(0xAB).to_string(),
63            "unknown message type byte 0xab"
64        );
65        assert_eq!(
66            ProtocolError::InvalidHandSide(7).to_string(),
67            "invalid hand-side byte 7 (expected 0 or 1)"
68        );
69    }
70}