use nix::sys::statvfs::statvfs;
pub fn disk_usage_percent(mount_path: &str) -> f64 {
match statvfs(mount_path) {
Ok(stat) => {
let fsize = stat.fragment_size() as u64;
let total = stat.blocks() * fsize;
let avail = stat.blocks_available() * fsize;
if total == 0 {
return 0.0;
}
let used = total.saturating_sub(avail);
(used as f64 / total as f64) * 100.0
}
Err(e) => {
eprintln!("ERROR: statvfs('{}') failed: {}", mount_path, e);
0.0
}
}
}
pub fn disk_bytes(mount_path: &str) -> (u64, u64) {
match statvfs(mount_path) {
Ok(stat) => {
let fsize = stat.fragment_size() as u64;
let total = stat.blocks() * fsize;
let avail = stat.blocks_available() * fsize;
let used = total.saturating_sub(avail);
(used, total)
}
Err(_) => (0, 0),
}
}
pub fn human_bytes(bytes: u64) -> String {
const GIB: u64 = 1 << 30;
const MIB: u64 = 1 << 20;
const KIB: u64 = 1 << 10;
if bytes >= GIB {
format!("{:.1} GiB", bytes as f64 / GIB as f64)
} else if bytes >= MIB {
format!("{:.1} MiB", bytes as f64 / MIB as f64)
} else if bytes >= KIB {
format!("{:.1} KiB", bytes as f64 / KIB as f64)
} else {
format!("{} B", bytes)
}
}