1use serde::{Deserialize, Serialize};
2use std::fs::File;
3use std::io::Read;
4#[derive(Default, Debug, Serialize, Deserialize)]
5pub struct Memory {
6 pub total: i64,
7 pub free: i64,
8 pub used: i64,
9 pub avaliable: i64,
10 pub buffer_or_cached: i64,
11 pub swap_total: i64,
12 pub swap_used: i64,
13 pub swap_free: i64,
14}
15
16pub fn get_memory() -> Result<Memory, String> {
17 let mut file = match File::open("/proc/meminfo") {
18 Ok(o) => o,
19 Err(err) => return Err(err.to_string()),
20 };
21 let mut content = String::new();
22 match file.read_to_string(&mut content) {
23 Ok(_) => {}
24 Err(err) => return Err(err.to_string()),
25 };
26 let mut memory = Memory::default();
27 for i in content.split("\n") {
28 let fields: Vec<&str> = i.split(":").collect();
29 match fields[0].trim() {
30 "MemTotal" => {
31 memory.total = String::from(fields[1].trim())
32 .replace(" kB", "")
33 .parse::<i64>()
34 .unwrap();
35 }
36 "MemFree" => {
37 memory.free = String::from(fields[1].trim())
38 .replace(" kB", "")
39 .parse::<i64>()
40 .unwrap();
41 }
42 "MemAvailable" => {
43 memory.avaliable = String::from(fields[1].trim())
44 .replace(" kB", "")
45 .parse::<i64>()
46 .unwrap();
47 }
48 "Buffers" => {
49 memory.buffer_or_cached += String::from(fields[1].trim())
50 .replace(" kB", "")
51 .parse::<i64>()
52 .unwrap();
53 }
54 "Cached" => {
55 memory.buffer_or_cached += String::from(fields[1].trim())
56 .replace(" kB", "")
57 .parse::<i64>()
58 .unwrap();
59 }
60 "SReclaimable" => {
61 memory.buffer_or_cached += String::from(fields[1].trim())
62 .replace(" kB", "")
63 .parse::<i64>()
64 .unwrap();
65 }
66 "SwapTotal" => {
67 memory.swap_total = String::from(fields[1].trim())
68 .replace(" kB", "")
69 .parse::<i64>()
70 .unwrap();
71 }
72 "SwapFree" => {
73 memory.swap_free = String::from(fields[1].trim())
74 .replace(" kB", "")
75 .parse::<i64>()
76 .unwrap();
77 }
78 _ => {}
79 }
80 memory.used = memory.total - memory.buffer_or_cached - memory.free;
81 memory.swap_used = memory.swap_total - memory.swap_free;
82 }
83 Ok(memory)
84}
85#[test]
86fn get_memory_stat_test() {
87 println!("{:?}", get_memory());
88}