use std::fmt;
pub type Result<T, E = Error> = std::result::Result<T, E>;
#[derive(Debug)]
pub enum Error {
Io(std::io::Error),
InvalidFormat(&'static str),
InvalidData(String),
Truncated {
context: &'static str,
needed: usize,
remaining: usize,
},
LimitExceeded {
limit: &'static str,
value: u64,
max: u64,
},
ChecksumMismatch {
context: &'static str,
expected: u32,
actual: u32,
},
Decode {
context: &'static str,
encoding: &'static str,
},
MissingPasscode,
Unsupported(&'static str),
}
impl Error {
pub fn truncated(context: &'static str, needed: usize, remaining: usize) -> Self {
Self::Truncated {
context,
needed,
remaining,
}
}
}
impl fmt::Display for Error {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
Self::Io(error) => write!(f, "I/O error: {error}"),
Self::InvalidFormat(context) => write!(f, "invalid format: {context}"),
Self::InvalidData(context) => write!(f, "invalid data: {context}"),
Self::Truncated {
context,
needed,
remaining,
} => write!(
f,
"truncated {context}: need {needed} bytes, have {remaining}"
),
Self::LimitExceeded { limit, value, max } => {
write!(f, "limit exceeded for {limit}: {value} > {max}")
}
Self::ChecksumMismatch {
context,
expected,
actual,
} => write!(
f,
"checksum mismatch for {context}: expected {expected:#010x}, got {actual:#010x}"
),
Self::Decode { context, encoding } => {
write!(f, "failed to decode {context} using {encoding}")
}
Self::MissingPasscode => write!(f, "dictionary requires a passcode"),
Self::Unsupported(feature) => write!(f, "unsupported feature: {feature}"),
}
}
}
impl std::error::Error for Error {
fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
match self {
Self::Io(error) => Some(error),
_ => None,
}
}
}
impl From<std::io::Error> for Error {
fn from(value: std::io::Error) -> Self {
Self::Io(value)
}
}