use core::fmt;
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
#[non_exhaustive]
pub enum ParseMode {
#[default]
Lenient,
Strict,
}
impl ParseMode {
pub(crate) const fn is_strict(self) -> bool {
matches!(self, Self::Strict)
}
}
#[derive(Clone, Debug, PartialEq, Eq)]
#[non_exhaustive]
pub enum ParseError {
BufferTooShort {
context: &'static str,
minimum: usize,
actual: usize,
},
InvalidLength {
context: &'static str,
value: usize,
},
Malformed {
context: &'static str,
},
Truncated {
context: &'static str,
expected: usize,
actual: usize,
},
CompressionLoop {
context: &'static str,
},
InvalidCompression {
context: &'static str,
},
InvalidUtf8 {
context: &'static str,
},
}
impl fmt::Display for ParseError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
ParseError::BufferTooShort {
context,
minimum,
actual,
} => write!(
f,
"{context}: buffer too short (expected at least {minimum} bytes, got {actual})"
),
ParseError::InvalidLength { context, value } => {
write!(f, "{context}: invalid length value {value}")
}
ParseError::Malformed { context } => write!(f, "{context}: malformed packet data"),
ParseError::Truncated {
context,
expected,
actual,
} => write!(
f,
"{context}: truncated payload (expected {expected} bytes, got {actual})"
),
ParseError::CompressionLoop { context } => {
write!(f, "{context}: compression pointer loop detected")
}
ParseError::InvalidCompression { context } => {
write!(f, "{context}: invalid compression pointer")
}
ParseError::InvalidUtf8 { context } => {
write!(f, "{context}: invalid UTF-8 sequence")
}
}
}
}
impl std::error::Error for ParseError {}
#[cfg(test)]
mod tests {
use super::ParseError;
fn assert_error_contract<T: std::error::Error + Send + Sync + 'static>() {}
#[test]
fn parse_error_implements_public_error_contract() {
assert_error_contract::<ParseError>();
}
}