proc_getter/proc/
crypto.rs

1use crate::{Error, Result};
2use std::collections::HashMap;
3use std::ops::Deref;
4use std::str::FromStr;
5
6/// represent an entry in /proc/crypto
7///
8/// ```
9/// use proc_getter::crypto::*;
10///
11/// let info = crypto().unwrap();
12/// assert_eq!(info[0].name(), info[0].get("name").unwrap());
13/// ```
14#[derive(Debug)]
15pub struct Crypto(HashMap<String, String>);
16
17impl Crypto {
18    pub fn name(&self) -> &str {
19        self.get("name").unwrap()
20    }
21
22    pub fn driver(&self) -> &str {
23        self.get("driver").unwrap()
24    }
25
26    pub fn module(&self) -> &str {
27        self.get("module").unwrap()
28    }
29
30    pub fn selftest(&self) -> bool {
31        self.get("selftest").unwrap() == "passed"
32    }
33
34    pub fn refcnt(&self) -> usize {
35        self.get("refcnt").unwrap().parse::<usize>().unwrap()
36    }
37
38    pub fn priority(&self) -> usize {
39        self.get("priority").unwrap().parse::<usize>().unwrap()
40    }
41
42    pub fn r#type(&self) -> &str {
43        self.get("type").unwrap()
44    }
45}
46
47impl Deref for Crypto {
48    type Target = HashMap<String, String>;
49
50    fn deref(&self) -> &HashMap<String, String> {
51        &self.0
52    }
53}
54
55impl FromStr for Crypto {
56    type Err = Error;
57
58    fn from_str(value: &str) -> Result<Self> {
59        let mut ret = HashMap::new();
60        for line in value.trim().lines() {
61            let columns: Vec<&str> = line.split(':').collect();
62            if columns.len() != 2 {
63                return Err(Error::BadFormat);
64            }
65            ret.insert(columns[0].trim().to_string(), columns[1].trim().to_string());
66        }
67        Ok(Crypto(ret))
68    }
69}
70
71#[inline(always)]
72fn to_crypto(block: &str) -> Result<Crypto> {
73    Crypto::from_str(block)
74}
75
76default_list! {
77    crypto, "/proc/crypto", Crypto, to_crypto, "\n\n"
78}
79
80#[cfg(test)]
81mod test {
82    use super::*;
83
84    #[test]
85    fn getter() {
86        let source = r#"
87name         : sha1
88driver       : sha1-ssse3
89module       : kernel
90priority     : 150
91refcnt       : 5
92selftest     : passed
93type         : shash
94blocksize    : 64
95digestsize   : 20
96"#;
97        let c = Crypto::from_str(source.trim()).unwrap();
98        assert_eq!(c.get("name").unwrap(), c.name());
99        assert_eq!(c.get("driver").unwrap(), c.driver());
100        assert_eq!(c.get("module").unwrap(), c.module());
101        assert_eq!(c.get("priority").unwrap(), &c.priority().to_string());
102        assert_eq!(c.get("refcnt").unwrap(), &c.refcnt().to_string());
103        assert_eq!(c.get("selftest").unwrap() == "passed", c.selftest());
104        assert_eq!(c.get("type").unwrap(), c.r#type());
105    }
106}