Skip to main content

veilid_tools/
system_info.rs

1#![cfg(not(all(target_arch = "wasm32", target_os = "unknown")))]
2
3use super::*;
4
5/// Total physical memory in bytes, or None if not determinable on this platform.
6#[must_use]
7pub fn total_memory_bytes() -> Option<u64> {
8    cfg_if! {
9        if #[cfg(any(target_os = "linux", target_os = "android"))] {
10            let mut si: libc::sysinfo = unsafe { core::mem::zeroed() };
11            if unsafe { libc::sysinfo(&mut si) } != 0 {
12                return None;
13            }
14            // c_ulong is u64 on 64-bit targets, u32 on 32-bit; the cast is identity or a widen
15            #[allow(clippy::unnecessary_cast)]
16            let total = si.totalram as u64;
17            #[allow(clippy::unnecessary_cast)]
18            let unit = si.mem_unit as u64;
19            total.checked_mul(unit)
20        } else if #[cfg(any(target_os = "macos", target_os = "ios"))] {
21            let mut mem: u64 = 0;
22            let mut len = core::mem::size_of::<u64>();
23            let mut mib = [libc::CTL_HW, libc::HW_MEMSIZE];
24            let res = unsafe {
25                libc::sysctl(
26                    mib.as_mut_ptr(),
27                    mib.len() as u32,
28                    (&mut mem) as *mut u64 as *mut libc::c_void,
29                    &mut len,
30                    core::ptr::null_mut(),
31                    0,
32                )
33            };
34            if res != 0 {
35                return None;
36            }
37            Some(mem)
38        } else if #[cfg(target_os = "windows")] {
39            use winapi::um::sysinfoapi::{GlobalMemoryStatusEx, MEMORYSTATUSEX};
40            let mut status: MEMORYSTATUSEX = unsafe { core::mem::zeroed() };
41            status.dwLength = core::mem::size_of::<MEMORYSTATUSEX>() as u32;
42            if unsafe { GlobalMemoryStatusEx(&mut status) } == 0 {
43                return None;
44            }
45            Some(status.ullTotalPhys)
46        } else {
47            None
48        }
49    }
50}