use std::time::SystemTime;
use chrono::{DateTime, Local};
pub fn format_size(bytes: u64) -> String {
const UNITS: [&str; 5] = ["B", "KB", "MB", "GB", "TB"];
if bytes < 1024 {
return format!("{bytes} B");
}
let mut size = bytes as f64;
let mut unit = 0;
while size >= 1024.0 && unit < UNITS.len() - 1 {
size /= 1024.0;
unit += 1;
}
format!("{:.1} {}", size, UNITS[unit])
}
pub fn format_modified(modified: Option<SystemTime>) -> String {
match modified {
Some(t) => {
let dt: DateTime<Local> = t.into();
dt.format("%Y-%m-%d %H:%M").to_string()
}
None => "-".to_string(),
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn format_size_bytes_below_kb() {
assert_eq!(format_size(0), "0 B");
assert_eq!(format_size(512), "512 B");
assert_eq!(format_size(1023), "1023 B");
}
#[test]
fn format_size_kilobytes() {
assert_eq!(format_size(1024), "1.0 KB");
assert_eq!(format_size(1536), "1.5 KB");
}
#[test]
fn format_size_megabytes_and_up() {
assert_eq!(format_size(1024 * 1024), "1.0 MB");
assert_eq!(format_size(3 * 1024 * 1024 + 1024 * 200), "3.2 MB");
assert_eq!(format_size(2 * 1024 * 1024 * 1024), "2.0 GB");
}
#[test]
fn format_modified_none_is_dash() {
assert_eq!(format_modified(None), "-");
}
#[test]
fn format_modified_some_produces_expected_shape() {
let result = format_modified(Some(SystemTime::UNIX_EPOCH));
assert_eq!(result.len(), 16);
assert_eq!(result.chars().nth(4), Some('-'));
assert_eq!(result.chars().nth(7), Some('-'));
assert_eq!(result.chars().nth(10), Some(' '));
assert_eq!(result.chars().nth(13), Some(':'));
}
}