lzma_rs/
error.rs

1//! Error handling.
2
3use std::fmt::Display;
4use std::{io, result};
5
6/// Library errors.
7#[derive(Debug)]
8pub enum Error {
9    /// I/O error.
10    IoError(io::Error),
11    /// Not enough bytes to complete header
12    HeaderTooShort(io::Error),
13    /// LZMA error.
14    LzmaError(String),
15    /// XZ error.
16    XzError(String),
17}
18
19/// Library result alias.
20pub type Result<T> = result::Result<T, Error>;
21
22impl From<io::Error> for Error {
23    fn from(e: io::Error) -> Error {
24        Error::IoError(e)
25    }
26}
27
28impl Display for Error {
29    fn fmt(&self, fmt: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
30        match self {
31            Error::IoError(e) => write!(fmt, "io error: {}", e),
32            Error::HeaderTooShort(e) => write!(fmt, "header too short: {}", e),
33            Error::LzmaError(e) => write!(fmt, "lzma error: {}", e),
34            Error::XzError(e) => write!(fmt, "xz error: {}", e),
35        }
36    }
37}
38
39impl std::error::Error for Error {
40    fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
41        match self {
42            Error::IoError(e) | Error::HeaderTooShort(e) => Some(e),
43            Error::LzmaError(_) | Error::XzError(_) => None,
44        }
45    }
46}
47
48#[cfg(test)]
49mod test {
50    use super::Error;
51
52    #[test]
53    fn test_display() {
54        assert_eq!(
55            Error::IoError(std::io::Error::new(
56                std::io::ErrorKind::Other,
57                "this is an error"
58            ))
59            .to_string(),
60            "io error: this is an error"
61        );
62        assert_eq!(
63            Error::LzmaError("this is an error".to_string()).to_string(),
64            "lzma error: this is an error"
65        );
66        assert_eq!(
67            Error::XzError("this is an error".to_string()).to_string(),
68            "xz error: this is an error"
69        );
70    }
71}