Skip to content

Commit 1ed5b69

Browse files
committed
chore(utils): add utility function to fetch disk free space for unix
1 parent 0e0b597 commit 1ed5b69

1 file changed

Lines changed: 24 additions & 0 deletions

File tree

src/utils/mod.rs

Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -516,6 +516,30 @@ pub(crate) fn home_dir_from_passwd() -> Option<PathBuf> {
516516
}
517517
}
518518

519+
#[cfg(unix)]
520+
pub(crate) fn disk_free(path: impl AsRef<OsStr>) -> Result<u64> {
521+
use libc::statvfs;
522+
use std::mem::MaybeUninit;
523+
use std::os::unix::ffi::OsStrExt;
524+
525+
let mut os_path = path.as_ref().as_bytes().to_vec();
526+
os_path.push(0);
527+
528+
let mut stat = MaybeUninit::<statvfs>::uninit();
529+
match unsafe { statvfs(os_path.as_ptr() as *const _, stat.as_mut_ptr()) } {
530+
// bit width of f_bavail and f_bsize may differ on platforms and sometimes u32
531+
#[allow(clippy::useless_conversion)]
532+
0 => {
533+
let stat = unsafe { stat.assume_init() };
534+
let available_blocks: u64 = stat.f_bavail.into();
535+
let block_size: u64 = stat.f_bsize.into();
536+
537+
Ok(available_blocks.saturating_mul(block_size))
538+
}
539+
_ => anyhow::bail!("failed to acquire block size"),
540+
}
541+
}
542+
519543
#[cfg(test)]
520544
mod tests {
521545
use super::*;

0 commit comments

Comments
 (0)