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
define_struct!{
pub struct Swap {
filename: String,
r#type: String,
size: usize,
used: usize,
priority: isize,
}
}
use std::str::FromStr;
impl FromStr for Swap {
type Err = crate::ProcErr;
fn from_str(value: &str) -> Result<Self, Self::Err> {
let columns: Vec<&str> = value.split_ascii_whitespace().collect();
if columns.len() != 5 {
return Err("no enough fields".into());
}
let filename = columns[0].to_string();
let r#type = columns[1].to_string();
let size = columns[2].parse::<usize>()?;
let used = columns[3].parse::<usize>()?;
let priority = columns[4].parse::<isize>()?;
Ok(Swap {
filename,
r#type,
size,
used,
priority,
})
}
}
list_impl!{
swaps, "/proc/swaps", Swap, '\n', 1
}
#[cfg(test)]
mod test {
use super::*;
#[test]
fn test_parse_swap() {
let source = "/swapfile file 969964 0 -2";
let correct = Swap{
filename: "/swapfile".to_string(),
r#type: "file".to_string(),
size: 969964,
used: 0,
priority: -2
};
assert_eq!(correct, source.parse::<Swap>().unwrap());
}
}