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
use core::any::Any;
use core::borrow::Borrow;

use crate::Error;

/// No runtime values provided.
pub const NO_VALUES: &dyn Values = &();

/// Try to find `key` in `values` and then to convert it to `T`.
pub fn get_value<T: Any>(values: &dyn Values, key: impl AsRef<str>) -> Result<&T, Error> {
    let Some(src) = values.get_value(key.as_ref()) else {
        return Err(Error::ValueMissing);
    };

    if let Some(value) = src.downcast_ref::<T>() {
        return Ok(value);
    } else if let Some(value) = src.downcast_ref::<&T>() {
        return Ok(value);
    }

    #[cfg(feature = "alloc")]
    if let Some(value) = src.downcast_ref::<alloc::boxed::Box<T>>() {
        return Ok(value);
    } else if let Some(value) = src.downcast_ref::<alloc::rc::Rc<T>>() {
        return Ok(value);
    } else if let Some(value) = src.downcast_ref::<alloc::sync::Arc<T>>() {
        return Ok(value);
    }

    Err(Error::ValueType)
}

/// A runtime value store for [`Template::render_with_values()`][crate::Template::render_with_values].
pub trait Values {
    /// Try to find `key` in this store.
    fn get_value<'a>(&'a self, key: &str) -> Option<&'a dyn Any>;
}

crate::impl_for_ref! {
    impl Values for T {
        #[inline]
        fn get_value<'a>(&'a self, key: &str) -> Option<&'a dyn Any> {
            T::get_value(self, key)
        }
    }
}

impl Values for () {
    #[inline]
    fn get_value<'a>(&'a self, _: &str) -> Option<&'a dyn Any> {
        None
    }
}

impl<T: Values> Values for Option<T> {
    #[inline]
    fn get_value<'a>(&'a self, key: &str) -> Option<&'a dyn Any> {
        self.as_ref()?.get_value(key)
    }
}

impl<K, V, const N: usize> Values for [(K, V); N]
where
    K: Borrow<str>,
    V: Value,
{
    #[inline]
    fn get_value<'a>(&'a self, key: &str) -> Option<&'a dyn Any> {
        find_value_linear(self.iter(), key)
    }
}

impl<K, V> Values for [(K, V)]
where
    K: Borrow<str>,
    V: Value,
{
    fn get_value<'a>(&'a self, key: &str) -> Option<&'a dyn Any> {
        find_value_linear(self.iter(), key)
    }
}

#[cfg(feature = "alloc")]
impl<K, V> Values for alloc::vec::Vec<(K, V)>
where
    K: Borrow<str>,
    V: Value,
{
    #[inline]
    fn get_value<'a>(&'a self, key: &str) -> Option<&'a dyn Any> {
        find_value_linear(self.iter(), key)
    }
}

#[cfg(feature = "alloc")]
impl<K, V> Values for alloc::collections::VecDeque<(K, V)>
where
    K: Borrow<str>,
    V: Value,
{
    #[inline]
    fn get_value<'a>(&'a self, key: &str) -> Option<&'a dyn Any> {
        find_value_linear(self.iter(), key)
    }
}

#[cfg(feature = "alloc")]
impl<K, V> Values for alloc::collections::LinkedList<(K, V)>
where
    K: Borrow<str>,
    V: Value,
{
    #[inline]
    fn get_value<'a>(&'a self, key: &str) -> Option<&'a dyn Any> {
        find_value_linear(self.iter(), key)
    }
}

fn find_value_linear<'a, K, V, I>(it: I, key: &str) -> Option<&'a dyn Any>
where
    K: Borrow<str> + 'a,
    V: Value + 'a,
    I: Iterator<Item = &'a (K, V)>,
{
    for (k, v) in it {
        if k.borrow() == key {
            return v.ref_any();
        }
    }
    None
}

#[cfg(feature = "alloc")]
impl<K, V> Values for alloc::collections::BTreeMap<K, V>
where
    K: Borrow<str> + core::cmp::Ord,
    V: Value,
{
    #[inline]
    fn get_value<'a>(&'a self, key: &str) -> Option<&'a dyn Any> {
        self.get(key)?.ref_any()
    }
}

#[cfg(feature = "std")]
impl<K, V, S> Values for std::collections::HashMap<K, V, S>
where
    K: Borrow<str> + Eq + core::hash::Hash,
    V: Value,
    S: core::hash::BuildHasher,
{
    #[inline]
    fn get_value<'a>(&'a self, key: &str) -> Option<&'a dyn Any> {
        self.get(key)?.ref_any()
    }
}

/// A value in a [`Values`] collection.
///
/// This is <code>[dyn](https://doc.rust-lang.org/stable/std/keyword.dyn.html) [Any]</code>,
/// <code>[Option]&lt;dyn Any&gt;</code>, or a reference to either.
pub trait Value {
    /// Returns a reference to this value unless it is `None`.
    fn ref_any(&self) -> Option<&dyn Any>;
}

crate::impl_for_ref! {
    impl Value for T {
        #[inline]
        fn ref_any(&self) -> Option<&dyn Any> {
            T::ref_any(self)
        }
    }
}

impl Value for dyn Any {
    #[inline]
    fn ref_any(&self) -> Option<&dyn Any> {
        Some(self)
    }
}

impl<T: Value> Value for Option<T> {
    #[inline]
    fn ref_any(&self) -> Option<&dyn Any> {
        T::ref_any(self.as_ref()?)
    }
}

#[cfg(test)]
mod tests {
    use assert_matches::assert_matches;

    use super::*;

    #[track_caller]
    fn assert_a_10_c_blam(values: &dyn Values) {
        assert_matches!(get_value::<u32>(values, "a"), Ok(10u32));
        assert_matches!(get_value::<&str>(values, "c"), Ok(&"blam"));
        assert_matches!(get_value::<u8>(values, "a"), Err(Error::ValueType));
        assert_matches!(get_value::<u8>(values, "d"), Err(Error::ValueMissing));
    }

    #[track_caller]
    fn assert_a_12_c_blam(values: &dyn Values) {
        assert_matches!(get_value::<u32>(values, "a"), Ok(12u32));
        assert_matches!(get_value::<&str>(values, "c"), Ok(&"blam"));
        assert_matches!(get_value::<u8>(values, "a"), Err(Error::ValueType));
        assert_matches!(get_value::<u8>(values, "d"), Err(Error::ValueMissing));
    }

    #[cfg(feature = "std")]
    #[test]
    fn values_on_hashmap() {
        use alloc::boxed::Box;
        use alloc::string::String;
        use std::collections::HashMap;

        let mut values: HashMap<String, Box<dyn Any>> = HashMap::new();
        values.insert("a".into(), Box::new(12u32));
        values.insert("c".into(), Box::new("blam"));
        assert_a_12_c_blam(&values);

        let mut values: HashMap<&str, Box<dyn Any>> = HashMap::new();
        values.insert("a", Box::new(10u32));
        assert_matches!(get_value::<u32>(&values, "a"), Ok(&10u32));
    }

    #[cfg(feature = "alloc")]
    #[test]
    fn values_on_btreemap() {
        use alloc::boxed::Box;
        use alloc::collections::BTreeMap;
        use alloc::string::String;

        let mut values: BTreeMap<String, Box<dyn Any>> = BTreeMap::new();
        values.insert("a".into(), Box::new(12u32));
        values.insert("c".into(), Box::new("blam"));
        assert_a_12_c_blam(&values);

        let mut values: BTreeMap<&str, Box<dyn Any>> = BTreeMap::new();
        values.insert("a", Box::new(10u32));
        assert_matches!(get_value::<u32>(&values, "a"), Ok(&10u32));
    }

    #[test]
    fn values_on_slice() {
        let slice: &[(&str, &dyn Any)] = &[("a", &12u32), ("c", &"blam")];
        assert_a_12_c_blam(&slice);
    }

    #[cfg(feature = "alloc")]
    #[test]
    fn values_vec() {
        let vec: alloc::vec::Vec<(&str, &dyn Any)> = alloc::vec![("a", &12u32), ("c", &"blam")];
        assert_a_12_c_blam(&vec);
    }

    #[cfg(feature = "alloc")]
    #[test]
    fn values_deque() {
        let mut deque = alloc::collections::VecDeque::<(&str, &dyn Any)>::new();
        deque.push_back(("a", &12u32));
        deque.push_back(("c", &"blam"));
        assert_a_12_c_blam(&deque);
        deque.pop_front();
        deque.push_back(("a", &10u32));
        assert_a_10_c_blam(&deque);
    }

    #[cfg(feature = "alloc")]
    #[test]
    fn values_list() {
        let mut list = alloc::collections::LinkedList::<(&str, &dyn Any)>::new();
        list.push_back(("a", &12u32));
        list.push_back(("c", &"blam"));
        assert_a_12_c_blam(&list);
        list.pop_front();
        list.push_back(("a", &10u32));
        assert_a_10_c_blam(&list);
    }
}