1use std::fmt;
4
5pub type Result<T> = std::result::Result<T, Error>;
7
8#[derive(Debug, thiserror::Error)]
15pub enum Error {
16 #[error("io error: {0}")]
18 Io(#[from] std::io::Error),
19 #[error("invalid format: {0}")]
21 Format(String),
22 #[error("checksum mismatch: {0}")]
25 Checksum(&'static str),
26 #[error("unexpected end of data at byte {0}")]
28 Eof(usize),
29 #[error("chunk decode error: {0}")]
31 Decode(String),
32 #[error("corrupt data: {0}")]
35 Corrupt(String),
36 #[error("unsupported: {0}")]
38 Unsupported(String),
39}
40
41impl Error {
42 pub fn format(msg: impl fmt::Display) -> Self {
44 Error::Format(msg.to_string())
45 }
46
47 pub fn decode(msg: impl fmt::Display) -> Self {
49 Error::Decode(msg.to_string())
50 }
51
52 pub fn corrupt(msg: impl fmt::Display) -> Self {
54 Error::Corrupt(msg.to_string())
55 }
56
57 pub fn is_corruption(&self) -> bool {
62 matches!(
63 self,
64 Error::Format(_)
65 | Error::Checksum(_)
66 | Error::Eof(_)
67 | Error::Decode(_)
68 | Error::Corrupt(_)
69 )
70 }
71}
72
73#[cfg(test)]
74mod tests {
75 use super::*;
76
77 #[test]
78 fn constructors_keep_the_message() {
79 assert!(matches!(Error::format("x"), Error::Format(ref m) if m == "x"));
80 assert!(matches!(Error::decode("y"), Error::Decode(ref m) if m == "y"));
81 assert!(matches!(Error::corrupt("z"), Error::Corrupt(ref m) if m == "z"));
82 }
83
84 #[test]
85 fn corruption_is_classified() {
86 assert!(Error::format("x").is_corruption());
87 assert!(Error::corrupt("x").is_corruption());
88 assert!(Error::Eof(3).is_corruption());
89 assert!(!Error::Unsupported("v9".into()).is_corruption());
90 assert!(!Error::from(std::io::Error::other("disk")).is_corruption());
91 }
92
93 #[test]
94 fn io_errors_keep_their_source() {
95 let error = Error::from(std::io::Error::new(std::io::ErrorKind::NotFound, "gone"));
96 assert!(matches!(error, Error::Io(_)));
97 assert!(std::error::Error::source(&error).is_some());
98 assert!(error.to_string().contains("gone"));
99 }
100}