use std::path::Path;
pub fn available_bytes(path: &Path) -> Option<u64> {
fs2::available_space(path).ok()
}
pub fn is_low(path: &Path, threshold_mb: u64) -> bool {
if threshold_mb == 0 {
return false;
}
match available_bytes(path) {
Some(avail) => avail < threshold_mb.saturating_mul(1024 * 1024),
None => false,
}
}
pub fn human(bytes: u64) -> String {
const MB: u64 = 1024 * 1024;
const GB: u64 = 1024 * MB;
if bytes >= GB {
format!("{:.1} GB", bytes as f64 / GB as f64)
} else {
format!("{} MB", bytes / MB)
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn available_bytes_for_temp_dir_is_some() {
let n = available_bytes(&std::env::temp_dir());
assert!(n.is_some());
assert!(n.unwrap() > 0);
}
#[test]
fn zero_threshold_disables_check() {
assert!(!is_low(&std::env::temp_dir(), 0));
}
#[test]
fn unknown_path_is_not_low() {
let missing = Path::new("/this/path/should/not/exist/inkhaven");
assert!(!is_low(missing, 100));
}
#[test]
fn human_formats_mb_and_gb() {
assert_eq!(human(50 * 1024 * 1024), "50 MB");
assert_eq!(human(2 * 1024 * 1024 * 1024), "2.0 GB");
}
}