Skip to main content

temple_dsl/common/
value.rs

1use indexmap::IndexMap;
2use rust_decimal::prelude::ToPrimitive;
3use rust_decimal::Decimal;
4use serde::de::{self, IntoDeserializer, Visitor};
5use smol_str::SmolStr;
6use std::collections::HashMap;
7
8/// A dynamic value: a render's input and, unless deserialized into your own
9/// type, its output. Numbers are integers or exact decimals, never floats;
10/// objects keep insertion order.
11#[derive(Debug, Clone, PartialEq)]
12#[allow(missing_docs)] // variants name themselves
13pub enum Value {
14    Null,
15    Bool(bool),
16    Int(i64),
17    Decimal(Decimal),
18    Str(SmolStr),
19    Arr(Vec<Value>),
20    Obj(IndexMap<SmolStr, Value>),
21}
22
23// Non-recursive: the derived drop overflows the stack on a deep value. Nested
24// containers go to a heap worklist; a flat value allocates nothing.
25impl Drop for Value {
26    #[inline]
27    fn drop(&mut self) {
28        match self {
29            Value::Arr(items) if !items.is_empty() => {}
30            Value::Obj(object) if !object.is_empty() => {}
31            _ => return,
32        }
33        let mut stack: Vec<Value> = Vec::new();
34        detach_nested(self, &mut stack);
35        while let Some(mut value) = stack.pop() {
36            detach_nested(&mut value, &mut stack);
37        }
38    }
39}
40
41fn detach_nested(value: &mut Value, stack: &mut Vec<Value>) {
42    fn nested(value: &Value) -> bool {
43        match value {
44            Value::Arr(items) => !items.is_empty(),
45            Value::Obj(object) => !object.is_empty(),
46            _ => false,
47        }
48    }
49    match value {
50        Value::Arr(items) => {
51            for child in items.iter_mut().filter(|child| nested(child)) {
52                stack.push(std::mem::replace(child, Value::Null));
53            }
54        }
55        Value::Obj(object) => {
56            for child in object.values_mut().filter(|child| nested(child)) {
57                stack.push(std::mem::replace(child, Value::Null));
58            }
59        }
60        _ => {}
61    }
62}
63
64impl Value {
65    /// The type as a word (`null`, `bool`, `int`, `decimal`, `string`,
66    /// `array`, `object`), as `type_of` and error messages print it.
67    pub fn kind(&self) -> &'static str {
68        match self {
69            Value::Null => "null",
70            Value::Bool(_) => "bool",
71            Value::Int(_) => "int",
72            Value::Decimal(_) => "decimal",
73            Value::Str(_) => "string",
74            Value::Arr(_) => "array",
75            Value::Obj(_) => "object",
76        }
77    }
78
79    /// The items, if this is an array; otherwise the value back.
80    pub fn into_arr(mut self) -> Result<Vec<Value>, Value> {
81        // taken through `&mut`: `Value` has a `Drop`, so fields can't move out
82        match &mut self {
83            Value::Arr(items) => Ok(std::mem::take(items)),
84            _ => Err(self),
85        }
86    }
87
88    /// The entries, if this is an object; otherwise the value back.
89    pub fn into_obj(mut self) -> Result<IndexMap<SmolStr, Value>, Value> {
90        match &mut self {
91            Value::Obj(object) => Ok(std::mem::take(object)),
92            _ => Err(self),
93        }
94    }
95
96    /// An object from `(key, value)` pairs.
97    ///
98    /// ```
99    /// use temple_dsl::Value;
100    ///
101    /// let user = Value::obj([("name", Value::from("Ada")), ("age", Value::Int(36))]);
102    /// assert_eq!(user.kind(), "object");
103    /// ```
104    pub fn obj<K, V, I>(pairs: I) -> Value
105    where
106        K: Into<SmolStr>,
107        V: Into<Value>,
108        I: IntoIterator<Item = (K, V)>,
109    {
110        Value::Obj(
111            pairs
112                .into_iter()
113                .map(|(key, value)| (key.into(), value.into()))
114                .collect(),
115        )
116    }
117}
118
119impl From<()> for Value {
120    fn from(_: ()) -> Value {
121        Value::Null
122    }
123}
124impl From<bool> for Value {
125    fn from(value: bool) -> Value {
126        Value::Bool(value)
127    }
128}
129impl From<i64> for Value {
130    fn from(value: i64) -> Value {
131        Value::Int(value)
132    }
133}
134impl From<i32> for Value {
135    fn from(value: i32) -> Value {
136        Value::Int(i64::from(value))
137    }
138}
139impl From<u32> for Value {
140    fn from(value: u32) -> Value {
141        Value::Int(i64::from(value))
142    }
143}
144impl From<&str> for Value {
145    fn from(value: &str) -> Value {
146        Value::Str(value.into())
147    }
148}
149impl From<String> for Value {
150    fn from(value: String) -> Value {
151        Value::Str(value.into())
152    }
153}
154impl From<SmolStr> for Value {
155    fn from(value: SmolStr) -> Value {
156        Value::Str(value)
157    }
158}
159impl From<Decimal> for Value {
160    fn from(value: Decimal) -> Value {
161        Value::Decimal(value)
162    }
163}
164
165impl<V: Into<Value>> From<Vec<V>> for Value {
166    fn from(items: Vec<V>) -> Value {
167        Value::Arr(items.into_iter().map(Into::into).collect())
168    }
169}
170
171impl<K: Into<SmolStr>, V: Into<Value>, const N: usize> From<[(K, V); N]> for Value {
172    fn from(pairs: [(K, V); N]) -> Value {
173        Value::Obj(
174            pairs
175                .into_iter()
176                .map(|(key, value)| (key.into(), value.into()))
177                .collect(),
178        )
179    }
180}
181
182impl<K, V> From<HashMap<K, V>> for Value
183where
184    K: Into<SmolStr>,
185    V: Into<Value>,
186{
187    fn from(map: HashMap<K, V>) -> Value {
188        Value::Obj(
189            map.into_iter()
190                .map(|(key, value)| (key.into(), value.into()))
191                .collect(),
192        )
193    }
194}
195
196impl<K, V> From<IndexMap<K, V>> for Value
197where
198    K: Into<SmolStr>,
199    V: Into<Value>,
200{
201    fn from(map: IndexMap<K, V>) -> Value {
202        Value::Obj(
203            map.into_iter()
204                .map(|(key, value)| (key.into(), value.into()))
205                .collect(),
206        )
207    }
208}
209
210/// Exact: numbers convert from their digits, never through `f64`; a number
211/// outside `Decimal`'s range becomes `Null`.
212#[cfg(feature = "json")]
213impl From<serde_json::Value> for Value {
214    fn from(value: serde_json::Value) -> Value {
215        match value {
216            serde_json::Value::Null => Value::Null,
217            serde_json::Value::Bool(flag) => Value::Bool(flag),
218            serde_json::Value::Number(number) => match number.as_i64() {
219                Some(int) => Value::Int(int),
220                None => number
221                    .to_string()
222                    .parse()
223                    .map(Value::Decimal)
224                    .unwrap_or(Value::Null),
225            },
226            serde_json::Value::String(text) => Value::Str(text.into()),
227            serde_json::Value::Array(items) => {
228                Value::Arr(items.into_iter().map(Value::from).collect())
229            }
230            serde_json::Value::Object(object) => Value::Obj(
231                object
232                    .into_iter()
233                    .map(|(key, value)| (SmolStr::new(&key), Value::from(value)))
234                    .collect(),
235            ),
236        }
237    }
238}
239
240/// Decimals become JSON number tokens with their exact digits.
241#[cfg(feature = "json")]
242impl From<Value> for serde_json::Value {
243    fn from(mut value: Value) -> serde_json::Value {
244        match &mut value {
245            Value::Null => serde_json::Value::Null,
246            Value::Bool(flag) => serde_json::Value::Bool(*flag),
247            Value::Int(int) => serde_json::Value::from(*int),
248            Value::Decimal(decimal) => decimal
249                .to_string()
250                .parse::<serde_json::Number>()
251                .map(serde_json::Value::Number)
252                .unwrap_or_else(|_| serde_json::Value::String(decimal.to_string())),
253            Value::Str(text) => serde_json::Value::String(std::mem::take(text).into()),
254            Value::Arr(items) => serde_json::Value::Array(
255                std::mem::take(items).into_iter().map(Into::into).collect(),
256            ),
257            Value::Obj(object) => serde_json::Value::Object(
258                std::mem::take(object)
259                    .into_iter()
260                    .map(|(key, value)| (key.to_string(), value.into()))
261                    .collect(),
262            ),
263        }
264    }
265}
266
267impl<'de> de::Deserializer<'de> for &'de Value {
268    type Error = de::value::Error;
269
270    fn deserialize_any<V>(self, visitor: V) -> Result<V::Value, Self::Error>
271    where
272        V: Visitor<'de>,
273    {
274        match self {
275            Value::Null => visitor.visit_unit(),
276            Value::Bool(flag) => visitor.visit_bool(*flag),
277            Value::Int(int) => visitor.visit_i64(*int),
278            // String form so rust_decimal's Deserialize lands cleanly into `Decimal`.
279            Value::Decimal(decimal) => visitor.visit_string(decimal.to_string()),
280            Value::Str(text) => visitor.visit_str(text.as_str()),
281            Value::Arr(items) => visitor.visit_seq(ValueSeqAccess { iter: items.iter() }),
282            Value::Obj(object) => visitor.visit_map(ValueMapAccess {
283                iter: object.iter(),
284                value: None,
285            }),
286        }
287    }
288
289    fn deserialize_option<V>(self, visitor: V) -> Result<V::Value, Self::Error>
290    where
291        V: Visitor<'de>,
292    {
293        match self {
294            Value::Null => visitor.visit_none(),
295            _ => visitor.visit_some(self),
296        }
297    }
298
299    // An f64 target field is an explicit opt-in; the model itself carries no f64.
300    fn deserialize_f64<V>(self, visitor: V) -> Result<V::Value, Self::Error>
301    where
302        V: Visitor<'de>,
303    {
304        match self {
305            Value::Int(int) => visitor.visit_f64(*int as f64),
306            Value::Decimal(decimal) => match decimal.to_f64() {
307                Some(float) => visitor.visit_f64(float),
308                None => Err(de::Error::custom("decimal out of f64 range")),
309            },
310            _ => self.deserialize_any(visitor),
311        }
312    }
313
314    fn deserialize_f32<V>(self, visitor: V) -> Result<V::Value, Self::Error>
315    where
316        V: Visitor<'de>,
317    {
318        self.deserialize_f64(visitor)
319    }
320
321    fn deserialize_enum<V>(
322        self,
323        _name: &'static str,
324        _variants: &'static [&'static str],
325        visitor: V,
326    ) -> Result<V::Value, Self::Error>
327    where
328        V: Visitor<'de>,
329    {
330        // only unit variants, named by a string
331        match self {
332            Value::Str(text) => visitor.visit_enum(text.as_str().into_deserializer()),
333            other => Err(de::Error::custom(format!(
334                "cannot deserialize enum from {}",
335                other.kind()
336            ))),
337        }
338    }
339
340    serde::forward_to_deserialize_any! {
341        bool i8 i16 i32 i64 u8 u16 u32 u64 char str string bytes
342        byte_buf unit unit_struct newtype_struct seq tuple
343        tuple_struct map struct identifier ignored_any
344    }
345}
346
347struct ValueSeqAccess<'a> {
348    iter: std::slice::Iter<'a, Value>,
349}
350
351impl<'de> de::SeqAccess<'de> for ValueSeqAccess<'de> {
352    type Error = de::value::Error;
353
354    fn next_element_seed<T>(&mut self, seed: T) -> Result<Option<T::Value>, Self::Error>
355    where
356        T: de::DeserializeSeed<'de>,
357    {
358        match self.iter.next() {
359            Some(value) => seed.deserialize(value).map(Some),
360            None => Ok(None),
361        }
362    }
363}
364
365struct ValueMapAccess<'a> {
366    iter: indexmap::map::Iter<'a, SmolStr, Value>,
367    value: Option<&'a Value>,
368}
369
370impl<'de> de::MapAccess<'de> for ValueMapAccess<'de> {
371    type Error = de::value::Error;
372
373    fn next_key_seed<K>(&mut self, seed: K) -> Result<Option<K::Value>, Self::Error>
374    where
375        K: de::DeserializeSeed<'de>,
376    {
377        match self.iter.next() {
378            Some((key, value)) => {
379                self.value = Some(value);
380                seed.deserialize(de::value::BorrowedStrDeserializer::new(key.as_str()))
381                    .map(Some)
382            }
383            None => Ok(None),
384        }
385    }
386
387    fn next_value_seed<V>(&mut self, seed: V) -> Result<V::Value, Self::Error>
388    where
389        V: de::DeserializeSeed<'de>,
390    {
391        let value = self
392            .value
393            .take()
394            .ok_or_else(|| de::Error::custom("value requested before key"))?;
395        seed.deserialize(value)
396    }
397}