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
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
/*!
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 (use [template_default] to use default value for placeholders),
* all provided values must have matching placeholder (when using [template_strict]),
* 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, Write};

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

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),
            TemplateError::OutputError(_) => write!(f, "failed to write to output"),
        }
    }
}

impl Error for TemplateError {
    fn source(&self) -> Option<&(dyn Error + 'static)> {
        match self {
            TemplateError::MissingValueForPlaceholder(_) => None,
            TemplateError::NoPlaceholder(_) => None,
            TemplateError::OutputError(err) => Some(err),
        }
    }
}

impl From<fmt::Error> for TemplateError {
    fn from(err: fmt::Error) -> TemplateError {
        TemplateError::OutputError(err)
    }
}

/// Provides a way to get placeholder name and value for template expansion.
pub trait PlaceholderValuePair<'v, V: ?Sized> {
    /// The name of the placeholder to match in the template.
    fn placeholder(&self) -> &str;
    /// Reference to the value to replace the template placeholders with.
    fn value_ref(&self) -> &'v V;
}

impl<'k, 'v, V: ?Sized, P: PlaceholderValuePair<'v, V>> PlaceholderValuePair<'v, V> for &P {
    fn placeholder(&self) -> &str {
        (*self).placeholder()
    }

    fn value_ref(&self) -> &'v V {
        (*self).value_ref()
    }
}

impl<'v, K: AsRef<str>, V: ?Sized> PlaceholderValuePair<'v, V> for (K, &'v V) {
    fn placeholder(&self) -> &str {
        self.0.as_ref()
    }

    fn value_ref(&self) -> &'v V {
        self.1
    }
}

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

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

fn alloc_out_string(template: &str) -> String {
    String::with_capacity(template.len())
}

/// Renders a string from the template, replacing all instances of `{placeholder}` with given values.
///
/// Placeholder name may only contain letters, numbers, dash, underscore and a dot.
pub fn template<'v, T: PlaceholderValuePair<'v, impl Display + ?Sized + 'v>>(
    template: &str, values: impl IntoIterator<Item = T>
) -> Result<String, TemplateError> {
    let mut out = alloc_out_string(template);
    template_base(&mut out, template, values, false, None)?;
    Ok(out)
}

/// Variant of [template()] that write outputs to `out`.
pub fn write_template<'v, T: PlaceholderValuePair<'v, impl Display + ?Sized + 'v>>(
    mut out: impl Write, template: &str, values: impl IntoIterator<Item = T>
) -> Result<(), TemplateError> {
    template_base(&mut out, template, values, false, None)
}

/// Renders a string from the template, replacing all instances of `{placeholder}` with given values.
///
/// Placeholder name may only contain letters, numbers, dash, underscore and a dot.
///
/// It is an error to pass values for non-existing placeholders.
pub fn template_strict<'v, T: PlaceholderValuePair<'v, impl Display + ?Sized + 'v>>(
    template: &str, values: impl IntoIterator<Item = T>
) -> Result<String, TemplateError> {
    let mut out = alloc_out_string(template);
    template_base(&mut out, template, values, true, None)?;
    Ok(out)
}

/// Variant of [template_strict()] that writes output to `out`.
pub fn write_template_strict<'v, T: PlaceholderValuePair<'v, impl Display + ?Sized + 'v>>(
    mut out: impl Write, template: &str, values: impl IntoIterator<Item = T>
) -> Result<(), TemplateError> {
    template_base(&mut out, template, values, true, None)
}

/// Renders a string from the template, replacing all instances of `{placeholder}` with given values.
///
/// Placeholder name may only contain letters, numbers, dash, underscore and a dot.
///
/// Default value is used for missing placeholder values.
pub fn template_default<'v, T: PlaceholderValuePair<'v, impl Display + ?Sized + 'v>>(
    template: &str, values: impl IntoIterator<Item = T>, default: &str
) -> Result<String, TemplateError> {
    let mut out = alloc_out_string(template);
    template_base(&mut out, template, values, false, Some(default))?;
    Ok(out)
}

/// Variant of [template_default()] that writes output to `out`.
pub fn write_template_default<'v, T: PlaceholderValuePair<'v, impl Display + ?Sized + 'v>>(
    mut out: impl Write, template: &str, values: impl IntoIterator<Item = T>, default: &str
) -> Result<(), TemplateError> {
    template_base(&mut out, template, values, false, Some(default))
}

fn template_base<'v, T: PlaceholderValuePair<'v, impl Display + 'v + ?Sized>>(
    mut out: impl Write,
    template: &str,
    values: impl IntoIterator<Item = T>,
    strict_values: bool,
    default: Option<&str>,
) -> Result<(), 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 = t.placeholder();
        let tvalue = t.value_ref();
        let mut found = false;

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

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

    let len = slices.len();

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

        if i < len - 1 {
            let slot = &vars[i];
            match &slot.1 {
                Some(ph) => { write!(out, "{}", ph).unwrap(); },
                None => if let Some(default) = default.as_ref() {
                    out.write_str(default)?
                } else {
                    return Err(TemplateError::MissingValueForPlaceholder(slot.0.to_owned()))
                }
            }
        }
    }
    
    Ok(())
}

#[cfg(test)]
mod tests {
    use std::collections::HashMap;

    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_int() {
        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_string_refs() {
        assert_eq!(&template("{foo} hello {bar} world {baz}", &[("foo", &"1".to_string()), ("bar", &"2".to_string()), ("baz" ,&"3".to_string())]).unwrap(), "1 hello 2 world 3");
    }

    #[test]
    fn test_template_many_placeholder_strings() {
        assert_eq!(&template("{foo} hello {bar} world {baz}", &[("foo".to_owned(), "1"), ("bar".to_owned(), "2"), ("baz".to_owned() ,"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_vec() {
        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_many_vars_hash_map() {
        let mut map = HashMap::new();
        map.insert("foo", "1");
        map.insert("bar", "2");
        map.insert("baz", "3");
        assert_eq!(&template("{foo} hello {bar} world {baz}", map).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]
    fn test_template_missing_placeholder_default() {
        assert_eq!(&template_default::<&(&str, &str)>("{foo} hello {foo} world {foo}", &[], "bar").unwrap(), "bar hello bar world bar");
    }

    #[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]
    fn test_template_no_placeholder() {
        assert_eq!(&template("{foo} hello {foo} world {foo}", vec![("foo", "1"), ("bar", "2")]).unwrap(), "1 hello 1 world 1");
    }

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