linux_proc/
uptime.rs

1//! Bindings to `/proc/uptime`.
2use std::collections::HashMap;
3use std::fs::File;
4use std::io;
5use std::time::Duration;
6
7use crate::{util, Error};
8
9pub struct Uptime {
10    /// The time the system has been up for.
11    pub up: Duration,
12    /// The time any core has been idle for. This may be more than the uptime if the system has
13    /// multiple cores.
14    pub idle: Duration,
15}
16
17impl Uptime {
18    const PATH: &'static str = "/proc/uptime";
19    /// Parse the contents of `/proc/uptime`.
20    pub fn from_system() -> io::Result<Self> {
21        Uptime::from_reader(File::open(Self::PATH)?)
22    }
23
24    pub fn from_reader(reader: impl io::Read) -> io::Result<Self> {
25        let mut reader = util::LineParser::new(reader);
26        let uptime = reader.parse_line(Self::from_str)?;
27        Ok(uptime)
28    }
29
30    pub fn from_str(input: &str) -> Result<Self, Error> {
31        let (input, up_secs) = util::parse_u64(input).ok_or("expected number")?;
32        let input = util::expect_bytes(".", input).ok_or("expected \".\"")?;
33        let (input, up_nanos) = util::parse_nanos(input).ok_or("expected number")?;
34        let (input, idle_secs) = util::parse_u64(input).ok_or("expected number")?;
35        let input = util::expect_bytes(".", input).ok_or("expected \".\"")?;
36        let (_input, idle_nanos) = util::parse_nanos(input).ok_or("expected number")?;
37        Ok(Uptime {
38            up: Duration::new(up_secs, up_nanos),
39            idle: Duration::new(idle_secs, idle_nanos),
40        })
41    }
42}
43
44#[cfg(test)]
45mod tests {
46    use super::Uptime;
47    use std::io;
48
49    #[test]
50    fn proc_uptime() {
51        let raw = "\
52            1640919.14 2328903.47
53";
54        let _stat = Uptime::from_reader(io::Cursor::new(raw)).unwrap();
55    }
56}