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());
}
}