aboutsummaryrefslogtreecommitdiff
path: root/base/src/locale.rs
blob: 188ab63253fae296acb03cb5c4a8ad7f02ba86bb (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
use std::{borrow::Cow, collections::HashMap, sync::LazyLock};

#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum Language {
    English,
    German,
}

static LANG_TABLES: LazyLock<HashMap<Language, HashMap<&'static str, &'static str>>> =
    LazyLock::new(|| {
        let mut k = HashMap::new();
        for (lang, source) in [
            (Language::English, include_str!("../../locale/en.ini")),
            (Language::German, include_str!("../../locale/de.ini")),
        ] {
            let tr_map = source
                .lines()
                .filter_map(|line| {
                    let (key, value) = line.split_once("=")?;
                    Some((key.trim(), value.trim()))
                })
                .collect::<HashMap<&'static str, &'static str>>();
            k.insert(lang, tr_map);
        }
        k
    });

pub fn tr(lang: Language, key: &str, args: &[(&str, &str)]) -> Cow<'static, str> {
    let tr_map = LANG_TABLES.get(&lang).unwrap();
    match tr_map.get(key) {
        Some(value) => {
            if args.is_empty() {
                Cow::Borrowed(value)
            } else {
                let mut s = value.to_string();
                for (k, v) in args {
                    s = s.replace(&format!("{{{k}}}"), v)
                }
                Cow::Owned(s)
            }
        }
        None => Cow::Owned(format!("TR[{key}]")),
    }
}