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
53
54
55
use std::collections::BTreeMap;
use std::sync::{Arc, RwLock};

// This is a poor man's translation service. Should be replaced by
// something more sophisticated, possibly `fluent`, but that's not
// ready for primetime yet.

pub enum Arg<'a> {
    S(&'a str),
}

impl<'a> Arg<'a> {
    fn to_string(&self) -> String {
        match self {
            Arg::S(s) => s.to_string(),
        }
    }
}

#[derive(Clone)]
pub struct Tr {
    bundle: Arc<RwLock<BTreeMap<String, String>>>,
}

impl Tr {
    pub fn new() -> Tr {
        Tr {
            bundle: Arc::default(),
        }
    }

    pub fn switch(&mut self, bundle: BTreeMap<String, String>) {
        let mut guard = self.bundle.write().unwrap();
        *guard = bundle;
    }

    pub fn fmt(&self, s: &str) -> String {
        self.bundle
            .read()
            .unwrap()
            .get(&s.to_string())
            .map(|s| s.as_str())
            .unwrap_or(s)
            .to_string()
    }

    pub fn fmt_a(&self, s: &str, args: BTreeMap<String, Arg>) -> String {
        let mut result = self.fmt(s);
        for (k, v) in args.iter() {
            let needle = format!("{}{}{}", "{", k, "}");
            result = result.replace(&needle, &v.to_string());
        }
        result
    }
}