agentmux_common/
disk_space.rs1use std::path::Path;
7
8#[cfg(windows)]
12pub fn volume_free_total_bytes(path: &Path) -> Option<(u64, u64)> {
13 use std::os::windows::ffi::OsStrExt;
14 use windows_sys::Win32::Storage::FileSystem::GetDiskFreeSpaceExW;
15 let wide: Vec<u16> = path.as_os_str().encode_wide().chain(std::iter::once(0)).collect();
16 let mut free_available: u64 = 0;
17 let mut total: u64 = 0;
18 let ok = unsafe { GetDiskFreeSpaceExW(wide.as_ptr(), &mut free_available, &mut total, std::ptr::null_mut()) };
20 (ok != 0 && total > 0).then_some((free_available, total))
21}
22
23#[cfg(unix)]
24pub fn volume_free_total_bytes(path: &Path) -> Option<(u64, u64)> {
25 use std::os::unix::ffi::OsStrExt;
26 let c = std::ffi::CString::new(path.as_os_str().as_bytes()).ok()?;
27 let mut st: libc::statvfs = unsafe { std::mem::zeroed() };
28 if unsafe { libc::statvfs(c.as_ptr(), &mut st) } != 0 {
29 return None;
30 }
31 let frsize = st.f_frsize as u64;
32 let total = (st.f_blocks as u64).saturating_mul(frsize);
33 let free = (st.f_bavail as u64).saturating_mul(frsize);
35 (total > 0).then_some((free, total))
36}
37
38#[cfg(test)]
39mod tests {
40 use super::*;
41
42 #[test]
43 fn reads_the_volume_of_an_existing_directory() {
44 let dir = std::env::temp_dir();
45 let (free, total) = volume_free_total_bytes(&dir).expect("temp dir's volume");
46 assert!(total > 0 && free <= total, "free {free} total {total}");
47 }
48
49 #[test]
50 fn a_missing_path_has_no_volume() {
51 assert_eq!(volume_free_total_bytes(Path::new("/no/such/agentmux/path/xyz")), None);
52 }
53}