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
use std::io::Write;
use std::{collections::BTreeMap, iter};
use serde::ser::Serialize;
use serde_json::value::{to_value, Map, Value};
use crate::errors::{Error, Result as TeraResult};
use crate::FunctionRelaxed;
use std::sync::Arc;
#[derive(Clone)]
pub struct Context {
data: BTreeMap<String, Value>,
functions: BTreeMap<String, Arc<dyn FunctionRelaxed>>,
}
impl std::fmt::Debug for Context {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("Context")
.field("data", &self.data)
.field("functions", &self.functions.keys())
.finish()
}
}
impl PartialEq for Context {
fn eq(&self, other: &Self) -> bool {
self.data.eq(&other.data)
}
}
impl Context {
pub fn new() -> Self {
Context { data: BTreeMap::new(), functions: Default::default() }
}
pub fn insert<T: Serialize + ?Sized, S: Into<String>>(&mut self, key: S, val: &T) {
self.data.insert(key.into(), to_value(val).unwrap());
}
pub fn try_insert<T: Serialize + ?Sized, S: Into<String>>(
&mut self,
key: S,
val: &T,
) -> TeraResult<()> {
self.data.insert(key.into(), to_value(val)?);
Ok(())
}
pub fn register_function<T: FunctionRelaxed + 'static, S: Into<String>>(
&mut self,
key: S,
val: T,
) {
self.functions.insert(key.into(), Arc::new(val));
}
pub fn extend(&mut self, mut source: Context) {
self.data.append(&mut source.data);
}
pub fn into_json(self) -> Value {
let mut m = Map::new();
for (key, value) in self.data {
m.insert(key, value);
}
Value::Object(m)
}
pub fn from_value(obj: Value) -> TeraResult<Self> {
match obj {
Value::Object(m) => {
let mut data = BTreeMap::new();
for (key, value) in m {
data.insert(key, value);
}
Ok(Context { data, functions: Default::default() })
}
_ => Err(Error::msg(
"Creating a Context from a Value/Serialize requires it being a JSON object",
)),
}
}
pub fn from_serialize(value: impl Serialize) -> TeraResult<Self> {
let obj = to_value(value).map_err(Error::json)?;
Context::from_value(obj)
}
pub fn get(&self, index: &str) -> Option<&Value> {
self.data.get(index)
}
pub fn remove(&mut self, index: &str) -> Option<Value> {
self.data.remove(index)
}
pub fn contains_key(&self, index: &str) -> bool {
self.data.contains_key(index)
}
#[inline]
pub fn get_function(&self, fn_name: &str) -> Option<&Arc<dyn FunctionRelaxed>> {
self.functions.get(fn_name)
}
}
impl Default for Context {
fn default() -> Context {
Context::new()
}
}
pub trait ValueRender {
fn render(&self, write: &mut impl Write) -> std::io::Result<()>;
}
impl ValueRender for Value {
fn render(&self, write: &mut impl Write) -> std::io::Result<()> {
match *self {
Value::String(ref s) => write!(write, "{}", s),
Value::Number(ref i) => write!(write, "{}", i),
Value::Bool(i) => write!(write, "{}", i),
Value::Null => Ok(()),
Value::Array(ref a) => {
let mut first = true;
write!(write, "[")?;
for i in a.iter() {
if !first {
write!(write, ", ")?;
}
first = false;
i.render(write)?;
}
write!(write, "]")?;
Ok(())
}
Value::Object(_) => write!(write, "[object]"),
}
}
}
pub trait ValueNumber {
fn to_number(&self) -> Result<f64, ()>;
}
impl ValueNumber for Value {
fn to_number(&self) -> Result<f64, ()> {
match *self {
Value::Number(ref i) => Ok(i.as_f64().unwrap()),
_ => Err(()),
}
}
}
pub trait ValueTruthy {
fn is_truthy(&self) -> bool;
}
impl ValueTruthy for Value {
fn is_truthy(&self) -> bool {
match *self {
Value::Number(ref i) => {
if i.is_i64() {
return i.as_i64().unwrap() != 0;
}
if i.is_u64() {
return i.as_u64().unwrap() != 0;
}
let f = i.as_f64().unwrap();
f != 0.0 && !f.is_nan()
}
Value::Bool(ref i) => *i,
Value::Null => false,
Value::String(ref i) => !i.is_empty(),
Value::Array(ref i) => !i.is_empty(),
Value::Object(ref i) => !i.is_empty(),
}
}
}
#[inline]
pub fn get_json_pointer(key: &str) -> String {
lazy_static::lazy_static! {
static ref JSON_POINTER_REGEX: regex::Regex = regex::Regex::new(r#""[^"]*"|[^.]+"#).unwrap();
}
if key.find('"').is_some() {
let segments: Vec<&str> = iter::once("")
.chain(JSON_POINTER_REGEX.find_iter(key).map(|mat| mat.as_str().trim_matches('"')))
.collect();
segments.join("/")
} else {
["/", &key.replace(".", "/")].join("")
}
}
#[cfg(test)]
mod tests {
use super::*;
use serde_json::json;
use std::collections::HashMap;
#[test]
fn test_get_json_pointer() {
assert_eq!(get_json_pointer(""), "/");
assert_eq!(get_json_pointer("foo"), "/foo");
assert_eq!(get_json_pointer("foo.bar.baz"), "/foo/bar/baz");
assert_eq!(get_json_pointer(r#"foo["bar"].baz"#), r#"/foo["bar"]/baz"#);
assert_eq!(
get_json_pointer(r#"foo["bar"].baz["qux"].blub"#),
r#"/foo["bar"]/baz["qux"]/blub"#
);
}
#[test]
fn can_extend_context() {
let mut target = Context::new();
target.insert("a", &1);
target.insert("b", &2);
let mut source = Context::new();
source.insert("b", &3);
source.insert("c", &4);
target.extend(source);
assert_eq!(*target.data.get("a").unwrap(), to_value(1).unwrap());
assert_eq!(*target.data.get("b").unwrap(), to_value(3).unwrap());
assert_eq!(*target.data.get("c").unwrap(), to_value(4).unwrap());
}
#[test]
fn can_create_context_from_value() {
let obj = json!({
"name": "bob",
"age": 25
});
let context_from_value = Context::from_value(obj).unwrap();
let mut context = Context::new();
context.insert("name", "bob");
context.insert("age", &25);
assert_eq!(context_from_value, context);
}
#[test]
fn can_create_context_from_impl_serialize() {
let mut map = HashMap::new();
map.insert("name", "bob");
map.insert("last_name", "something");
let context_from_serialize = Context::from_serialize(&map).unwrap();
let mut context = Context::new();
context.insert("name", "bob");
context.insert("last_name", "something");
assert_eq!(context_from_serialize, context);
}
#[test]
fn can_remove_a_key() {
let mut context = Context::new();
context.insert("name", "foo");
context.insert("bio", "Hi, I'm foo.");
let mut expected = Context::new();
expected.insert("name", "foo");
assert_eq!(context.remove("bio"), Some(to_value("Hi, I'm foo.").unwrap()));
assert_eq!(context.get("bio"), None);
assert_eq!(context, expected);
}
#[test]
fn remove_return_none_with_unknown_index() {
let mut context = Context::new();
assert_eq!(context.remove("unknown"), None);
}
}