use core::fmt;
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
#[non_exhaustive]
pub enum DecodeError {
Incomplete {
needed: usize,
},
TooLarge {
what: &'static str,
declared: u64,
cap: u64,
},
Malformed {
what: &'static str,
},
}
impl DecodeError {
#[must_use]
pub const fn is_violation(&self) -> bool {
!matches!(self, Self::Incomplete { .. })
}
}
impl fmt::Display for DecodeError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
Self::Incomplete { needed } => write!(f, "incomplete: at least {needed} more octets"),
Self::TooLarge {
what,
declared,
cap,
} => write!(
f,
"{what} too large: {declared} octets over the cap of {cap}"
),
Self::Malformed { what } => write!(f, "malformed: {what}"),
}
}
}
impl std::error::Error for DecodeError {}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
#[non_exhaustive]
pub enum EncodeError {
InvalidName {
what: &'static str,
},
InvalidValue {
what: &'static str,
},
TooLarge {
what: &'static str,
len: u64,
cap: u64,
},
}
impl fmt::Display for EncodeError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
Self::InvalidName { what } => write!(f, "invalid {what}: not a token"),
Self::InvalidValue { what } => write!(f, "invalid {what}"),
Self::TooLarge { what, len, cap } => {
write!(f, "{what} too large: {len} over the limit of {cap}")
}
}
}
}
impl std::error::Error for EncodeError {}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn only_incomplete_is_not_a_violation() {
assert!(!DecodeError::Incomplete { needed: 1 }.is_violation());
assert!(DecodeError::Malformed { what: "version" }.is_violation());
assert!(
DecodeError::TooLarge {
what: "head",
declared: 2,
cap: 1
}
.is_violation()
);
}
}