abstutil/
utils.rs

1use std::collections::BTreeSet;
2use std::fmt::Write;
3
4pub fn plain_list_names(names: BTreeSet<String>) -> String {
5    let mut s = String::new();
6    let len = names.len();
7    for (idx, n) in names.into_iter().enumerate() {
8        if idx != 0 {
9            if idx == len - 1 {
10                if len == 2 {
11                    write!(s, " and ").unwrap();
12                } else {
13                    write!(s, ", and ").unwrap();
14                }
15            } else {
16                write!(s, ", ").unwrap();
17            }
18        }
19        write!(s, "{}", n).unwrap();
20    }
21    s
22}
23
24pub fn prettyprint_usize(x: usize) -> String {
25    let num = format!("{}", x);
26    let mut result = String::new();
27    let mut i = num.len();
28    for c in num.chars() {
29        result.push(c);
30        i -= 1;
31        if i > 0 && i % 3 == 0 {
32            result.push(',');
33        }
34    }
35    result
36}
37
38pub fn prettyprint_bytes(bytes: u64) -> String {
39    if bytes < 1024 {
40        return format!("{} bytes", bytes);
41    }
42    let kb = (bytes as f64) / 1024.0;
43    if kb < 1024.0 {
44        return format!("{} KB", kb as usize);
45    }
46    let mb = kb / 1024.0;
47    format!("{} MB", mb as usize)
48}
49
50pub fn abbreviated_format(x: usize) -> String {
51    if x >= 1000 {
52        let ks = x as f32 / 1000.0;
53        format!("{:.1}k", ks)
54    } else {
55        x.to_string()
56    }
57}
58
59pub fn basename<I: AsRef<str>>(path: I) -> String {
60    std::path::Path::new(path.as_ref())
61        .file_stem()
62        .unwrap()
63        .to_os_string()
64        .into_string()
65        .unwrap()
66}
67
68pub fn parent_path(path: &str) -> String {
69    format!("{}", std::path::Path::new(path).parent().unwrap().display())
70}