Skip to main content

devbook_tui/
format.rs

1pub fn format_date_short(iso: &str) -> String {
2    // Expected format: "2026-11-20T19:21:28Z" or "2026-11-20T19:21:28.123Z"
3    if iso.len() >= 16 {
4        // e.g. "11-20 19:21"
5        let month_day = &iso[5..10];
6        let hour_min = &iso[11..16];
7        format!("{} {}", month_day, hour_min)
8    } else if iso.len() >= 10 {
9        iso[..10].to_string()
10    } else {
11        iso.to_string()
12    }
13}
14
15pub fn format_bytes(bytes: u64) -> String {
16    const KB: u64 = 1024;
17    const MB: u64 = KB * 1024;
18    const GB: u64 = MB * 1024;
19
20    if bytes >= GB {
21        format!("{:.1} GB", bytes as f64 / GB as f64)
22    } else if bytes >= MB {
23        format!("{:.1} MB", bytes as f64 / MB as f64)
24    } else if bytes >= KB {
25        format!("{:.1} KB", bytes as f64 / KB as f64)
26    } else {
27        format!("{} B", bytes)
28    }
29}
30
31pub fn word_and_line_count(text: &str) -> (usize, usize, usize) {
32    let chars = text.chars().count();
33    let words = text.split_whitespace().count();
34    let lines = if text.is_empty() { 0 } else { text.lines().count() };
35    (chars, words, lines)
36}
37
38pub fn truncate_str(s: &str, max_width: usize) -> String {
39    if s.chars().count() <= max_width {
40        s.to_string()
41    } else {
42        let mut truncated: String = s.chars().take(max_width.saturating_sub(1)).collect();
43        truncated.push('…');
44        truncated
45    }
46}
47
48#[cfg(test)]
49mod tests {
50    use super::*;
51
52    #[test]
53    fn test_date_formatting() {
54        assert_eq!(format_date_short("2026-11-20T19:21:28Z"), "11-20 19:21");
55        assert_eq!(format_date_short("2026-11-20"), "2026-11-20");
56        assert_eq!(format_date_short("short"), "short");
57    }
58
59    #[test]
60    fn test_format_bytes() {
61        assert_eq!(format_bytes(500), "500 B");
62        assert_eq!(format_bytes(1024), "1.0 KB");
63        assert_eq!(format_bytes(1536), "1.5 KB");
64        assert_eq!(format_bytes(1024 * 1024), "1.0 MB");
65    }
66
67    #[test]
68    fn test_word_and_line_count() {
69        let text = "Hello world\nThis is a prompt\nWith three lines";
70        let (chars, words, lines) = word_and_line_count(text);
71        assert_eq!(lines, 3);
72        assert_eq!(words, 9);
73        assert_eq!(chars, text.chars().count());
74
75        let (c, w, l) = word_and_line_count("");
76        assert_eq!((c, w, l), (0, 0, 0));
77    }
78}