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::collections::BTreeMap;

/// A template. The syntax for specifying a variable to be replaced is "~{myname}".
///
/// ```ignore
/// let mut template = StringTemplate::new("hello ~{name2} my name is ~{name}");
/// template.set("name", "grok");
/// template.set("name2", "traveler");
/// assert!(template.format() == "hello traveler my name is grok");
/// ```
#[derive(Clone, PartialEq, Eq, PartialOrd, Ord)]
pub struct StringTemplate {
    template: String,
    vars: BTreeMap<String, String>
}

impl StringTemplate {
    /// Create a new template from a string.
    pub fn new(template: impl Into<String>) -> Self {
        Self {
            template: template.into(),
            vars: BTreeMap::new(),
        }
    }

    /// Set a variable.
    pub fn set(&mut self, key: impl AsRef<str>, replacement: impl Into<String>) {
        self.vars.insert(format!("~{{{}}}", key.as_ref()), replacement.into());
    }

    /// Format the template, producing a string.
    pub fn format(&self) -> String {
        let mut s = self.template.clone();
        self.vars.iter().for_each(|(k, v)| {
            s = s.replace(k, v);
        });
        s
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn fmt_test() {
        let mut template = StringTemplate::new("hello ~{name2} my name is ~{name}");
        template.set("name", "grok");
        template.set("name2", "traveler");
        assert!(template.format() == "hello traveler my name is grok");
    }
}