uptic/
lib.rs

1// MIT License
2//
3// Copyright (c) 2021 Ferhat Geçdoğan All Rights Reserved.
4// Distributed under the terms of the MIT License.
5//
6//
7// uptic - easy-to-use uptime crate for linux.
8//
9// there's Default implemented for Uptic structure, you can use it like this:
10//
11// let uptime = Uptic::default();
12
13use std::io::{BufRead};
14
15pub struct Uptic {
16    pub days   : u64,
17    pub hours  : u8,  // < 24
18    pub minutes: u8,  // < 60
19    pub raw_ss : u64
20}
21
22impl Default for Uptic {
23    fn default() -> Self {
24        let mut data = Uptic {
25            days   : 0,
26            hours  : 0,
27            minutes: 0,
28            raw_ss : 0
29        }; data.init();
30
31        data
32    }
33}
34
35impl Uptic {
36    fn read_lines<P>(&self, file: &P) -> std::io::Result<
37        std::io::Lines<std::io::BufReader<std::fs::File>>
38    > where P: AsRef<std::path::Path>, {
39        Ok(std::io::BufReader::new(
40            std::fs::File::open(file)?).lines())
41    }
42
43    #[cfg(not(target_os = "windows"))]
44    fn init(&mut self) {
45        if std::path::Path::new("/proc/uptime").exists() {
46            if let Ok(lines) = self.read_lines(&"/proc/uptime") {
47                for line in lines {
48                    if let Ok(__line__) = line {
49                        self.raw_ss = __line__.split(' ').next().unwrap().parse::<f64>().unwrap() as u64;
50                    }
51                }
52
53                self.days    = (self.raw_ss / 60 / 60 / 24) ^ 0;
54                self.hours   = ((self.raw_ss / 60 / 60 % 24) ^ 0) as u8;
55                self.minutes = ((self.raw_ss / 60      % 60) ^ 0) as u8;
56            }
57        }
58    }
59}
60
61#[cfg(test)]
62mod tests {
63    use crate::{Uptic};
64
65    #[test]
66    fn hmm() {
67        let uptime = Uptic::default();
68
69        println!("d/s({}), h/s({}), m/s({})", uptime.days, uptime.hours, uptime.minutes);
70    }
71}