1use libc::SI_LOAD_SHIFT;
2use std::time::Duration;
3use std::{cmp, mem};
4
5use crate::errno::Errno;
6use crate::Result;
7
8#[derive(Copy, Clone, Debug, Eq, Hash, PartialEq)]
10#[repr(transparent)]
11pub struct SysInfo(libc::sysinfo);
12
13#[cfg(all(target_arch = "x86_64", target_pointer_width = "32"))]
15type mem_blocks_t = u64;
16#[cfg(not(all(target_arch = "x86_64", target_pointer_width = "32")))]
17type mem_blocks_t = libc::c_ulong;
18
19impl SysInfo {
20 pub fn load_average(&self) -> (f64, f64, f64) {
25 (
26 self.0.loads[0] as f64 / (1 << SI_LOAD_SHIFT) as f64,
27 self.0.loads[1] as f64 / (1 << SI_LOAD_SHIFT) as f64,
28 self.0.loads[2] as f64 / (1 << SI_LOAD_SHIFT) as f64,
29 )
30 }
31
32 #[allow(clippy::unnecessary_cast)]
35 pub fn uptime(&self) -> Duration {
36 Duration::from_secs(cmp::max(self.0.uptime, 0) as u64)
38 }
39
40 pub fn process_count(&self) -> u16 {
42 self.0.procs
43 }
44
45 pub fn swap_total(&self) -> u64 {
47 self.scale_mem(self.0.totalswap)
48 }
49
50 pub fn swap_free(&self) -> u64 {
52 self.scale_mem(self.0.freeswap)
53 }
54
55 pub fn ram_total(&self) -> u64 {
57 self.scale_mem(self.0.totalram)
58 }
59
60 pub fn ram_unused(&self) -> u64 {
66 self.scale_mem(self.0.freeram)
67 }
68
69 #[allow(clippy::unnecessary_cast)]
71 fn scale_mem(&self, units: mem_blocks_t) -> u64 {
72 units as u64 * self.0.mem_unit as u64
73 }
74}
75
76pub fn sysinfo() -> Result<SysInfo> {
80 let mut info = mem::MaybeUninit::uninit();
81 let res = unsafe { libc::sysinfo(info.as_mut_ptr()) };
82 Errno::result(res).map(|_| unsafe { SysInfo(info.assume_init()) })
83}