fontpm_api/
util.rs

1use std::fs::create_dir_all;
2use std::path::PathBuf;
3// Thank you https://stackoverflow.com/a/27582993
4// (some modifications to please the type checker)
5#[macro_export]
6macro_rules! collection {
7    // map-like
8    ($($k:expr => $v:expr),* $(,)?) => {{
9        core::convert::From::from([$(($k.into(), $v.into()),)*])
10    }};
11    // set-like
12    ($($v:expr),* $(,)?) => {{
13        core::convert::From::from([$($v.into(),)*])
14    }};
15}
16
17pub fn create_parent(path: &PathBuf) -> std::io::Result<()> {
18    let parent = path.parent();
19
20    if let Some(parent) = parent {
21        if !parent.exists() {
22            return create_dir_all(parent)
23        }
24    }
25
26    Ok(())
27}
28
29pub fn plural_s(n: usize) -> &'static str {
30    return if n == 1 { "" } else { "s" }
31}
32pub fn plural_s_opposite(n: usize) -> &'static str {
33    return if n == 1 { "s" } else { "" }
34}
35
36pub fn nice_list<'a, I, S>(iter: I, last_join: S) -> String where I: IntoIterator, I::Item: ToString, S: ToString {
37    let collected: Vec<String> = iter.into_iter()
38        .map(|v| v.to_string())
39        .collect();
40
41    match collected.len() {
42        0 => "".into(),
43        1 => collected.first().unwrap().clone(),
44        2 => {
45            let first = collected.first().unwrap();
46            let last = collected.last().unwrap();
47            format!("{} {} {}", first, last_join.to_string(), last)
48        },
49        length => {
50            let mut str = String::new();
51            for (i, item) in collected.iter().rev().enumerate() {
52                let prefix = if i == length - 1 {
53                    "".into()
54                } else {
55                    if i == 0 {
56                        format!(", {} ", last_join.to_string())
57                    } else {
58                        ", ".into()
59                    }
60                };
61                str.push_str(prefix.as_str());
62                str.push_str(item.as_str());
63            }
64            str
65        }
66    }
67}