use std::fmt;
#[derive(Debug, thiserror::Error)]
pub enum Error {
#[error("bad magic: expected {expected}, got {got}")]
BadMagic {
expected: HexBytes,
got: HexBytes,
},
#[error("truncated: need {need} bytes at offset {at}, {have} available")]
Truncated {
need: usize,
at: usize,
have: usize,
},
#[error("malformed at offset {at}: {reason}")]
Malformed {
at: usize,
reason: String,
},
#[error("implausible length {length} for {what} (limit {limit})")]
ImplausibleLength {
what: &'static str,
length: u64,
limit: u64,
},
#[error(transparent)]
Binrw(#[from] binrw::Error),
}
impl Error {
pub fn is_truncated(&self) -> bool {
match self {
Self::Truncated { .. } => true,
Self::Binrw(inner) => inner.is_eof(),
_ => false,
}
}
pub(crate) fn malformed(at: usize, reason: impl Into<String>) -> Self {
Self::Malformed {
at,
reason: reason.into(),
}
}
}
pub type Result<T, E = Error> = std::result::Result<T, E>;
#[derive(Clone, PartialEq, Eq)]
pub struct HexBytes(pub Vec<u8>);
impl fmt::Debug for HexBytes {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
fmt::Display::fmt(self, f)
}
}
impl fmt::Display for HexBytes {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
for byte in &self.0 {
write!(f, "{byte:02x}")?;
}
Ok(())
}
}
impl From<&[u8]> for HexBytes {
fn from(bytes: &[u8]) -> Self {
Self(bytes.to_vec())
}
}