Skip to main content

linux_procfs/
error.rs

1use std::fmt;
2use std::io;
3use std::num::{ParseFloatError, ParseIntError};
4use std::str::Utf8Error;
5
6#[derive(Debug)]
7pub enum ProcError {
8    Io(io::Error),
9    Utf8(Utf8Error),
10    ParseInt(ParseIntError),
11    ParseFloat(ParseFloatError),
12    UnexpectedFormat(String),
13    ParseError,
14    InternalError,
15    PermissionDenied,
16    NotFound,
17}
18
19impl ProcError {
20    pub fn is_not_found(&self) -> bool {
21        matches!(self, Self::NotFound)
22    }
23}
24impl fmt::Display for ProcError {
25    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
26        match self {
27            ProcError::Io(e) => write!(f, "IO error: {}", e),
28            ProcError::Utf8(e) => write!(f, "UTF-8 error: {}", e),
29            ProcError::ParseInt(e) => write!(f, "Parse int error: {}", e),
30            ProcError::ParseFloat(e) => write!(f, "Parse float error: {}", e),
31            ProcError::UnexpectedFormat(s) => write!(f, "Unexpected format: {}", s),
32            ProcError::ParseError => write!(f, "Parse error"),
33            ProcError::InternalError => write!(f, "Internal error"),
34            ProcError::PermissionDenied => write!(f, "Permission denied"),
35            ProcError::NotFound => write!(f, "Not found"),
36        }
37    }
38}
39
40impl std::error::Error for ProcError {
41    fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
42        match self {
43            ProcError::Io(e) => Some(e),
44            ProcError::Utf8(e) => Some(e),
45            ProcError::ParseInt(e) => Some(e),
46            ProcError::ParseFloat(e) => Some(e),
47            _ => None,
48        }
49    }
50}
51
52impl From<io::Error> for ProcError {
53    fn from(err: io::Error) -> Self {
54        match err.kind() {
55            io::ErrorKind::PermissionDenied => ProcError::PermissionDenied,
56            io::ErrorKind::NotFound => ProcError::NotFound,
57            _ => ProcError::Io(err),
58        }
59    }
60}
61
62impl From<Utf8Error> for ProcError {
63    fn from(err: Utf8Error) -> Self {
64        ProcError::Utf8(err)
65    }
66}
67
68impl From<ParseIntError> for ProcError {
69    fn from(err: ParseIntError) -> Self {
70        ProcError::ParseInt(err)
71    }
72}
73
74impl From<ParseFloatError> for ProcError {
75    fn from(err: ParseFloatError) -> Self {
76        ProcError::ParseFloat(err)
77    }
78}
79
80pub type ProcResult<T> = Result<T, ProcError>;