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
use std::error;
use std::fmt;
use std::io;
use std::result;

use heim_common::Error;

use crate::Pid;

/// A specialized `Result` type for process-related routines.
pub type ProcessResult<T> = result::Result<T, ProcessError>;

/// Error which might happen during the process information fetching.
#[derive(Debug)]
#[non_exhaustive]
pub enum ProcessError {
    /// Process with this pid does not exists.
    NoSuchProcess(Pid),
    /// Might be returned when querying zombie process on Unix systems.
    ZombieProcess(Pid),
    /// Not enough permissions to query the process information.
    AccessDenied(Pid),
    /// Data loading failure.
    Load(Error),
}

impl fmt::Display for ProcessError {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        match self {
            ProcessError::NoSuchProcess(pid) => {
                f.write_fmt(format_args!("Process {} does not exists", pid))
            }
            ProcessError::ZombieProcess(pid) => {
                f.write_fmt(format_args!("Process {} is zombie", pid))
            }
            ProcessError::AccessDenied(pid) => {
                f.write_fmt(format_args!("Access denied for process {}", pid))
            }
            ProcessError::Load(e) => fmt::Display::fmt(e, f),
        }
    }
}

impl error::Error for ProcessError {
    fn source(&self) -> Option<&(dyn error::Error + 'static)> {
        match self {
            ProcessError::Load(e) => Some(e),
            _ => None,
        }
    }
}

impl From<Error> for ProcessError {
    fn from(e: Error) -> Self {
        ProcessError::Load(e)
    }
}

impl From<io::Error> for ProcessError {
    fn from(e: io::Error) -> Self {
        ProcessError::from(Error::from(e))
    }
}