//! Plain string formatting helpers shared across Rustik crates. use std::time::SystemTime; /// Formats byte counts using compact binary units. pub fn human_size(bytes: u64) -> String { const UNITS: [&str; 5] = ["B", "KB", "MB", "GB", "TB"]; let mut value = bytes as f64; let mut unit = 0; while value >= 1024.0 && unit + 1 < UNITS.len() { value /= 1024.0; unit += 1; } if unit == 0 { format!("{bytes} {}", UNITS[unit]) } else { format!("{value:.1} {}", UNITS[unit]) } } /// Returns a relative time label from `now` to `time`. pub fn relative_time(now: SystemTime, time: SystemTime) -> String { let Ok(age) = now.duration_since(time) else { return String::from("in the future"); }; let seconds = age.as_secs(); if seconds < 60 { String::from("just now") } else if seconds < 60 * 60 { format!("{}m ago", seconds / 60) } else if seconds < 60 * 60 * 24 { format!("{}h ago", seconds / 60 / 60) } else { format!("{}d ago", seconds / 60 / 60 / 24) } } #[cfg(test)] mod tests { use super::*; use std::time::Duration; #[test] fn human_size_formats_compact_binary_units() { assert_eq!(human_size(0), "0 B"); assert_eq!(human_size(999), "999 B"); assert_eq!(human_size(1024), "1.0 KB"); assert_eq!(human_size(1536), "1.5 KB"); assert_eq!(human_size(1024 * 1024), "1.0 MB"); assert_eq!(human_size(1024 * 1024 * 1024), "1.0 GB"); } #[test] fn relative_time_formats_past_ranges() { let now = SystemTime::UNIX_EPOCH + Duration::from_secs(60 * 60 * 24 * 2); assert_eq!(relative_time(now, now), "just now"); assert_eq!( relative_time(now, now - Duration::from_secs(5 * 60)), "5m ago" ); assert_eq!( relative_time(now, now - Duration::from_secs(3 * 60 * 60)), "3h ago" ); assert_eq!( relative_time(now, now - Duration::from_secs(2 * 60 * 60 * 24)), "2d ago" ); } #[test] fn relative_time_formats_future_times() { let now = SystemTime::UNIX_EPOCH; assert_eq!( relative_time(now, now + Duration::from_secs(1)), "in the future" ); } }