eye_hal/
error.rs

1use std::{error, fmt, io, result};
2
3//
4// Modeled after std::io::error: https://doc.rust-lang.org/src/std/io/error.rs.html.
5//
6
7/// Specialized result type for this crate.
8pub type Result<T> = result::Result<T, Error>;
9
10/// Error type for all fallible operations in this crate.
11#[derive(Debug)]
12pub struct Error {
13    repr: Repr,
14}
15
16enum Repr {
17    Simple(ErrorKind),
18    Custom(Box<Custom>),
19}
20
21impl fmt::Debug for Repr {
22    fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
23        match self {
24            Repr::Simple(kind) => fmt.debug_tuple("Kind").field(&kind).finish(),
25            Repr::Custom(ref c) => fmt::Debug::fmt(&c, fmt),
26        }
27    }
28}
29
30#[derive(Debug)]
31struct Custom {
32    kind: ErrorKind,
33    error: Box<dyn error::Error + Send + Sync>,
34}
35
36#[derive(Debug)]
37pub enum ErrorKind {
38    /// This operation is not supported.
39    NotSupported,
40    /// Any other error not part of this list.
41    Other,
42}
43
44impl fmt::Display for ErrorKind {
45    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
46        match self {
47            ErrorKind::NotSupported => write!(f, "not supported"),
48            ErrorKind::Other => write!(f, "other"),
49        }
50    }
51}
52
53impl Error {
54    pub fn new<E>(kind: ErrorKind, error: E) -> Self
55    where
56        E: Into<Box<dyn error::Error + Send + Sync>>,
57    {
58        Error {
59            repr: Repr::Custom(Box::new(Custom {
60                kind,
61                error: error.into(),
62            })),
63        }
64    }
65}
66
67impl From<ErrorKind> for Error {
68    fn from(kind: ErrorKind) -> Self {
69        Error {
70            repr: Repr::Simple(kind),
71        }
72    }
73}
74
75impl From<io::Error> for Error {
76    fn from(error: io::Error) -> Self {
77        Error {
78            repr: Repr::Custom(Box::new(Custom {
79                kind: ErrorKind::Other,
80                error: error.into(),
81            })),
82        }
83    }
84}
85
86impl fmt::Display for Error {
87    fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
88        match &self.repr {
89            Repr::Simple(kind) => write!(fmt, "{}", kind),
90            Repr::Custom(ref c) => c.error.fmt(fmt),
91        }
92    }
93}
94
95impl error::Error for Error {
96    fn cause(&self) -> Option<&dyn std::error::Error> {
97        None
98    }
99}