summaryrefslogtreecommitdiffstats
path: root/src/util/format.rs
blob: 3a9bc541fed7c317841fa838bd0c6f4a207c5af3 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
use std::time;

pub fn file_size_to_string(file_size: u64) -> String {
    const FILE_UNITS: [&str; 6] = ["B", "K", "M", "G", "T", "P"];
    const CONV_RATE: f64 = 1024.0;
    let mut file_size: f64 = file_size as f64;

    let mut index = 0;
    while file_size > CONV_RATE {
        file_size /= CONV_RATE;
        index += 1;
    }

    if file_size >= 100.0 {
        format!("{:>4.0} {}", file_size, FILE_UNITS[index])
    } else if file_size >= 10.0 {
        format!("{:>4.1} {}", file_size, FILE_UNITS[index])
    } else {
        format!("{:>4.2} {}", file_size, FILE_UNITS[index])
    }
}

pub fn mtime_to_string(mtime: time::SystemTime) -> String {
    const MTIME_FORMATTING: &str = "%Y-%m-%d %H:%M";

    let datetime: chrono::DateTime<chrono::offset::Local> = mtime.into();
    datetime.format(MTIME_FORMATTING).to_string()
}

pub fn format_tab_bar_title_string(
    max_len: usize,
    number: Option<usize>,
    title: impl Into<String>,
) -> String {
    let title: String = title.into();

    if let Some(number) = number {
        if title.len() > max_len {
            format!(
                "{}: {}…",
                number + 1,
                title.chars().take(max_len - 1).collect::<String>()
            )
        } else {
            format!("{}: {}", number + 1, title)
        }
    } else if title.len() > max_len {
        format!("{}…", title.chars().take(max_len - 1).collect::<String>())
    } else {
        title.to_string()
    }
}