minijinja/value/
namespace_object.rs

1use std::collections::BTreeMap;
2use std::sync::{Arc, Mutex};
3
4use crate::value::{Enumerator, Object, Value};
5
6/// This object exists for the `namespace` function.
7///
8/// It's special in that it behaves like a dictionary in many ways but it's the only
9/// object that can be used with `{% set %}` assignments.  This is used internally
10/// in the vm via downcasting.
11#[derive(Debug, Default)]
12pub(crate) struct Namespace {
13    data: Mutex<BTreeMap<Arc<str>, Value>>,
14}
15
16impl Object for Namespace {
17    fn get_value(self: &Arc<Self>, key: &Value) -> Option<Value> {
18        self.data.lock().unwrap().get(some!(key.as_str())).cloned()
19    }
20
21    fn enumerate(self: &Arc<Self>) -> Enumerator {
22        let data = self.data.lock().unwrap();
23        let keys = data.keys().cloned().map(Value::from);
24        Enumerator::Values(keys.collect())
25    }
26}
27
28impl Namespace {
29    pub(crate) fn set_value(&self, key: &str, value: Value) {
30        self.data.lock().unwrap().insert(key.into(), value);
31    }
32}