hw_linux/
memory.rs

1use crate::{is_linux, InfoTrait};
2use std::error::Error;
3use std::fs;
4
5#[derive(Default, Clone, Debug)]
6pub struct MemoryInfo {
7    pub total: Option<f64>,
8    pub used: Option<f64>,
9    pub free: Option<f64>,
10}
11
12#[derive(Default, Clone, Debug)]
13pub struct SwapInfo {
14    pub total: Option<f64>,
15    pub used: Option<f64>,
16    pub free: Option<f64>,
17}
18
19impl InfoTrait for SwapInfo {
20    fn get() -> Result<Self, Box<dyn Error>> {
21        let _ = is_linux()?;
22        let mut total = 0_f64;
23        let mut free = 0_f64;
24        fs::read_to_string("/proc/meminfo")?
25            .split('\n')
26            .for_each(|i| {
27                let inf = i.split(':').collect::<Vec<&str>>();
28                if inf.len() > 1 {
29                    let key = inf[0].trim();
30                    let val = inf[1]
31                        .replace("kB", "")
32                        .replace("\n", "")
33                        .trim()
34                        .parse::<f64>()
35                        .unwrap();
36
37                    match key {
38                        "SwapTotal" => {
39                            total = val;
40                        }
41                        "SwapFree" => {
42                            free = val;
43                        }
44                        &_ => (),
45                    }
46                }
47            });
48
49        let mut swap = Self::default();
50        swap.used = Some((total - free) / 1024_f64);
51        swap.total = Some(total / 1024_f64);
52        swap.free = Some(free / 1024_f64);
53        Ok(swap)
54    }
55}
56
57impl InfoTrait for MemoryInfo {
58    fn get() -> Result<Self, Box<dyn Error>> {
59        let _ = is_linux()?;
60        let mut total = 0_f64;
61        let mut free = 0_f64;
62        fs::read_to_string("/proc/meminfo")?
63            .split('\n')
64            .for_each(|i| {
65                let inf = i.split(':').collect::<Vec<&str>>();
66                if inf.len() > 1 {
67                    let key = inf[0].trim();
68                    let val = inf[1]
69                        .replace("kB", "")
70                        .replace("\n", "")
71                        .trim()
72                        .parse::<f64>()
73                        .unwrap();
74
75                    match key {
76                        "MemTotal" => {
77                            total = val;
78                        }
79                        "MemAvailable" => {
80                            free = val;
81                        }
82                        &_ => (),
83                    }
84                }
85            });
86
87        let mut mem = Self::default();
88        mem.used = Some((total - free) / 1024_f64);
89        mem.total = Some(total / 1024_f64);
90        mem.free = Some(free / 1024_f64);
91        Ok(mem)
92    }
93}