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
pub mod backends;
mod config;
mod device;
mod key;

use std::{
    fmt::{self, Display, Formatter},
    str::FromStr,
};

pub use crate::{config::*, device::*, key::*};

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Backend {
    #[cfg(target_os = "linux")]
    Kernel,
    Userspace,
}

impl Default for Backend {
    fn default() -> Self {
        #[cfg(target_os = "linux")]
        {
            Self::Kernel
        }

        #[cfg(not(target_os = "linux"))]
        {
            Self::Userspace
        }
    }
}

impl Display for Backend {
    fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
        match self {
            #[cfg(target_os = "linux")]
            Self::Kernel => write!(f, "kernel"),
            Self::Userspace => write!(f, "userspace"),
        }
    }
}

impl FromStr for Backend {
    type Err = String;

    fn from_str(s: &str) -> Result<Self, Self::Err> {
        match s.to_ascii_lowercase().as_str() {
            #[cfg(target_os = "linux")]
            "kernel" => Ok(Self::Kernel),
            "userspace" => Ok(Self::Userspace),
            _ => Err(format!("valid values: {}.", Self::variants().join(", "))),
        }
    }
}

impl Backend {
    pub fn variants() -> &'static [&'static str] {
        #[cfg(target_os = "linux")]
        {
            &["kernel", "userspace"]
        }

        #[cfg(not(target_os = "linux"))]
        {
            &["userspace"]
        }
    }
}