1use std::path::Path;
21
22#[derive(Debug, Clone, Copy, PartialEq, Eq)]
24pub struct MemoryInfo {
25 pub total_bytes: u64,
26 pub available_bytes: u64,
29}
30
31#[derive(Debug, Clone, Copy, PartialEq, Eq)]
33pub struct DiskSpace {
34 pub total_bytes: u64,
35 pub free_bytes: u64,
39}
40
41pub fn memory() -> Option<MemoryInfo> {
43 platform_memory()
44}
45
46pub fn load_average() -> Option<[f64; 3]> {
50 #[cfg(unix)]
51 {
52 let mut loads = [0f64; 3];
53 #[allow(unsafe_code)]
56 let n = unsafe { libc::getloadavg(loads.as_mut_ptr(), 3) };
57 (n == 3).then_some(loads)
58 }
59 #[cfg(not(unix))]
60 {
61 None
62 }
63}
64
65pub fn disk_space(path: &Path) -> Option<DiskSpace> {
67 platform_disk_space(path)
68}
69
70#[cfg(target_os = "linux")]
71fn platform_memory() -> Option<MemoryInfo> {
72 let text = std::fs::read_to_string("/proc/meminfo").ok()?;
73 parse_meminfo(&text)
74}
75
76#[cfg(any(target_os = "linux", test))]
78fn parse_meminfo(text: &str) -> Option<MemoryInfo> {
79 let field = |name: &str| -> Option<u64> {
80 let line = text.lines().find(|l| l.starts_with(name))?;
81 let rest = line[name.len()..].trim_start_matches(':').trim();
82 let kib: u64 = rest.split_whitespace().next()?.parse().ok()?;
83 kib.checked_mul(1024)
84 };
85 Some(MemoryInfo {
86 total_bytes: field("MemTotal")?,
87 available_bytes: field("MemAvailable")?,
88 })
89}
90
91#[cfg(target_os = "macos")]
92fn platform_memory() -> Option<MemoryInfo> {
93 let total_bytes = macos_memsize()?;
94 let page_size = macos_page_size()?;
95 let (free, inactive) = macos_free_and_inactive_pages()?;
96 Some(MemoryInfo {
97 total_bytes,
98 available_bytes: (free + inactive).saturating_mul(page_size).min(total_bytes),
99 })
100}
101
102#[cfg(target_os = "macos")]
103fn macos_memsize() -> Option<u64> {
104 let mut value: u64 = 0;
105 let mut len: libc::size_t = std::mem::size_of::<u64>();
106 #[allow(unsafe_code)]
110 let result = unsafe {
111 libc::sysctlbyname(
112 c"hw.memsize".as_ptr(),
113 (&mut value as *mut u64).cast(),
114 &mut len,
115 std::ptr::null_mut(),
116 0,
117 )
118 };
119 (result == 0 && len == std::mem::size_of::<u64>() && value > 0).then_some(value)
120}
121
122#[cfg(target_os = "macos")]
123fn macos_page_size() -> Option<u64> {
124 #[allow(unsafe_code)]
126 let size = unsafe { libc::sysconf(libc::_SC_PAGESIZE) };
127 u64::try_from(size).ok().filter(|s| *s > 0)
128}
129
130#[cfg(target_os = "macos")]
131#[allow(deprecated)] fn macos_free_and_inactive_pages() -> Option<(u64, u64)> {
133 #[allow(unsafe_code)]
136 let mut stats: libc::vm_statistics64 = unsafe { std::mem::zeroed() };
137 let mut count = libc::HOST_VM_INFO64_COUNT;
138 static HOST_PORT: std::sync::OnceLock<libc::mach_port_t> = std::sync::OnceLock::new();
142 #[allow(unsafe_code)]
144 let host = *HOST_PORT.get_or_init(|| unsafe { libc::mach_host_self() });
145 #[allow(unsafe_code)]
149 let result = unsafe {
150 libc::host_statistics64(
151 host,
152 libc::HOST_VM_INFO64,
153 (&mut stats as *mut libc::vm_statistics64).cast(),
154 &mut count,
155 )
156 };
157 (result == libc::KERN_SUCCESS)
158 .then(|| (u64::from(stats.free_count), u64::from(stats.inactive_count)))
159}
160
161#[cfg(windows)]
162fn platform_memory() -> Option<MemoryInfo> {
163 use windows_sys::Win32::System::SystemInformation::{GlobalMemoryStatusEx, MEMORYSTATUSEX};
164 #[allow(unsafe_code)]
166 let mut status: MEMORYSTATUSEX = unsafe { std::mem::zeroed() };
167 status.dwLength = std::mem::size_of::<MEMORYSTATUSEX>() as u32;
168 #[allow(unsafe_code)]
171 let ok = unsafe { GlobalMemoryStatusEx(&mut status) };
172 (ok != 0 && status.ullTotalPhys > 0).then_some(MemoryInfo {
173 total_bytes: status.ullTotalPhys,
174 available_bytes: status.ullAvailPhys,
175 })
176}
177
178#[cfg(not(any(target_os = "linux", target_os = "macos", windows)))]
179fn platform_memory() -> Option<MemoryInfo> {
180 None
181}
182
183#[cfg(unix)]
184fn platform_disk_space(path: &Path) -> Option<DiskSpace> {
185 use std::os::unix::ffi::OsStrExt;
186 let c_path = std::ffi::CString::new(path.as_os_str().as_bytes()).ok()?;
187 #[allow(unsafe_code)]
189 let mut st: libc::statvfs = unsafe { std::mem::zeroed() };
190 #[allow(unsafe_code)]
193 let result = unsafe { libc::statvfs(c_path.as_ptr(), &mut st) };
194 if result != 0 {
195 return None;
196 }
197 #[allow(clippy::unnecessary_cast)] let unit = st.f_frsize as u64;
200 #[allow(clippy::unnecessary_cast)]
201 let (blocks, avail) = (st.f_blocks as u64, st.f_bavail as u64);
202 let total_bytes = blocks.checked_mul(unit)?;
203 (total_bytes > 0).then(|| DiskSpace {
204 total_bytes,
205 free_bytes: avail.saturating_mul(unit),
206 })
207}
208
209#[cfg(windows)]
210fn platform_disk_space(path: &Path) -> Option<DiskSpace> {
211 use std::os::windows::ffi::OsStrExt;
212 use windows_sys::Win32::Storage::FileSystem::GetDiskFreeSpaceExW;
213 let wide: Vec<u16> = path
214 .as_os_str()
215 .encode_wide()
216 .chain(std::iter::once(0))
217 .collect();
218 let (mut free_to_caller, mut total, mut _free_total) = (0u64, 0u64, 0u64);
219 #[allow(unsafe_code)]
222 let ok = unsafe {
223 GetDiskFreeSpaceExW(
224 wide.as_ptr(),
225 &mut free_to_caller,
226 &mut total,
227 &mut _free_total,
228 )
229 };
230 (ok != 0 && total > 0).then_some(DiskSpace {
231 total_bytes: total,
232 free_bytes: free_to_caller,
233 })
234}
235
236#[cfg(not(any(unix, windows)))]
237fn platform_disk_space(_path: &Path) -> Option<DiskSpace> {
238 None
239}
240
241#[cfg(test)]
242mod tests {
243 use super::*;
244
245 #[test]
246 fn meminfo_text_parses_to_bytes() {
247 let text = "MemTotal: 16314952 kB\nMemFree: 1000 kB\nMemAvailable: 12002000 kB\n";
248 assert_eq!(
249 parse_meminfo(text),
250 Some(MemoryInfo {
251 total_bytes: 16_314_952 * 1024,
252 available_bytes: 12_002_000 * 1024,
253 })
254 );
255 assert_eq!(parse_meminfo("MemTotal: 5 kB\n"), None);
256 }
257
258 #[cfg(any(target_os = "linux", target_os = "macos", windows))]
259 #[test]
260 fn memory_is_plausible() {
261 let m = memory().expect("this platform reports memory");
262 assert!(m.total_bytes >= 64 << 20, "{m:?}");
264 assert!(m.total_bytes <= 64 << 40, "{m:?}");
265 assert!(m.available_bytes > 0, "{m:?}");
266 assert!(m.available_bytes <= m.total_bytes, "{m:?}");
267 }
268
269 #[cfg(unix)]
270 #[test]
271 fn load_average_is_plausible() {
272 let [one, five, fifteen] = load_average().expect("unix reports load");
273 for l in [one, five, fifteen] {
274 assert!(l.is_finite() && l >= 0.0, "{one} {five} {fifteen}");
275 assert!(l < 100_000.0, "{one} {five} {fifteen}");
277 }
278 }
279
280 #[cfg(windows)]
281 #[test]
282 fn windows_has_no_load_average() {
283 assert_eq!(load_average(), None);
284 }
285
286 #[cfg(any(unix, windows))]
287 #[test]
288 fn disk_space_is_plausible() {
289 let dir = std::env::temp_dir();
290 let d = disk_space(&dir).expect("the temp directory's filesystem reports space");
291 assert!(d.total_bytes >= 1 << 20, "{d:?}");
292 assert!(d.free_bytes <= d.total_bytes, "{d:?}");
293 }
294
295 #[test]
296 fn a_missing_path_has_no_disk_space() {
297 assert_eq!(
298 disk_space(Path::new("/definitely/not/a/real/path/for/subc-os")),
299 None
300 );
301 }
302}