Skip to main content

wa_wire_codec/
error.rs

1//! Parse failures.
2//!
3//! A frame arrives from the network by way of another process, so a malformed
4//! one is ordinary input. Every variant names what was wrong specifically
5//! enough to tell a protocol change apart from corruption — the distinction
6//! that matters when a stanza suddenly stops parsing in production.
7
8use core::fmt;
9
10/// Why a frame could not be parsed.
11#[derive(Debug, Clone, Copy, PartialEq, Eq)]
12#[non_exhaustive]
13pub enum ParseError {
14    /// The buffer ended mid-field.
15    UnexpectedEof {
16        /// Bytes the field required.
17        needed: usize,
18        /// Bytes actually left.
19        available: usize,
20    },
21    /// A node did not begin with a list tag.
22    ExpectedList {
23        /// The tag byte found instead.
24        found: u8,
25    },
26    /// A node's list length was zero. Every node has at least a tag.
27    EmptyNode,
28    /// A tag byte has no meaning in this position.
29    UnexpectedTag {
30        /// The offending byte.
31        tag: u8,
32    },
33    /// A dictionary index points past the end of its dictionary. Usually means
34    /// the token table is older than the stanza.
35    UnknownToken {
36        /// Which dictionary, or `None` for the single-byte table.
37        dictionary: Option<u8>,
38        /// The index that was out of range.
39        index: u16,
40    },
41    /// A node's tag was not a string.
42    NonStringTag,
43    /// An attribute key or value was not a string.
44    NonStringAttr,
45    /// A packed nibble or hex run declared a length that cannot exist.
46    InvalidPackedLength {
47        /// The length byte as read.
48        byte: u8,
49    },
50    /// Bytes remain after the root node. The caller passed more than one frame,
51    /// or the frame is not what it claims.
52    TrailingBytes(usize),
53    /// Nesting went deeper than the parser permits.
54    DepthLimitExceeded {
55        /// The limit that was hit.
56        limit: usize,
57    },
58}
59
60impl fmt::Display for ParseError {
61    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
62        match self {
63            Self::UnexpectedEof { needed, available } => write!(
64                f,
65                "unexpected end of frame: needed {needed} byte(s), {available} available"
66            ),
67            Self::ExpectedList { found } => {
68                write!(f, "expected a list tag, found {found:#04x}")
69            }
70            Self::EmptyNode => f.write_str("node list is empty; every node has at least a tag"),
71            Self::UnexpectedTag { tag } => write!(f, "unexpected tag {tag:#04x}"),
72            Self::UnknownToken { dictionary, index } => match dictionary {
73                Some(dict) => write!(f, "no token {index} in dictionary {dict}"),
74                None => write!(f, "no single-byte token {index}"),
75            },
76            Self::NonStringTag => f.write_str("node tag is not a string"),
77            Self::NonStringAttr => f.write_str("attribute key or value is not a string"),
78            Self::InvalidPackedLength { byte } => {
79                write!(f, "invalid packed length byte {byte:#04x}")
80            }
81            Self::TrailingBytes(count) => {
82                write!(f, "{count} trailing byte(s) after the root node")
83            }
84            Self::DepthLimitExceeded { limit } => {
85                write!(f, "nesting deeper than the limit of {limit}")
86            }
87        }
88    }
89}
90
91impl core::error::Error for ParseError {}
92
93#[cfg(test)]
94mod tests {
95    use super::*;
96    extern crate alloc;
97    use alloc::string::ToString;
98
99    #[test]
100    fn every_variant_renders_its_detail() {
101        let cases: [(ParseError, &[&str]); 10] = [
102            (
103                ParseError::UnexpectedEof {
104                    needed: 4,
105                    available: 1,
106                },
107                &["4", "1"],
108            ),
109            (ParseError::ExpectedList { found: 0x07 }, &["0x07"]),
110            (ParseError::EmptyNode, &["empty"]),
111            (ParseError::UnexpectedTag { tag: 0xAB }, &["0xab"]),
112            (
113                ParseError::UnknownToken {
114                    dictionary: Some(2),
115                    index: 300,
116                },
117                &["2", "300"],
118            ),
119            (
120                ParseError::UnknownToken {
121                    dictionary: None,
122                    index: 240,
123                },
124                &["240"],
125            ),
126            (ParseError::NonStringTag, &["tag"]),
127            (ParseError::NonStringAttr, &["attribute"]),
128            (ParseError::InvalidPackedLength { byte: 0x80 }, &["0x80"]),
129            (ParseError::TrailingBytes(9), &["9"]),
130        ];
131        for (error, fragments) in cases {
132            let text = error.to_string();
133            assert!(!text.is_empty());
134            for fragment in fragments {
135                assert!(text.contains(fragment), "{text:?} lacks {fragment:?}");
136            }
137        }
138        assert!(
139            ParseError::DepthLimitExceeded { limit: 64 }
140                .to_string()
141                .contains("64")
142        );
143    }
144
145    #[test]
146    fn errors_are_std_errors_and_comparable() {
147        fn assert_error<E: core::error::Error>(_: &E) {}
148        assert_error(&ParseError::EmptyNode);
149        assert_eq!(ParseError::EmptyNode, ParseError::EmptyNode);
150        assert_ne!(ParseError::EmptyNode, ParseError::NonStringTag);
151        assert!(!alloc::format!("{:?}", ParseError::EmptyNode).is_empty());
152    }
153}