oxwm

https://git.tonybtw.com/oxwm.git git://git.tonybtw.com/oxwm.git
2,056 bytes raw
1
use super::Block;
2
use crate::errors::BlockError;
3
use std::fs;
4
use std::time::Duration;
5
6
pub struct Ram {
7
    format: String,
8
    interval: Duration,
9
    color: u32,
10
}
11
12
impl Ram {
13
    pub fn new(format: &str, interval_secs: u64, color: u32) -> Self {
14
        Self {
15
            format: format.to_string(),
16
            interval: Duration::from_secs(interval_secs),
17
            color,
18
        }
19
    }
20
21
    fn get_memory_info(&self) -> Result<(u64, u64, f32), BlockError> {
22
        let meminfo = fs::read_to_string("/proc/meminfo")?;
23
        let mut total: u64 = 0;
24
        let mut available: u64 = 0;
25
26
        for line in meminfo.lines() {
27
            if line.starts_with("MemTotal:") {
28
                total = line
29
                    .split_whitespace()
30
                    .nth(1)
31
                    .and_then(|s| s.parse().ok())
32
                    .unwrap_or(0)
33
            } else if line.starts_with("MemAvailable:") {
34
                available = line
35
                    .split_whitespace()
36
                    .nth(1)
37
                    .and_then(|s| s.parse().ok())
38
                    .unwrap_or(0)
39
            }
40
        }
41
42
        let used = total.saturating_sub(available);
43
        let percentage = if total > 0 {
44
            (used as f32 / total as f32) * 100.0
45
        } else {
46
            0.0
47
        };
48
49
        Ok((used, total, percentage))
50
    }
51
}
52
53
impl Block for Ram {
54
    fn content(&mut self) -> Result<String, BlockError> {
55
        let (used, total, percentage) = self.get_memory_info()?;
56
57
        let used_gb = used as f32 / 1024.0 / 1024.0;
58
        let total_gb = total as f32 / 1024.0 / 1024.0;
59
60
        let result = self
61
            .format
62
            .replace("{used}", &format!("{:.1}", used_gb))
63
            .replace("{total}", &format!("{:.1}", total_gb))
64
            .replace("{percent}", &format!("{:.1}", percentage))
65
            .replace("{}", &format!("{:.1}", used_gb));
66
67
        Ok(result)
68
    }
69
70
    fn interval(&self) -> Duration {
71
        self.interval
72
    }
73
74
    fn color(&self) -> u32 {
75
        self.color
76
    }
77
}