use std::fmt;
pub type Result<T> = std::result::Result<T, Error>;
#[derive(Debug, thiserror::Error)]
pub enum Error {
#[error("io error: {0}")]
Io(#[from] std::io::Error),
#[error("invalid format: {0}")]
Format(String),
#[error("checksum mismatch: {0}")]
Checksum(&'static str),
#[error("unexpected end of data at byte {0}")]
Eof(usize),
#[error("chunk decode error: {0}")]
Decode(String),
#[error("corrupt data: {0}")]
Corrupt(String),
#[error("unsupported: {0}")]
Unsupported(String),
}
impl Error {
pub fn format(msg: impl fmt::Display) -> Self {
Error::Format(msg.to_string())
}
pub fn decode(msg: impl fmt::Display) -> Self {
Error::Decode(msg.to_string())
}
pub fn corrupt(msg: impl fmt::Display) -> Self {
Error::Corrupt(msg.to_string())
}
pub fn is_corruption(&self) -> bool {
matches!(
self,
Error::Format(_)
| Error::Checksum(_)
| Error::Eof(_)
| Error::Decode(_)
| Error::Corrupt(_)
)
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn constructors_keep_the_message() {
assert!(matches!(Error::format("x"), Error::Format(ref m) if m == "x"));
assert!(matches!(Error::decode("y"), Error::Decode(ref m) if m == "y"));
assert!(matches!(Error::corrupt("z"), Error::Corrupt(ref m) if m == "z"));
}
#[test]
fn corruption_is_classified() {
assert!(Error::format("x").is_corruption());
assert!(Error::corrupt("x").is_corruption());
assert!(Error::Eof(3).is_corruption());
assert!(!Error::Unsupported("v9".into()).is_corruption());
assert!(!Error::from(std::io::Error::other("disk")).is_corruption());
}
#[test]
fn io_errors_keep_their_source() {
let error = Error::from(std::io::Error::new(std::io::ErrorKind::NotFound, "gone"));
assert!(matches!(error, Error::Io(_)));
assert!(std::error::Error::source(&error).is_some());
assert!(error.to_string().contains("gone"));
}
}