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
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
/*!
A minimal templating engine that renders a string from the template, replacing all instances of `{placeholder}` with given values.

The engine is strict:

* all placeholders must have values provided,
* all provided values must have matching placeholder,
* a single placeholder can be used multiple times and will be expanded in all places.

Values are provided as an iterable object that provides placeholder name and value pairs.

Placeholder name may only contain letters (`a` to `z`, `A` to `Z`), numbers, dash, underscore and a dot to limit the risk of accidental placeholders in templates.

Hash maps are not used; all data is kept in vectors making it `O(N + N * M)` where `N` is number of placeholders and `M` is number of values. This should still be very fast for templates with small number of placeholders as no data is copied (works with slices).

```rust
use nanotemplate::template;

assert_eq!(
    template("Hello, my name is {name}!", &[("name", "nanotemplate")]).unwrap(),
    "Hello, my name is nanotemplate!".to_owned());
```

Also comes with simple CLI utility:

```sh
echo "Hello, my name is {name}!" | nanotemplate name=nanotemplate
```

*/

use std::error::Error;
use std::fmt::{self, Display};

#[derive(Debug)]
pub enum TemplateError {
    MissingValueForPlaceholder(String),
    NoPlaceholder(String),
}

impl Display for TemplateError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            TemplateError::MissingValueForPlaceholder(placeh) => write!(f, "template is missing value for placeholder {:?}", placeh),
            TemplateError::NoPlaceholder(placeh) => write!(f, "template has no placeholder {:?}", placeh),
        }
    }
}

impl Error for TemplateError {}

/// Provides a way to get placeholder name and value for template expansion.
pub trait PlaceholderValuePair<'k, 'v> {
    fn get_placeholder(&self) -> &'k str;
    fn get_value(&self) -> &'v str;
}

impl<'k, 'v> PlaceholderValuePair<'k, 'v> for (&'k str, &'v str) {
    fn get_placeholder(&self) -> &'k str {
        self.0
    }

    fn get_value(&self) -> &'v str {
        self.1
    }
}

impl<'k, 'v> PlaceholderValuePair<'k, 'v> for &(&'k str, &'v str) {
    fn get_placeholder(&self) -> &'k str {
        self.0
    }

    fn get_value(&self) -> &'v str {
        self.1
    }
}

impl<'t> PlaceholderValuePair<'t, 't> for [&'t str; 2] {
    fn get_placeholder(&self) -> &'t str {
        self[0]
    }

    fn get_value(&self) -> &'t str {
        self[1]
    }
}

impl<'t> PlaceholderValuePair<'t, 't> for &[&'t str; 2] {
    fn get_placeholder(&self) -> &'t str {
        self[0]
    }

    fn get_value(&self) -> &'t str {
        self[1]
    }
}

/// Renders a string from the tempalte, replacing all instances of {placeholder} with given values.
///
/// Placeholder name may only contain letters, numbers, dash, underscore and a dot.
pub fn template<'k, 'v, T: PlaceholderValuePair<'k, 'v>, I: IntoIterator<Item = T>>(template: &str, values: I) -> Result<String, TemplateError> {
    let mut vars = Vec::new();
    let mut slices = Vec::new();

    let mut from = 0;
    let mut candidate = None;

    for (i, c) in template.char_indices() {
        match c {
            '{' => candidate = Some(i),
            '}' => if let Some(placeh) = candidate.take() {
                slices.push(&template[from .. placeh]);
                vars.push((&template[placeh + 1 .. i], None));
                from = i + 1;
            }
            c => match c {
                'a'..='z' | 'A'..='Z' | '0'..='9' | '-' | '_' | '.' => (),
                _ => candidate = None,
            }
        }
    }

    slices.push(&template[from .. template.len()]);

    for t in values {
        let (tplaceh, tvalue) = (t.get_placeholder(), t.get_value());
        let mut found = false;

        for &mut (placeh, ref mut value) in vars.iter_mut() {
            if placeh == tplaceh {
                *value = Some(tvalue);
                found = true;
            }
        }

        if !found {
            return Err(TemplateError::NoPlaceholder(tplaceh.to_owned()))
        }
    }

    let mut out = String::new();
    let len = slices.len();

    for (i, s) in slices.into_iter().enumerate() {
        out.push_str(s);

        if i < len - 1 {
            let slot = &vars[i];
            let value = slot.1
                .as_ref()
                .ok_or_else(|| TemplateError::MissingValueForPlaceholder(slot.0.to_owned()))?;
            out.push_str(value);
        }
    }

    Ok(out)
}

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

    #[test]
    fn test_template_empty() {
        assert_eq!(&template::<&(&str, &str), _>("", None).unwrap(), "");
    }

    #[test]
    fn test_template_none() {
        assert_eq!(&template::<&(&str, &str), _>("hello world", None).unwrap(), "hello world");
    }

    #[test]
    fn test_template_single() {
        assert_eq!(&template("hello {foo} world", Some(("foo", "bar"))).unwrap(), "hello bar world");
    }

    #[test]
    fn test_template_single_variable_multi() {
        assert_eq!(&template("{foo} hello {foo} world {foo}", Some(("foo", "bar"))).unwrap(), "bar hello bar world bar");
    }

    #[test]
    fn test_template_many_vars_slice() {
        assert_eq!(&template("{foo} hello {bar} world {baz}", &[("foo", "1"), ("bar", "2"), ("baz" ,"3")]).unwrap(), "1 hello 2 world 3");
    }

    #[test]
    fn test_template_many_vars_slice_array() {
        assert_eq!(&template("{foo} hello {bar} world {baz}", &[["foo", "1"], ["bar", "2"], ["baz" ,"3"]]).unwrap(), "1 hello 2 world 3");
    }

    #[test]
    fn test_template_many_vars() {
        assert_eq!(&template("{foo} hello {bar} world {baz}", vec![("foo", "1"), ("bar", "2"), ("baz" ,"3")]).unwrap(), "1 hello 2 world 3");
    }

    #[test]
    fn test_template_nested_reverse() {
        assert_eq!(&template("}}}{foo}{{ hello }}}{bar}{{{ world }}{baz}{{{", vec![("foo", "1"), ("bar", "2"), ("baz" ,"3")]).unwrap(), "}}}1{{ hello }}}2{{{ world }}3{{{");
    }

    #[test]
    fn test_template_nested() {
        assert_eq!(&template("{{{{foo}}} hello {{{{bar}}}} world {{{baz}}}}", vec![("foo", "1"), ("bar", "2"), ("baz" ,"3")]).unwrap(), "{{{1}} hello {{{2}}} world {{3}}}");
    }

    #[test]
    fn test_template_json() {
        let tpl = r#"{"menu": {
  "id": "file",
  "value": {File},
  "{Popup}": {
    "menuitem": [
      {"value": "{New}", "onclick": "CreateNewDoc()"},
      {"value": "{Open}", "onclick": "OpenDoc()"},
      {"value": "{Close}", "onclick": "CloseDoc()"}
    ]
  }
}}"#;

        let out = r#"{"menu": {
  "id": "file",
  "value": "File",
  "popup": {
    "menuitem": [
      {"value": "New", "onclick": "CreateNewDoc()"},
      {"value": "Open", "onclick": "OpenDoc()"},
      {"value": "Close", "onclick": "CloseDoc()"}
    ]
  }
}}"#;

        assert_eq!(&template(tpl, vec![("File", "\"File\""), ("Popup", "popup"), ("New", "New"), ("Open" ,"Open"), ("Close", "Close")]).unwrap(), out);
    }

    #[test]
    fn test_template_many_vars_space() {
        assert_eq!(&template("{foo} hello {foo bar} world {baz}", vec![("foo", "1"), ("baz" ,"3")]).unwrap(), "1 hello {foo bar} world 3");
        assert_eq!(&template("{foo.bar} hello {foo+bar} world {foo_baz}", vec![("foo.bar", "1"), ("foo_baz" ,"3")]).unwrap(), "1 hello {foo+bar} world 3");
    }

    #[test]
    #[should_panic(expected = "template is missing value for placeholder \\\"foo\\\"")]
    fn test_template_missing_placeholder() {
        template::<&(&str, &str), _>("{foo} hello {foo} world {foo}", &[]).map_err(|e| e.to_string()).unwrap();
    }

    #[test]
    #[should_panic(expected = "template has no placeholder \\\"bar\\\"")]
    fn test_template_no_placeholder() {
        template("{foo} hello {foo} world {foo}", vec![("foo", "1"), ("bar", "2")]).map_err(|e| e.to_string()).unwrap();
    }
}