Files
addr2line
adler
aho_corasick
arrayvec
atty
backtrace
bitflags
camino
cargo_metadata
cargo_nextest
cargo_platform
cfg_expr
cfg_if
chrono
clap
clap_derive
color_eyre
config
crossbeam_channel
crossbeam_deque
crossbeam_epoch
crossbeam_utils
ctrlc
datatest_stable
debug_ignore
duct
either
enable_ansi_support
env_logger
eyre
fixedbitset
gimli
guppy
guppy_workspace_hack
hashbrown
humantime
humantime_serde
indent_write
indenter
indexmap
is_ci
itertools
itoa
lazy_static
lexical_core
libc
log
memchr
memoffset
miniz_oxide
nested
nextest_metadata
nextest_runner
nix
nom
num_cpus
num_integer
num_traits
object
once_cell
os_pipe
os_str_bytes
owo_colors
pathdiff
petgraph
proc_macro2
proc_macro_error
proc_macro_error_attr
quick_junit
quick_xml
quote
rayon
rayon_core
regex
regex_syntax
rustc_demangle
ryu
same_file
scopeguard
semver
serde
serde_derive
serde_json
shared_child
shellwords
smallvec
static_assertions
strip_ansi_escapes
strsim
structopt
structopt_derive
supports_color
syn
target_lexicon
target_spec
termcolor
textwrap
time
toml
twox_hash
unicode_xid
utf8parse
vte
vte_generate_state_changes
walkdir
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
use libc::{self, SI_LOAD_SHIFT};
use std::{cmp, mem};
use std::time::Duration;

use crate::Result;
use crate::errno::Errno;

/// System info structure returned by `sysinfo`.
#[derive(Copy, Clone, Debug, Eq, Hash, PartialEq)]
#[repr(transparent)]
pub struct SysInfo(libc::sysinfo);

// The fields are c_ulong on 32-bit linux, u64 on 64-bit linux; x32's ulong is u32
#[cfg(all(target_arch = "x86_64", target_pointer_width = "32"))]
type mem_blocks_t = u64;
#[cfg(not(all(target_arch = "x86_64", target_pointer_width = "32")))]
type mem_blocks_t = libc::c_ulong;

impl SysInfo {
    /// Returns the load average tuple.
    ///
    /// The returned values represent the load average over time intervals of
    /// 1, 5, and 15 minutes, respectively.
    pub fn load_average(&self) -> (f64, f64, f64) {
        (
            self.0.loads[0] as f64 / (1 << SI_LOAD_SHIFT) as f64,
            self.0.loads[1] as f64 / (1 << SI_LOAD_SHIFT) as f64,
            self.0.loads[2] as f64 / (1 << SI_LOAD_SHIFT) as f64,
        )
    }

    /// Returns the time since system boot.
    pub fn uptime(&self) -> Duration {
        // Truncate negative values to 0
        Duration::from_secs(cmp::max(self.0.uptime, 0) as u64)
    }

    /// Current number of processes.
    pub fn process_count(&self) -> u16 {
        self.0.procs
    }

    /// Returns the amount of swap memory in Bytes.
    pub fn swap_total(&self) -> u64 {
        self.scale_mem(self.0.totalswap)
    }

    /// Returns the amount of unused swap memory in Bytes.
    pub fn swap_free(&self) -> u64 {
        self.scale_mem(self.0.freeswap)
    }

    /// Returns the total amount of installed RAM in Bytes.
    pub fn ram_total(&self) -> u64 {
        self.scale_mem(self.0.totalram)
    }

    /// Returns the amount of completely unused RAM in Bytes.
    ///
    /// "Unused" in this context means that the RAM in neither actively used by
    /// programs, nor by the operating system as disk cache or buffer. It is
    /// "wasted" RAM since it currently serves no purpose.
    pub fn ram_unused(&self) -> u64 {
        self.scale_mem(self.0.freeram)
    }

    fn scale_mem(&self, units: mem_blocks_t) -> u64 {
        units as u64 * self.0.mem_unit as u64
    }
}

/// Returns system information.
///
/// [See `sysinfo(2)`](https://man7.org/linux/man-pages/man2/sysinfo.2.html).
pub fn sysinfo() -> Result<SysInfo> {
    let mut info = mem::MaybeUninit::uninit();
    let res = unsafe { libc::sysinfo(info.as_mut_ptr()) };
    Errno::result(res).map(|_| unsafe{ SysInfo(info.assume_init()) })
}