1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
use std::convert::From;
use std::ffi::{OsStr, OsString};
use std::fmt::Display;
use std::io::Error as IoError;
#[cfg(feature = "http")]
use std::io::ErrorKind;

/// Any error that happens when opening a stream.
#[derive(Debug)]
pub enum Error {
    Io(IoError),
    #[cfg(feature = "http")]
    Http {
        code: u16,
        message: String,
    },
}

pub type Result<T> = std::result::Result<T, Error>;

impl Error {
    pub(crate) fn to_os_string(&self, path: &OsStr) -> OsString {
        let mut str = OsString::new();
        str.push("Error opening ");
        str.push(path);
        str.push(": ");
        str.push(self.to_string());
        str
    }
}

impl From<IoError> for Error {
    fn from(err: IoError) -> Self {
        Error::Io(err)
    }
}

impl Into<IoError> for Error {
    fn into(self) -> IoError {
        match self {
            Error::Io(err) => err,
            #[cfg(feature = "http")]
            Error::Http { code: 404, message } => IoError::new(ErrorKind::NotFound, message),
            #[cfg(feature = "http")]
            Error::Http { code: 403, message } => {
                IoError::new(ErrorKind::PermissionDenied, message)
            }
            #[cfg(feature = "http")]
            Error::Http { .. } => IoError::new(ErrorKind::Other, self.to_string()),
        }
    }
}

impl Display for Error {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::result::Result<(), std::fmt::Error> {
        match self {
            Error::Io(err) => err.fmt(f),
            #[cfg(feature = "http")]
            Error::Http { code, message } => write!(f, "{}: {}", code, message),
        }
    }
}