1use std::time::SystemTime;
2
3use chrono::{DateTime, Local};
4
5pub fn format_size(bytes: u64) -> String {
7 const UNITS: [&str; 5] = ["B", "KB", "MB", "GB", "TB"];
8
9 if bytes < 1024 {
10 return format!("{bytes} B");
11 }
12
13 let mut size = bytes as f64;
14 let mut unit = 0;
15 while size >= 1024.0 && unit < UNITS.len() - 1 {
16 size /= 1024.0;
17 unit += 1;
18 }
19 format!("{:.1} {}", size, UNITS[unit])
20}
21
22pub fn format_modified(modified: Option<SystemTime>) -> String {
24 match modified {
25 Some(t) => {
26 let dt: DateTime<Local> = t.into();
27 dt.format("%Y-%m-%d %H:%M").to_string()
28 }
29 None => "-".to_string(),
30 }
31}
32
33#[cfg(test)]
34mod tests {
35 use super::*;
36
37 #[test]
38 fn format_size_bytes_below_kb() {
39 assert_eq!(format_size(0), "0 B");
40 assert_eq!(format_size(512), "512 B");
41 assert_eq!(format_size(1023), "1023 B");
42 }
43
44 #[test]
45 fn format_size_kilobytes() {
46 assert_eq!(format_size(1024), "1.0 KB");
47 assert_eq!(format_size(1536), "1.5 KB");
48 }
49
50 #[test]
51 fn format_size_megabytes_and_up() {
52 assert_eq!(format_size(1024 * 1024), "1.0 MB");
53 assert_eq!(format_size(3 * 1024 * 1024 + 1024 * 200), "3.2 MB");
54 assert_eq!(format_size(2 * 1024 * 1024 * 1024), "2.0 GB");
55 }
56
57 #[test]
58 fn format_modified_none_is_dash() {
59 assert_eq!(format_modified(None), "-");
60 }
61
62 #[test]
63 fn format_modified_some_produces_expected_shape() {
64 let result = format_modified(Some(SystemTime::UNIX_EPOCH));
65 assert_eq!(result.len(), 16);
67 assert_eq!(result.chars().nth(4), Some('-'));
68 assert_eq!(result.chars().nth(7), Some('-'));
69 assert_eq!(result.chars().nth(10), Some(' '));
70 assert_eq!(result.chars().nth(13), Some(':'));
71 }
72}