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
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
use {
crate::*,
std::{
fs::File,
io::Read,
},
};
pub struct ProcStatus {
content: String,
}
impl ProcStatus {
pub fn read() -> Result<Self, ProcStatusError> {
Self::read_for(ProcRef::ProcSelf)
}
pub fn read_for(proc_ref: ProcRef) -> Result<Self, ProcStatusError> {
let mut file = match proc_ref {
ProcRef::ProcSelf => File::open("/proc/self/status"),
ProcRef::ProcId(id) => File::open(format!("/proc/{}/status", id)),
}?;
let mut content = String::new();
file.read_to_string(&mut content)?;
Ok(Self { content })
}
pub fn entries(&self) -> ProcEntries<'_> {
ProcEntries::from_content(&self.content)
}
pub fn entry(&self, key: &str) -> Result<ProcEntry<'_>, ProcStatusError> {
for entry in self.entries() {
let entry = entry?;
if entry.key == key {
return Ok(entry);
}
}
Err(ProcStatusError::EntryNotFound(key.to_string()))
}
pub fn value(&self, key: &str) -> Result<&str, ProcStatusError> {
self.entry(key).map(|e| e.value)
}
#[allow(non_snake_case)]
pub fn value_KiB(&self, key: &str) -> Result<usize, ProcStatusError> {
self.entry(key).and_then(|e| e.in_KiB())
}
pub fn mem_usage(&self) -> Result<MemUsage, ProcStatusError> {
self.value_KiB("VmRSS")
.and_then(|current| {
self.value_KiB("VmPeak")
.map(|peak| MemUsage {
current: current * 1024,
peak: peak * 1024,
})
})
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_read() {
let ps = ProcStatus::read().unwrap();
let name = ps.value("Name").unwrap();
println!("name: {:?}", name);
println!("VM peak: {:?}", ps.value("VmPeak").unwrap());
println!("VM peak KiB: {:?}", ps.entry("VmPeak").unwrap().in_KiB().unwrap());
mem_usage().unwrap();
}
}