diff --git a/src/main.rs b/src/main.rs index 785d28b..6a02f39 100644 --- a/src/main.rs +++ b/src/main.rs @@ -1,3 +1,4 @@ +mod proc; mod swaybar_object; fn main() { @@ -11,5 +12,8 @@ fn main() { array.push_object(swaybar_object::SwaybarObject::default()); array.push_object(swaybar_object::SwaybarObject::new()); array.push_object(swaybar_object::SwaybarObject::default()); + let meminfo_string = proc::get_meminfo().expect("Should be able to get meminfo"); + let meminfo_object = swaybar_object::SwaybarObject::from_string(meminfo_string); + array.push_object(meminfo_object); println!("{}", array); } diff --git a/src/proc.rs b/src/proc.rs new file mode 100644 index 0000000..9e2d59a --- /dev/null +++ b/src/proc.rs @@ -0,0 +1,67 @@ +use std::fs::File; +use std::io; +use std::io::prelude::*; + +pub fn get_meminfo() -> io::Result { + let mut meminfo_string = String::new(); + { + let mut meminfo: File = File::open("/proc/meminfo")?; + meminfo.read_to_string(&mut meminfo_string)?; + } + + let mut is_total_giga = false; + let mut total: u32 = 0; + let mut available: u32 = 0; + for line in meminfo_string.lines() { + if line.starts_with("MemTotal:") { + let line_parts = line + .split_whitespace() + .map(|s| s.to_owned()) + .collect::>(); + total = line_parts[1] + .parse() + .map_err(|_| io::Error::new(io::ErrorKind::Other, "MemTotal: parse error"))?; + } else if line.starts_with("MemAvailable:") { + let line_parts = line + .split_whitespace() + .map(|s| s.to_owned()) + .collect::>(); + available = line_parts[1] + .parse() + .map_err(|_| io::Error::new(io::ErrorKind::Other, "MemAvailable: parse error"))?; + } + } + + let mut used = total - available; + let mut is_used_giga = false; + + if total == 0 { + Ok("0".into()) + } else { + if total > 1024 { + total /= 1024; + is_total_giga = true; + } + + if used > 1024 { + used /= 1024; + is_used_giga = true; + } + + let mut output = format!("{} ", used); + if is_used_giga { + output.push_str("GiB / "); + } else { + output.push_str("KiB / "); + } + + output.push_str(&format!("{} ", total)); + if is_total_giga { + output.push_str("GiB"); + } else { + output.push_str("KiB"); + } + + Ok(output) + } +} diff --git a/src/swaybar_object.rs b/src/swaybar_object.rs index 4ae99df..ff97331 100644 --- a/src/swaybar_object.rs +++ b/src/swaybar_object.rs @@ -89,6 +89,28 @@ impl SwaybarObject { markup: None, } } + + pub fn from_string(string: String) -> Self { + Self { + full_text: string, + short_text: None, + color: None, + background: None, + border: None, + border_top: None, + border_bottom: None, + border_left: None, + border_right: None, + min_width: None, + align: None, + name: None, + instance: None, + urgent: None, + separator: None, + separator_block_width: None, + markup: None, + } + } } impl Default for SwaybarObject {