use core::fmt;
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[non_exhaustive]
pub enum ParseError {
UnexpectedEof {
needed: usize,
available: usize,
},
ExpectedList {
found: u8,
},
EmptyNode,
UnexpectedTag {
tag: u8,
},
UnknownToken {
dictionary: Option<u8>,
index: u16,
},
NonStringTag,
NonStringAttr,
InvalidPackedLength {
byte: u8,
},
TrailingBytes(usize),
DepthLimitExceeded {
limit: usize,
},
}
impl fmt::Display for ParseError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
Self::UnexpectedEof { needed, available } => write!(
f,
"unexpected end of frame: needed {needed} byte(s), {available} available"
),
Self::ExpectedList { found } => {
write!(f, "expected a list tag, found {found:#04x}")
}
Self::EmptyNode => f.write_str("node list is empty; every node has at least a tag"),
Self::UnexpectedTag { tag } => write!(f, "unexpected tag {tag:#04x}"),
Self::UnknownToken { dictionary, index } => match dictionary {
Some(dict) => write!(f, "no token {index} in dictionary {dict}"),
None => write!(f, "no single-byte token {index}"),
},
Self::NonStringTag => f.write_str("node tag is not a string"),
Self::NonStringAttr => f.write_str("attribute key or value is not a string"),
Self::InvalidPackedLength { byte } => {
write!(f, "invalid packed length byte {byte:#04x}")
}
Self::TrailingBytes(count) => {
write!(f, "{count} trailing byte(s) after the root node")
}
Self::DepthLimitExceeded { limit } => {
write!(f, "nesting deeper than the limit of {limit}")
}
}
}
}
impl core::error::Error for ParseError {}
#[cfg(test)]
mod tests {
use super::*;
extern crate alloc;
use alloc::string::ToString;
#[test]
fn every_variant_renders_its_detail() {
let cases: [(ParseError, &[&str]); 10] = [
(
ParseError::UnexpectedEof {
needed: 4,
available: 1,
},
&["4", "1"],
),
(ParseError::ExpectedList { found: 0x07 }, &["0x07"]),
(ParseError::EmptyNode, &["empty"]),
(ParseError::UnexpectedTag { tag: 0xAB }, &["0xab"]),
(
ParseError::UnknownToken {
dictionary: Some(2),
index: 300,
},
&["2", "300"],
),
(
ParseError::UnknownToken {
dictionary: None,
index: 240,
},
&["240"],
),
(ParseError::NonStringTag, &["tag"]),
(ParseError::NonStringAttr, &["attribute"]),
(ParseError::InvalidPackedLength { byte: 0x80 }, &["0x80"]),
(ParseError::TrailingBytes(9), &["9"]),
];
for (error, fragments) in cases {
let text = error.to_string();
assert!(!text.is_empty());
for fragment in fragments {
assert!(text.contains(fragment), "{text:?} lacks {fragment:?}");
}
}
assert!(
ParseError::DepthLimitExceeded { limit: 64 }
.to_string()
.contains("64")
);
}
#[test]
fn errors_are_std_errors_and_comparable() {
fn assert_error<E: core::error::Error>(_: &E) {}
assert_error(&ParseError::EmptyNode);
assert_eq!(ParseError::EmptyNode, ParseError::EmptyNode);
assert_ne!(ParseError::EmptyNode, ParseError::NonStringTag);
assert!(!alloc::format!("{:?}", ParseError::EmptyNode).is_empty());
}
}