Skip to main content

melin_wire_protocol/
error.rs

1//! Protocol error types.
2
3use std::fmt;
4
5/// Errors that can occur during protocol encoding/decoding.
6#[derive(Debug)]
7pub enum ProtocolError {
8    /// Buffer does not contain a complete message.
9    Truncated,
10    /// Unknown message type tag.
11    UnknownTag(u8),
12    /// A field value is invalid (e.g., zero where a count is required,
13    /// bad enum discriminant).
14    InvalidField(&'static str),
15    /// Message exceeds maximum allowed frame size.
16    MessageTooLarge(usize),
17    /// Underlying I/O error.
18    Io(std::io::Error),
19}
20
21impl fmt::Display for ProtocolError {
22    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
23        match self {
24            Self::Truncated => write!(f, "truncated message"),
25            Self::UnknownTag(tag) => write!(f, "unknown message tag: {tag}"),
26            Self::InvalidField(field) => write!(f, "invalid field: {field}"),
27            Self::MessageTooLarge(size) => write!(f, "message too large: {size} bytes"),
28            Self::Io(e) => write!(f, "I/O error: {e}"),
29        }
30    }
31}
32
33impl std::error::Error for ProtocolError {
34    fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
35        match self {
36            Self::Io(e) => Some(e),
37            _ => None,
38        }
39    }
40}
41
42impl From<std::io::Error> for ProtocolError {
43    fn from(e: std::io::Error) -> Self {
44        Self::Io(e)
45    }
46}