1use crate::IoctlKind;
6use std::error::Error as StdError;
7use std::fmt;
8use std::io::Error as IOError;
9
10pub(crate) type Result<T> = std::result::Result<T, Error>;
11
12#[derive(Debug)]
13pub struct Error {
14 kind: ErrorKind,
15}
16
17#[derive(Debug)]
18pub enum ErrorKind {
19 Event(nix::Error),
20 Io(IOError),
21 Ioctl { kind: IoctlKind, cause: nix::Error },
22 InvalidRequest(usize, usize),
23 Offset(u32),
24}
25
26pub(crate) fn ioctl_err(kind: IoctlKind, cause: nix::Error) -> Error {
27 Error {
28 kind: ErrorKind::Ioctl { kind, cause },
29 }
30}
31
32pub(crate) fn invalid_err(n_lines: usize, n_values: usize) -> Error {
33 Error {
34 kind: ErrorKind::InvalidRequest(n_lines, n_values),
35 }
36}
37
38pub(crate) fn offset_err(offset: u32) -> Error {
39 Error {
40 kind: ErrorKind::Offset(offset),
41 }
42}
43
44pub(crate) fn event_err(err: nix::Error) -> Error {
45 Error {
46 kind: ErrorKind::Event(err),
47 }
48}
49
50impl fmt::Display for IoctlKind {
51 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
52 match *self {
53 IoctlKind::ChipInfo => write!(f, "get chip info"),
54 IoctlKind::LineInfo => write!(f, "get line info"),
55 IoctlKind::LineHandle => write!(f, "get line handle"),
56 IoctlKind::LineEvent => write!(f, "get line event "),
57 IoctlKind::GetLine => write!(f, "get line value"),
58 IoctlKind::SetLine => write!(f, "set line value"),
59 }
60 }
61}
62
63impl fmt::Display for Error {
64 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
65 match &self.kind {
66 ErrorKind::Event(err) => write!(f, "Failed to read event: {}", err),
67 ErrorKind::Io(err) => err.fmt(f),
68 ErrorKind::Ioctl { cause, kind } => write!(f, "Ioctl to {} failed: {}", kind, cause),
69 ErrorKind::InvalidRequest(n_lines, n_values) => write!(
70 f,
71 "Invalid request: {} values requested to be set but only {} lines are open",
72 n_values, n_lines
73 ),
74 ErrorKind::Offset(offset) => write!(f, "Offset {} is out of range", offset),
75 }
76 }
77}
78
79impl StdError for Error {
80 fn source(&self) -> Option<&(dyn StdError + 'static)> {
81 match &self.kind {
82 ErrorKind::Event(err) => Some(err),
83 ErrorKind::Io(err) => Some(err),
84 ErrorKind::Ioctl { kind: _, cause } => Some(cause),
85 _ => None,
86 }
87 }
88}
89
90impl From<IOError> for Error {
91 fn from(err: IOError) -> Self {
92 Self {
93 kind: ErrorKind::Io(err),
94 }
95 }
96}