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
use std::str::Chars;
pub use microtemplate_derive::Substitutions;
pub trait Context {
fn get_field(&self, field_name: &str) -> &str;
}
#[inline(always)]
fn resolve_substitution<'a, C: Context>(iter: &mut Chars, context: &'a C) -> &'a str {
let mut field_name = String::with_capacity(4);
while let Some(c) = iter.next() {
match c {
'}' => return context.get_field(&field_name),
_ => field_name.push(c),
}
}
""
}
pub fn render<C: Context>(input: &str, context: C) -> String {
let first = input.find('{');
if let Some(first) = first {
let mut output = String::from(&input[0..first]);
output.reserve(input.len() - first);
let mut iter = input[first..].chars();
while let Some(c) = iter.next() {
match c {
'{' => output.push_str(resolve_substitution(&mut iter, &context)),
_ => output.push(c),
}
}
output
} else {
input.to_string()
}
}