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
use std::{borrow::Cow, fmt::Display, io::Write, ops};
use crate::{ParseError, RenderError, Values};
#[derive(Clone, Debug, Default, PartialEq, Eq)]
pub struct Template<'s> {
pub items: Cow<'s, [Item<'s>]>,
pub default: Option<Cow<'s, str>>,
}
#[derive(Clone, Debug, PartialEq, Eq)]
pub enum Item<'s> {
Text(&'s str),
Key(&'s str),
}
impl<'s> Template<'s> {
/// Construct a template with the given items and default.
///
/// You can write a template literal without any help by constructing it directly:
///
/// ```
/// use std::borrow::Cow;
/// use leon::{Item, Template};
/// const TEMPLATE: Template = Template {
/// items: Cow::Borrowed({
/// const ITEMS: &'static [Item<'static>] = &[
/// Item::Text("Hello"),
/// Item::Key("name"),
/// ];
/// ITEMS
/// }),
/// default: None,
/// };
/// assert_eq!(TEMPLATE.render(&[("name", "world")]).unwrap(), "Helloworld");
/// ```
///
/// As that's a bit verbose, using this function and the enum shorthands can be helpful:
///
/// ```
/// use leon::{Item, Item::*, Template};
/// const TEMPLATE: Template = Template::new({
/// const ITEMS: &'static [Item<'static>] = &[Text("Hello "), Key("name")];
/// ITEMS
/// }, Some("world"));
///
/// assert_eq!(TEMPLATE.render(&[("unrelated", "value")]).unwrap(), "Hello world");
/// ```
///
/// For an even more ergonomic syntax, see the [`leon::template!`](crate::template!) macro.
pub const fn new(items: &'s [Item<'s>], default: Option<&'s str>) -> Template<'s> {
Template {
items: Cow::Borrowed(items),
default: match default {
Some(default) => Some(Cow::Borrowed(default)),
None => None,
},
}
}
/// Parse a template from a string.
///
/// # Syntax
///
/// ```plain
/// it is better to rule { group }
/// one can live {adverb} without power
/// ```
///
/// A replacement is denoted by `{` and `}`. The contents of the braces, trimmed
/// of any whitespace, are the key. Any text outside of braces is left as-is.
///
/// To escape a brace, use `\{` or `\}`. To escape a backslash, use `\\`. Keys
/// cannot contain escapes.
///
/// ```plain
/// \{ leon \}
/// ```
///
/// The above examples, given the values `group = "no one"` and
/// `adverb = "honourably"`, would render to:
///
/// ```plain
/// it is better to rule no one
/// one can live honourably without power
/// { leon }
/// ```
///
/// # Example
///
/// ```
/// use leon::Template;
/// let template = Template::parse("hello {name}").unwrap();
/// ```
///
pub fn parse(s: &'s str) -> Result<Self, ParseError> {
Self::parse_items(s).map(|items| Template {
items: Cow::Owned(items),
default: None,
})
}
pub fn render_into(
&self,
writer: &mut dyn Write,
values: &dyn Values,
) -> Result<(), RenderError> {
for token in self.items.as_ref() {
match token {
Item::Text(text) => writer.write_all(text.as_bytes())?,
Item::Key(key) => {
if let Some(value) = values.get_value(key) {
writer.write_all(value.as_bytes())?;
} else if let Some(default) = &self.default {
writer.write_all(default.as_bytes())?;
} else {
return Err(RenderError::MissingKey(key.to_string()));
}
}
}
}
Ok(())
}
pub fn render(&self, values: &dyn Values) -> Result<String, RenderError> {
let mut buf = Vec::with_capacity(
self.items
.iter()
.map(|item| match item {
Item::Key(_) => 0,
Item::Text(t) => t.len(),
})
.sum(),
);
self.render_into(&mut buf, values)?;
// UNWRAP: We know that the buffer is valid UTF-8 because we only write strings.
Ok(String::from_utf8(buf).unwrap())
}
/// If the template contains key `key`.
pub fn has_key(&self, key: &str) -> bool {
self.has_any_of_keys(&[key])
}
/// If the template contains any one of the `keys`.
pub fn has_any_of_keys(&self, keys: &[&str]) -> bool {
self.items.iter().any(|token| match token {
Item::Key(k) => keys.contains(k),
_ => false,
})
}
/// Returns all keys in this template.
pub fn keys(&self) -> impl Iterator<Item = &&str> {
self.items.iter().filter_map(|token| match token {
Item::Key(k) => Some(k),
_ => None,
})
}
/// Sets the default value for this template.
pub fn set_default(&mut self, default: &dyn Display) {
self.default = Some(Cow::Owned(default.to_string()));
}
/// Cast `Template<'s>` to `Template<'t>` where `'s` is a subtype of `'t`,
/// meaning that `Template<'s>` outlives `Template<'t>`.
pub fn cast<'t>(self) -> Template<'t>
where
's: 't,
{
Template {
items: match self.items {
Cow::Owned(vec) => Cow::Owned(vec),
Cow::Borrowed(slice) => Cow::Borrowed(slice as &'t [Item<'t>]),
},
default: self.default.map(|default| default as Cow<'t, str>),
}
}
}
impl<'s, 'rhs: 's> ops::AddAssign<&Template<'rhs>> for Template<'s> {
fn add_assign(&mut self, rhs: &Template<'rhs>) {
self.items
.to_mut()
.extend(rhs.items.as_ref().iter().cloned());
if let Some(default) = &rhs.default {
self.default = Some(default.clone());
}
}
}
impl<'s, 'rhs: 's> ops::AddAssign<Template<'rhs>> for Template<'s> {
fn add_assign(&mut self, rhs: Template<'rhs>) {
match rhs.items {
Cow::Borrowed(items) => self.items.to_mut().extend(items.iter().cloned()),
Cow::Owned(items) => self.items.to_mut().extend(items),
}
if let Some(default) = rhs.default {
self.default = Some(default);
}
}
}
impl<'s, 'item: 's> ops::AddAssign<Item<'item>> for Template<'s> {
fn add_assign(&mut self, item: Item<'item>) {
self.items.to_mut().push(item);
}
}
impl<'s, 'item: 's> ops::AddAssign<&Item<'item>> for Template<'s> {
fn add_assign(&mut self, item: &Item<'item>) {
self.add_assign(item.clone())
}
}
impl<'s, 'rhs: 's> ops::Add<Template<'rhs>> for Template<'s> {
type Output = Self;
fn add(mut self, rhs: Template<'rhs>) -> Self::Output {
self += rhs;
self
}
}
impl<'s, 'rhs: 's> ops::Add<&Template<'rhs>> for Template<'s> {
type Output = Self;
fn add(mut self, rhs: &Template<'rhs>) -> Self::Output {
self += rhs;
self
}
}
impl<'s, 'item: 's> ops::Add<Item<'item>> for Template<'s> {
type Output = Self;
fn add(mut self, item: Item<'item>) -> Self::Output {
self += item;
self
}
}
impl<'s, 'item: 's> ops::Add<&Item<'item>> for Template<'s> {
type Output = Self;
fn add(mut self, item: &Item<'item>) -> Self::Output {
self += item;
self
}
}
#[cfg(test)]
mod test {
use crate::Template;
#[test]
fn concat_templates() {
let t1 = crate::template!("Hello", { "name" });
let t2 = crate::template!("have a", { "adjective" }, "day");
assert_eq!(
t1 + t2,
crate::template!("Hello", { "name" }, "have a", { "adjective" }, "day"),
);
}
#[test]
fn test_cast() {
fn inner<'a>(_: &'a u32, _: Template<'a>) {}
let template: Template<'static> = crate::template!("hello");
let i = 1;
inner(&i, template.cast());
}
}