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
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
use std::{fs, io};
use std::path::Path;
use std::time::Duration;
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Uptime {
raw: String
}
impl Uptime {
fn path() -> &'static Path {
Path::new("/proc/uptime")
}
#[cfg(test)]
fn from_string(raw: String) -> Self {
Self {raw}
}
pub fn read() -> io::Result<Self> {
Ok(Self {
raw: fs::read_to_string(Self::path())?
})
}
pub fn all_infos<'a>(&'a self) -> impl Iterator<Item=Duration> + 'a {
self.raw.split(' ')
.filter_map(|v| v.trim().parse().ok())
.map(Duration::from_secs_f64)
}
pub fn uptime(&self) -> Option<Duration> {
self.all_infos().next()
}
pub fn idletime(&self) -> Option<Duration> {
self.all_infos().nth(1)
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Hostname {
raw: String
}
impl Hostname {
fn path() -> &'static Path {
Path::new("/proc/sys/kernel/hostname")
}
#[cfg(test)]
fn from_string(raw: String) -> Self {
Self {raw}
}
pub fn read() -> io::Result<Self> {
Ok(Self {
raw: fs::read_to_string(Self::path())?
})
}
pub fn hostname(&self) -> &str {
self.raw.trim()
}
pub fn into_string(self) -> String {
self.raw
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct OsRelease {
raw: String
}
impl OsRelease {
fn path() -> &'static Path {
Path::new("/proc/sys/kernel/osrelease")
}
#[cfg(test)]
fn from_string(raw: String) -> Self {
Self {raw}
}
pub fn read() -> io::Result<Self> {
Ok(Self {
raw: fs::read_to_string(Self::path())?
})
}
pub fn full_str(&self) -> &str {
self.raw.trim()
}
pub fn into_string(self) -> String {
self.raw
}
}
#[cfg(test)]
mod tests {
use super::*;
fn uptime() -> Uptime {
Uptime::from_string("220420.83 5275548.45\n".into())
}
#[test]
fn uptime_methods() {
assert_eq!(uptime().uptime().unwrap().as_secs(), 220420);
assert_eq!(uptime().idletime().unwrap().as_secs(), 5275548);
}
#[test]
fn hostname() {
let name = Hostname::from_string("test-hostname\n".into());
assert_eq!(name.hostname(), "test-hostname");
}
#[test]
fn os_release() {
let name = OsRelease::from_string("test-hostname\n".into());
assert_eq!(name.full_str(), "test-hostname");
}
}