diff options
author | Mustafa Salih <37256744+MustafaSalih1993@users.noreply.github.com> | 2021-01-14 05:43:01 +0300 |
---|---|---|
committer | GitHub <noreply@github.com> | 2021-01-14 05:43:01 +0300 |
commit | e38859e0f0106b60f2dd6d2f8260ea16e5417a96 (patch) | |
tree | acdd23279a8fc837fa076739933b1269d74110fd /src/utils/memory.rs | |
parent | e829871f2d757c7414763992839a584038c7b443 (diff) | |
parent | 6a349a0e0282e56b03adbe02b41bfaf0cc3213f1 (diff) |
Merge pull request #34 from MustafaSalih1993/dev
orginized the code to seprated mods and deleted the lib file
Diffstat (limited to 'src/utils/memory.rs')
-rw-r--r-- | src/utils/memory.rs | 85 |
1 files changed, 85 insertions, 0 deletions
diff --git a/src/utils/memory.rs b/src/utils/memory.rs new file mode 100644 index 0000000..1a6c982 --- /dev/null +++ b/src/utils/memory.rs @@ -0,0 +1,85 @@ +use crate::types::Config; +use std::fs::File; +use std::io::Read; + +/* +mem_used = (mem_total + shmem - mem_free - mem_buffers - mem_cached - mem_srecl +thanks for htop's developer on stackoverflow for providing this algorithm to +calculate used memory. +*/ +pub fn get_memory(config: &Config) -> Result<String, std::io::Error> { + let mut buf = String::new(); + + File::open("/proc/meminfo")?.read_to_string(&mut buf)?; + + let mut mem_total: u32 = 0; + let mut shmem: u32 = 0; + let mut mem_free: u32 = 0; + let mut mem_buffers: u32 = 0; + let mut mem_cached: u32 = 0; + let mut mem_srecl: u32 = 0; + + for line in buf.lines() { + if mem_total > 0 + && shmem > 0 + && mem_free > 0 + && mem_buffers > 0 + && mem_cached > 0 + && mem_srecl > 0 + { + break; + } + if line.starts_with("MemTotal") { + assign_val(line, &mut mem_total); + } + if line.starts_with("SReclaimable") { + assign_val(line, &mut mem_srecl) + } + if line.starts_with("Cached") { + assign_val(line, &mut mem_cached) + } + + if line.starts_with("Shmem") { + assign_val(line, &mut shmem); + } + + if line.starts_with("MemFree") { + assign_val(line, &mut mem_free); + } + if line.starts_with("Buffers") { + assign_val(line, &mut mem_buffers); + } + } + + let mem_used = (mem_total + shmem - mem_free - mem_buffers - mem_cached - mem_srecl) / 1024; + let result: String; + if mem_used > 1000 { + result = format!( + " {} {:.1}G {}", + config.memory.icon, + mem_used as f32 / 1000.0, + config.seperator + ); + } else { + result = format!( + " {} {}M {}", + config.memory.icon, mem_used, config.seperator + ); + } + Ok(result) +} + +/* +this helper function will split the line(first argument) by the character(:) +and then parse the right splited item as u32 +then assign that to the "assignable"(2nd argument). +*/ +fn assign_val(line: &str, assignable: &mut u32) { + let parsed: u32 = line.split(':').collect::<Vec<&str>>()[1] + .trim() + .split(' ') + .collect::<Vec<&str>>()[0] + .parse() + .unwrap(); + *assignable = parsed; +} |