starship_battery/
errors.rs

1//! Errors handling
2
3use std::borrow::Cow;
4use std::error::Error as StdError;
5use std::fmt;
6use std::io;
7use std::result;
8
9pub type Result<T> = result::Result<T, Error>;
10
11/// Battery routines error.
12///
13/// Since all operations are basically I/O of some kind,
14/// this is a thin wrapper around `::std::io::Error` with option
15/// to store custom description for debugging purposes.
16#[derive(Debug)]
17pub struct Error {
18    source: io::Error,
19    description: Option<Cow<'static, str>>,
20}
21
22impl Error {
23    #[allow(unused)]
24    pub(crate) fn new<T>(e: io::Error, description: T) -> Error
25    where
26        T: Into<Cow<'static, str>>,
27    {
28        Error {
29            source: e,
30            description: Some(description.into()),
31        }
32    }
33
34    #[allow(unused)]
35    pub(crate) fn not_found<T>(description: T) -> Error
36    where
37        T: Into<Cow<'static, str>>,
38    {
39        Error {
40            source: io::Error::from(io::ErrorKind::NotFound),
41            description: Some(description.into()),
42        }
43    }
44
45    #[allow(unused)]
46    pub(crate) fn invalid_data<T>(description: T) -> Error
47    where
48        T: Into<Cow<'static, str>>,
49    {
50        Error {
51            source: io::Error::from(io::ErrorKind::InvalidData),
52            description: Some(description.into()),
53        }
54    }
55}
56
57impl StdError for Error {
58    fn source(&self) -> Option<&(dyn StdError + 'static)> {
59        Some(&self.source)
60    }
61}
62
63impl fmt::Display for Error {
64    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
65        match &self.description {
66            Some(desc) => write!(f, "{}", desc),
67            None => self.source.fmt(f),
68        }
69    }
70}
71
72impl From<io::Error> for Error {
73    fn from(e: io::Error) -> Self {
74        Error {
75            source: e,
76            description: None,
77        }
78    }
79}
80
81#[cfg(any(target_os = "dragonfly", target_os = "freebsd", target_os = "netbsd"))]
82mod nix_impl {
83    use std::io;
84
85    use super::Error;
86
87    impl From<nix::Error> for Error {
88        fn from(errno: nix::Error) -> Self {
89            Error {
90                source: io::Error::from_raw_os_error(errno as i32),
91                description: Some(errno.desc().into()),
92            }
93        }
94    }
95}
96
97#[cfg(target_os = "netbsd")]
98mod plist_impl {
99    use super::Error;
100
101    impl From<plist::Error> for Error {
102        fn from(e: plist::Error) -> Self {
103            let desc = e.to_string();
104
105            match e.into_io() {
106                Ok(ioerr) => Error::new(ioerr, desc),
107                Err(_) => Error::invalid_data("Problem while processing plist"),
108            }
109        }
110    }
111}