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
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
mod context;
pub(crate) use context::ErrorContext;
use std::{
fmt::Display,
num::{ParseFloatError, ParseIntError},
};
#[derive(Debug, PartialEq)]
pub struct Error {
context: Option<String>,
pub kind: ErrorKind,
}
#[derive(Debug)]
pub enum ErrorKind {
NotAllowed(String),
Unsupported(String),
InvalidSysFS,
ParseError {
msg: String,
line: usize,
},
IoError(std::io::Error),
}
impl Error {
pub(crate) fn unexpected_eol<T: Display>(expected_item: T, line: usize) -> Self {
ErrorKind::ParseError {
msg: format!("Unexpected EOL, expected {expected_item}"),
line,
}
.into()
}
pub(crate) fn basic_parse_error(msg: String) -> Self {
ErrorKind::ParseError { msg, line: 1 }.into()
}
pub(crate) fn not_allowed(msg: String) -> Self {
ErrorKind::NotAllowed(msg).into()
}
pub fn is_not_found(&self) -> bool {
matches!(&self.kind, ErrorKind::IoError(io_err) if io_err.kind() == std::io::ErrorKind::NotFound)
}
}
impl Display for Error {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match &self.kind {
ErrorKind::NotAllowed(info) => write!(f, "not allowed: {info}")?,
ErrorKind::InvalidSysFS => write!(f, "invalid SysFS")?,
ErrorKind::ParseError { msg, line } => write!(f, "parse error: {msg} at line {line}")?,
ErrorKind::IoError(error) => write!(f, "io error: {error}")?,
ErrorKind::Unsupported(err) => write!(f, "unsupported: {err}")?,
}
if let Some(ctx) = &self.context {
write!(f, "\n{ctx}")?;
}
Ok(())
}
}
impl std::error::Error for Error {}
impl From<ErrorKind> for Error {
fn from(kind: ErrorKind) -> Self {
Self {
context: None,
kind,
}
}
}
impl From<std::io::Error> for Error {
fn from(err: std::io::Error) -> Self {
Self {
context: None,
kind: ErrorKind::IoError(err),
}
}
}
impl From<ParseIntError> for Error {
fn from(err: ParseIntError) -> Self {
Self::basic_parse_error(err.to_string())
}
}
impl From<ParseFloatError> for Error {
fn from(err: ParseFloatError) -> Self {
Self::basic_parse_error(err.to_string())
}
}
impl PartialEq for ErrorKind {
fn eq(&self, other: &Self) -> bool {
match (self, other) {
(Self::IoError(l0), Self::IoError(r0)) => l0.kind() == r0.kind(),
_ => core::mem::discriminant(self) == core::mem::discriminant(other),
}
}
}