Skip to main content

joydev_rs/
error.rs

1use std::io::Error as IoError;
2use std::str::Utf8Error;
3use std::{error, fmt};
4
5use nix::errno::Errno;
6
7/// Joydev Error type
8#[derive(Debug)]
9pub enum Error {
10	/// Errors caused by Rust standard io (File::open, Read, etc.).
11	Io(IoError),
12	/// This gets returned from [`io_control::get_event`](io_control/fn.get_event.html) when the device is opened in
13	/// non-blocking mode and there aren't any events left on the device.
14	QueueEmpty,
15	/// Errors caused by C string to Rust string conversion.
16	String(Utf8Error),
17	/// Errors caused by ioctls.
18	Sys(Errno),
19}
20
21impl error::Error for Error {
22	fn description(&self) -> &str {
23		match self {
24			Self::Io(_) => "IO error",
25			Self::QueueEmpty => "Queue empty",
26			Self::String(_) => "String error",
27			Self::Sys(ref errno) => errno.desc(),
28		}
29	}
30
31	fn source(&self) -> Option<&(dyn error::Error + 'static)> {
32		match self {
33			Self::Io(ref error) => Some(error),
34			Self::String(ref error) => Some(error),
35			_ => None,
36		}
37	}
38}
39
40impl fmt::Display for Error {
41	fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
42		match self {
43			Self::Io(ref error) => write!(f, "{}", error),
44			Self::QueueEmpty => write!(f, "Queue empty"),
45			Self::String(ref error) => write!(f, "{}", error),
46			Self::Sys(ref errno) => write!(f, "{:?}: {}", errno, errno.desc()),
47		}
48	}
49}
50
51impl From<Errno> for Error {
52	fn from(errno: Errno) -> Self {
53		Error::Sys(errno)
54	}
55}
56
57impl From<IoError> for Error {
58	fn from(error: IoError) -> Self {
59		Self::Io(error)
60	}
61}
62
63impl From<Utf8Error> for Error {
64	fn from(error: Utf8Error) -> Self {
65		Error::String(error)
66	}
67}