Skip to main content

cellang/
value.rs

1use crate::types::{Constant, Type, TypeName};
2use base64::Engine;
3use base64::engine::general_purpose::STANDARD;
4use serde::Serialize;
5use serde::ser::{SerializeMap, SerializeSeq};
6use std::collections::{BTreeMap, HashMap};
7use std::fmt;
8use thiserror::Error;
9use time::{Duration, OffsetDateTime};
10
11/// Primary runtime value for CEL expressions.
12#[derive(Clone, Debug, PartialEq, Default)]
13pub enum Value {
14    Bool(bool),
15    Int(i64),
16    Uint(u64),
17    Double(f64),
18    String(String),
19    Bytes(Vec<u8>),
20    Timestamp(OffsetDateTime),
21    Duration(Duration),
22    List(ListValue),
23    Map(MapValue),
24    Struct(StructValue),
25    #[default]
26    Null,
27}
28
29/// Alias preserving the historical naming used by older versions of the crate.
30pub type List = ListValue;
31/// Alias preserving the historical naming used by older versions of the crate.
32pub type Map = MapValue;
33/// Alias preserving the historical naming used by older versions of the crate.
34pub type Struct = StructValue;
35
36impl Value {
37    /// Returns the kind of the value.
38    pub fn kind(&self) -> ValueKind {
39        match self {
40            Value::Bool(_) => ValueKind::Bool,
41            Value::Int(_) => ValueKind::Int,
42            Value::Uint(_) => ValueKind::Uint,
43            Value::Double(_) => ValueKind::Double,
44            Value::String(_) => ValueKind::String,
45            Value::Bytes(_) => ValueKind::Bytes,
46            Value::Timestamp(_) => ValueKind::Timestamp,
47            Value::Duration(_) => ValueKind::Duration,
48            Value::List(_) => ValueKind::List,
49            Value::Map(_) => ValueKind::Map,
50            Value::Struct(_) => ValueKind::Struct,
51            Value::Null => ValueKind::Null,
52        }
53    }
54
55    /// Returns true if the value is null.
56    pub fn is_null(&self) -> bool {
57        matches!(self, Value::Null)
58    }
59
60    /// Returns the CEL type of the value.
61    pub fn cel_type(&self) -> Type {
62        match self {
63            Value::Bool(_) => Type::Bool,
64            Value::Int(_) => Type::Int,
65            Value::Uint(_) => Type::Uint,
66            Value::Double(_) => Type::Double,
67            Value::String(_) => Type::String,
68            Value::Bytes(_) => Type::Bytes,
69            Value::Timestamp(_) => Type::Timestamp,
70            Value::Duration(_) => Type::Duration,
71            Value::Null => Type::Null,
72            Value::Struct(value) => Type::struct_type(value.type_name.clone()),
73            Value::List(list) => {
74                let element_ty = list
75                    .iter()
76                    .map(|value| value.cel_type())
77                    .reduce(
78                        |left, right| {
79                            if left == right { left } else { Type::Dyn }
80                        },
81                    )
82                    .unwrap_or(Type::Dyn);
83                Type::list(element_ty)
84            }
85            Value::Map(map) => {
86                let (key_ty, value_ty) = map.type_projection();
87                Type::map(key_ty, value_ty)
88            }
89        }
90    }
91
92    /// Attempts to convert the value into a typed rust value.
93    pub fn try_as<T: TryFromValue>(&self) -> Result<T, ValueError> {
94        T::try_from_value(self)
95    }
96
97    /// Attempts to convert the value into a typed rust value, consuming self.
98    pub fn try_into<T: TryFromValue>(self) -> Result<T, ValueError> {
99        T::try_from_value(&self)
100    }
101}
102
103impl fmt::Display for Value {
104    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
105        match self {
106            Value::Bool(v) => write!(f, "{v}"),
107            Value::Int(v) => write!(f, "{v}"),
108            Value::Uint(v) => write!(f, "{v}u"),
109            Value::Double(v) => write!(f, "{v}"),
110            Value::String(v) => write!(f, "\"{v}\""),
111            Value::Bytes(v) => write!(f, "b\"{}\"", STANDARD.encode(v)),
112            Value::Timestamp(ts) => write!(f, "{ts}"),
113            Value::Duration(dur) => write!(f, "{dur}"),
114            Value::List(list) => {
115                write!(f, "[")?;
116                for (idx, item) in list.iter().enumerate() {
117                    if idx > 0 {
118                        write!(f, ", ")?;
119                    }
120                    write!(f, "{item}")?;
121                }
122                write!(f, "]")
123            }
124            Value::Map(map) => {
125                write!(f, "{{")?;
126                for (idx, (key, value)) in map.iter().enumerate() {
127                    if idx > 0 {
128                        write!(f, ", ")?;
129                    }
130                    write!(f, "{key}: {value}")?;
131                }
132                write!(f, "}}")
133            }
134            Value::Struct(strct) => {
135                write!(f, "{} {{", strct.type_name)?;
136                for (idx, (field, value)) in strct.fields.iter().enumerate() {
137                    if idx > 0 {
138                        write!(f, ", ")?;
139                    }
140                    write!(f, "{field}: {value}")?;
141                }
142                write!(f, "}}")
143            }
144            Value::Null => write!(f, "null"),
145        }
146    }
147}
148
149impl Serialize for Value {
150    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
151    where
152        S: serde::Serializer,
153    {
154        match self {
155            Value::Bool(v) => serializer.serialize_bool(*v),
156            Value::Int(v) => serializer.serialize_i64(*v),
157            Value::Uint(v) => serializer.serialize_u64(*v),
158            Value::Double(v) => serializer.serialize_f64(*v),
159            Value::String(v) => serializer.serialize_str(v),
160            Value::Bytes(v) => serializer.serialize_bytes(v),
161            Value::Timestamp(v) => serializer.serialize_str(&v.to_string()),
162            Value::Duration(v) => serializer.serialize_str(&format!("{v}")),
163            Value::Null => serializer.serialize_unit(),
164            Value::List(v) => v.serialize(serializer),
165            Value::Map(v) => v.serialize(serializer),
166            Value::Struct(v) => v.serialize(serializer),
167        }
168    }
169}
170
171impl From<&Constant> for Value {
172    fn from(value: &Constant) -> Self {
173        match value {
174            Constant::Bool(v) => Value::Bool(*v),
175            Constant::Int(v) => Value::Int(*v),
176            Constant::Uint(v) => Value::Uint(*v),
177            Constant::Double(v) => Value::Double(*v),
178            Constant::String(v) => Value::String(v.clone()),
179            Constant::Bytes(v) => Value::Bytes(v.clone()),
180            Constant::Null => Value::Null,
181        }
182    }
183}
184
185/// Wrapper around a CEL list value.
186#[derive(Clone, Debug, Default, PartialEq)]
187pub struct ListValue {
188    items: Vec<Value>,
189}
190
191impl ListValue {
192    pub fn new() -> Self {
193        Self { items: Vec::new() }
194    }
195
196    pub fn len(&self) -> usize {
197        self.items.len()
198    }
199
200    pub fn is_empty(&self) -> bool {
201        self.items.is_empty()
202    }
203
204    pub fn push<V: IntoValue>(&mut self, value: V) {
205        self.items.push(value.into_value());
206    }
207
208    pub fn get(&self, index: usize) -> Option<&Value> {
209        self.items.get(index)
210    }
211
212    pub fn iter(&self) -> impl Iterator<Item = &Value> {
213        self.items.iter()
214    }
215
216    pub fn into_vec(self) -> Vec<Value> {
217        self.items
218    }
219}
220
221impl<T> From<Vec<T>> for ListValue
222where
223    T: IntoValue,
224{
225    fn from(value: Vec<T>) -> Self {
226        let items = value.into_iter().map(|item| item.into_value()).collect();
227        ListValue { items }
228    }
229}
230
231impl IntoIterator for ListValue {
232    type Item = Value;
233    type IntoIter = std::vec::IntoIter<Value>;
234
235    fn into_iter(self) -> Self::IntoIter {
236        self.items.into_iter()
237    }
238}
239
240impl Serialize for ListValue {
241    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
242    where
243        S: serde::Serializer,
244    {
245        let mut seq = serializer.serialize_seq(Some(self.items.len()))?;
246        for value in &self.items {
247            seq.serialize_element(value)?;
248        }
249        seq.end()
250    }
251}
252
253/// Wrapper around a CEL map value.
254#[derive(Clone, Debug, Default, PartialEq)]
255pub struct MapValue {
256    entries: BTreeMap<Key, Value>,
257}
258
259impl MapValue {
260    pub fn new() -> Self {
261        Self {
262            entries: BTreeMap::new(),
263        }
264    }
265
266    pub fn len(&self) -> usize {
267        self.entries.len()
268    }
269
270    pub fn is_empty(&self) -> bool {
271        self.entries.is_empty()
272    }
273
274    pub fn insert<K, V>(&mut self, key: K, value: V)
275    where
276        K: Into<Key>,
277        V: IntoValue,
278    {
279        self.entries.insert(key.into(), value.into_value());
280    }
281
282    pub fn get_by_key(&self, key: &Key) -> Option<&Value> {
283        self.entries.get(key)
284    }
285
286    pub fn get_str(&self, key: &str) -> Option<&Value> {
287        self.entries.get(&Key::from(key))
288    }
289
290    pub fn iter(&self) -> impl Iterator<Item = (&Key, &Value)> {
291        self.entries.iter()
292    }
293
294    pub fn contains_key(&self, key: &Key) -> bool {
295        self.entries.contains_key(key)
296    }
297
298    pub fn type_projection(&self) -> (Type, Type) {
299        let key_ty = self
300            .entries
301            .keys()
302            .map(Key::cel_type)
303            .reduce(|left, right| if left == right { left } else { Type::Dyn })
304            .unwrap_or(Type::Dyn);
305        let value_ty = self
306            .entries
307            .values()
308            .map(Value::cel_type)
309            .reduce(|left, right| if left == right { left } else { Type::Dyn })
310            .unwrap_or(Type::Dyn);
311        (key_ty, value_ty)
312    }
313}
314
315impl<K, V> From<BTreeMap<K, V>> for MapValue
316where
317    K: Into<Key>,
318    V: IntoValue,
319{
320    fn from(value: BTreeMap<K, V>) -> Self {
321        let mut map = MapValue::new();
322        for (key, val) in value {
323            map.insert(key.into(), val);
324        }
325        map
326    }
327}
328
329impl IntoIterator for MapValue {
330    type Item = (Key, Value);
331    type IntoIter = std::collections::btree_map::IntoIter<Key, Value>;
332
333    fn into_iter(self) -> Self::IntoIter {
334        self.entries.into_iter()
335    }
336}
337
338impl Serialize for MapValue {
339    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
340    where
341        S: serde::Serializer,
342    {
343        let mut map = serializer.serialize_map(Some(self.entries.len()))?;
344        for (key, value) in &self.entries {
345            map.serialize_entry(key, value)?;
346        }
347        map.end()
348    }
349}
350
351/// Runtime struct/message representation.
352#[derive(Clone, Debug, PartialEq)]
353pub struct StructValue {
354    pub type_name: TypeName,
355    pub fields: BTreeMap<String, Value>,
356}
357
358impl StructValue {
359    pub fn new(name: impl Into<TypeName>) -> Self {
360        StructValue {
361            type_name: name.into(),
362            fields: BTreeMap::new(),
363        }
364    }
365
366    pub fn with_fields(
367        name: impl Into<TypeName>,
368        fields: impl IntoIterator<Item = (String, Value)>,
369    ) -> Self {
370        StructValue {
371            type_name: name.into(),
372            fields: fields.into_iter().collect::<BTreeMap<_, _>>(),
373        }
374    }
375
376    pub fn set_field<K, V>(&mut self, name: K, value: V)
377    where
378        K: Into<String>,
379        V: IntoValue,
380    {
381        self.fields.insert(name.into(), value.into_value());
382    }
383
384    pub fn get(&self, name: &str) -> Option<&Value> {
385        self.fields.get(name)
386    }
387}
388
389impl Serialize for StructValue {
390    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
391    where
392        S: serde::Serializer,
393    {
394        let mut state = serializer.serialize_map(Some(self.fields.len()))?;
395        for (name, value) in &self.fields {
396            state.serialize_entry(name, value)?;
397        }
398        state.end()
399    }
400}
401
402/// Supported CEL map keys.
403#[derive(Clone, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
404pub enum Key {
405    Bool(bool),
406    Int(i64),
407    Uint(u64),
408    String(String),
409    Bytes(Vec<u8>),
410}
411
412impl Key {
413    pub fn cel_type(&self) -> Type {
414        match self {
415            Key::Bool(_) => Type::Bool,
416            Key::Int(_) => Type::Int,
417            Key::Uint(_) => Type::Uint,
418            Key::String(_) => Type::String,
419            Key::Bytes(_) => Type::Bytes,
420        }
421    }
422}
423
424impl fmt::Display for Key {
425    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
426        match self {
427            Key::Bool(value) => write!(f, "{value}"),
428            Key::Int(value) => write!(f, "{value}"),
429            Key::Uint(value) => write!(f, "{value}u"),
430            Key::String(value) => write!(f, "{value}"),
431            Key::Bytes(value) => write!(f, "b\"{}\"", STANDARD.encode(value)),
432        }
433    }
434}
435
436impl From<&Key> for Value {
437    fn from(key: &Key) -> Self {
438        match key {
439            Key::Bool(value) => Value::Bool(*value),
440            Key::Int(value) => Value::Int(*value),
441            Key::Uint(value) => Value::Uint(*value),
442            Key::String(value) => Value::String(value.clone()),
443            Key::Bytes(value) => Value::Bytes(value.clone()),
444        }
445    }
446}
447
448impl From<Key> for Value {
449    fn from(key: Key) -> Self {
450        Value::from(&key)
451    }
452}
453
454impl From<&str> for Key {
455    fn from(value: &str) -> Self {
456        Key::String(value.to_string())
457    }
458}
459
460impl From<String> for Key {
461    fn from(value: String) -> Self {
462        Key::String(value)
463    }
464}
465
466impl From<bool> for Key {
467    fn from(value: bool) -> Self {
468        Key::Bool(value)
469    }
470}
471
472impl From<i64> for Key {
473    fn from(value: i64) -> Self {
474        Key::Int(value)
475    }
476}
477
478impl From<u64> for Key {
479    fn from(value: u64) -> Self {
480        Key::Uint(value)
481    }
482}
483
484impl From<Vec<u8>> for Key {
485    fn from(value: Vec<u8>) -> Self {
486        Key::Bytes(value)
487    }
488}
489
490impl TryFrom<&Value> for Key {
491    type Error = ValueError;
492
493    fn try_from(value: &Value) -> Result<Self, Self::Error> {
494        match value {
495            Value::Bool(v) => Ok(Key::Bool(*v)),
496            Value::Int(v) => Ok(Key::Int(*v)),
497            Value::Uint(v) => Ok(Key::Uint(*v)),
498            Value::String(v) => Ok(Key::String(v.clone())),
499            Value::Bytes(v) => Ok(Key::Bytes(v.clone())),
500            _ => Err(ValueError::InvalidMapKey(value.kind())),
501        }
502    }
503}
504
505impl Serialize for Key {
506    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
507    where
508        S: serde::Serializer,
509    {
510        match self {
511            Key::Bool(value) => serializer.serialize_bool(*value),
512            Key::Int(value) => serializer.serialize_i64(*value),
513            Key::Uint(value) => serializer.serialize_u64(*value),
514            Key::String(value) => serializer.serialize_str(value),
515            Key::Bytes(value) => serializer.serialize_bytes(value),
516        }
517    }
518}
519
520/// Helper trait used to convert rust values into CEL runtime values.
521pub trait IntoValue {
522    fn into_value(self) -> Value;
523}
524
525impl IntoValue for Value {
526    fn into_value(self) -> Value {
527        self
528    }
529}
530
531impl IntoValue for &Value {
532    fn into_value(self) -> Value {
533        self.clone()
534    }
535}
536
537impl IntoValue for bool {
538    fn into_value(self) -> Value {
539        Value::Bool(self)
540    }
541}
542
543impl IntoValue for i64 {
544    fn into_value(self) -> Value {
545        Value::Int(self)
546    }
547}
548
549impl IntoValue for i32 {
550    fn into_value(self) -> Value {
551        Value::Int(i64::from(self))
552    }
553}
554
555impl IntoValue for u64 {
556    fn into_value(self) -> Value {
557        Value::Uint(self)
558    }
559}
560
561impl IntoValue for u32 {
562    fn into_value(self) -> Value {
563        Value::Uint(u64::from(self))
564    }
565}
566
567impl IntoValue for f64 {
568    fn into_value(self) -> Value {
569        Value::Double(self)
570    }
571}
572
573impl IntoValue for f32 {
574    fn into_value(self) -> Value {
575        Value::Double(f64::from(self))
576    }
577}
578
579impl IntoValue for String {
580    fn into_value(self) -> Value {
581        Value::String(self)
582    }
583}
584
585impl IntoValue for &str {
586    fn into_value(self) -> Value {
587        Value::String(self.to_string())
588    }
589}
590
591impl IntoValue for Vec<u8> {
592    fn into_value(self) -> Value {
593        Value::Bytes(self)
594    }
595}
596
597impl IntoValue for &[u8] {
598    fn into_value(self) -> Value {
599        Value::Bytes(self.to_vec())
600    }
601}
602
603impl IntoValue for Duration {
604    fn into_value(self) -> Value {
605        Value::Duration(self)
606    }
607}
608
609impl IntoValue for OffsetDateTime {
610    fn into_value(self) -> Value {
611        Value::Timestamp(self)
612    }
613}
614
615impl IntoValue for ListValue {
616    fn into_value(self) -> Value {
617        Value::List(self)
618    }
619}
620
621impl IntoValue for MapValue {
622    fn into_value(self) -> Value {
623        Value::Map(self)
624    }
625}
626
627impl IntoValue for StructValue {
628    fn into_value(self) -> Value {
629        Value::Struct(self)
630    }
631}
632
633impl<K, V> IntoValue for BTreeMap<K, V>
634where
635    K: Into<Key>,
636    V: IntoValue,
637{
638    fn into_value(self) -> Value {
639        Value::Map(MapValue::from(self))
640    }
641}
642
643impl<K, V> IntoValue for HashMap<K, V>
644where
645    K: Into<Key>,
646    V: IntoValue,
647{
648    fn into_value(self) -> Value {
649        let btree_map: BTreeMap<_, _> = self
650            .into_iter()
651            .map(|(k, v)| (k.into(), v.into_value()))
652            .collect();
653        Value::Map(MapValue { entries: btree_map })
654    }
655}
656
657impl<T> IntoValue for Vec<T>
658where
659    T: IntoValue,
660{
661    fn into_value(self) -> Value {
662        let mut list = ListValue::new();
663        for item in self {
664            list.push(item);
665        }
666        Value::List(list)
667    }
668}
669
670impl<T> IntoValue for Option<T>
671where
672    T: IntoValue,
673{
674    fn into_value(self) -> Value {
675        match self {
676            Some(value) => value.into_value(),
677            None => Value::Null,
678        }
679    }
680}
681
682/// Helper trait for converting CEL values into typed rust values.
683pub trait TryFromValue: Sized {
684    fn try_from_value(value: &Value) -> Result<Self, ValueError>;
685}
686
687impl TryFromValue for Value {
688    fn try_from_value(value: &Value) -> Result<Self, ValueError> {
689        Ok(value.clone())
690    }
691}
692
693impl TryFromValue for bool {
694    fn try_from_value(value: &Value) -> Result<Self, ValueError> {
695        match value {
696            Value::Bool(v) => Ok(*v),
697            _ => Err(ValueError::unexpected("bool", value.kind())),
698        }
699    }
700}
701
702impl TryFromValue for i64 {
703    fn try_from_value(value: &Value) -> Result<Self, ValueError> {
704        match value {
705            Value::Int(v) => Ok(*v),
706            _ => Err(ValueError::unexpected("int", value.kind())),
707        }
708    }
709}
710
711impl TryFromValue for u64 {
712    fn try_from_value(value: &Value) -> Result<Self, ValueError> {
713        match value {
714            Value::Uint(v) => Ok(*v),
715            _ => Err(ValueError::unexpected("uint", value.kind())),
716        }
717    }
718}
719
720impl TryFromValue for f64 {
721    fn try_from_value(value: &Value) -> Result<Self, ValueError> {
722        match value {
723            Value::Double(v) => Ok(*v),
724            Value::Int(v) => Ok(*v as f64),
725            Value::Uint(v) => Ok(*v as f64),
726            _ => Err(ValueError::unexpected("double", value.kind())),
727        }
728    }
729}
730
731impl TryFromValue for String {
732    fn try_from_value(value: &Value) -> Result<Self, ValueError> {
733        match value {
734            Value::String(v) => Ok(v.clone()),
735            _ => Err(ValueError::unexpected("string", value.kind())),
736        }
737    }
738}
739
740impl TryFromValue for Vec<u8> {
741    fn try_from_value(value: &Value) -> Result<Self, ValueError> {
742        match value {
743            Value::Bytes(v) => Ok(v.clone()),
744            _ => Err(ValueError::unexpected("bytes", value.kind())),
745        }
746    }
747}
748
749impl TryFromValue for Duration {
750    fn try_from_value(value: &Value) -> Result<Self, ValueError> {
751        match value {
752            Value::Duration(v) => Ok(*v),
753            _ => Err(ValueError::unexpected("duration", value.kind())),
754        }
755    }
756}
757
758impl TryFromValue for OffsetDateTime {
759    fn try_from_value(value: &Value) -> Result<Self, ValueError> {
760        match value {
761            Value::Timestamp(v) => Ok(*v),
762            _ => Err(ValueError::unexpected("timestamp", value.kind())),
763        }
764    }
765}
766
767impl TryFromValue for ListValue {
768    fn try_from_value(value: &Value) -> Result<Self, ValueError> {
769        match value {
770            Value::List(v) => Ok(v.clone()),
771            _ => Err(ValueError::unexpected("list", value.kind())),
772        }
773    }
774}
775
776impl TryFromValue for MapValue {
777    fn try_from_value(value: &Value) -> Result<Self, ValueError> {
778        match value {
779            Value::Map(v) => Ok(v.clone()),
780            _ => Err(ValueError::unexpected("map", value.kind())),
781        }
782    }
783}
784
785impl TryFromValue for StructValue {
786    fn try_from_value(value: &Value) -> Result<Self, ValueError> {
787        match value {
788            Value::Struct(v) => Ok(v.clone()),
789            _ => Err(ValueError::unexpected("struct", value.kind())),
790        }
791    }
792}
793
794impl<T> TryFromValue for Vec<T>
795where
796    T: TryFromValue,
797{
798    fn try_from_value(value: &Value) -> Result<Self, ValueError> {
799        match value {
800            Value::List(list) => list
801                .iter()
802                .map(T::try_from_value)
803                .collect::<Result<Vec<_>, _>>(),
804            _ => Err(ValueError::unexpected("list", value.kind())),
805        }
806    }
807}
808
809impl<T> TryFromValue for BTreeMap<String, T>
810where
811    T: TryFromValue,
812{
813    fn try_from_value(value: &Value) -> Result<Self, ValueError> {
814        match value {
815            Value::Map(map) => map
816                .iter()
817                .map(|(key, value)| match key {
818                    Key::String(name) => {
819                        let typed = T::try_from_value(value)?;
820                        Ok((name.clone(), typed))
821                    }
822                    _ => Err(ValueError::InvalidMapKey(key.kind())),
823                })
824                .collect::<Result<BTreeMap<_, _>, _>>(),
825            _ => Err(ValueError::unexpected("map", value.kind())),
826        }
827    }
828}
829
830impl<T> TryFromValue for HashMap<String, T>
831where
832    T: TryFromValue,
833{
834    fn try_from_value(value: &Value) -> Result<Self, ValueError> {
835        match value {
836            Value::Map(map) => map
837                .iter()
838                .map(|(key, value)| match key {
839                    Key::String(name) => {
840                        let typed = T::try_from_value(value)?;
841                        Ok((name.clone(), typed))
842                    }
843                    _ => Err(ValueError::InvalidMapKey(key.kind())),
844                })
845                .collect::<Result<HashMap<_, _>, _>>(),
846            _ => Err(ValueError::unexpected("map", value.kind())),
847        }
848    }
849}
850
851impl<T> TryFromValue for Option<T>
852where
853    T: TryFromValue,
854{
855    fn try_from_value(value: &Value) -> Result<Self, ValueError> {
856        if value.is_null() {
857            Ok(None)
858        } else {
859            Ok(Some(T::try_from_value(value)?))
860        }
861    }
862}
863
864/// Classification of runtime values used for diagnostics.
865#[derive(Copy, Clone, Debug, PartialEq, Eq)]
866pub enum ValueKind {
867    Null,
868    Bool,
869    Int,
870    Uint,
871    Double,
872    String,
873    Bytes,
874    Timestamp,
875    Duration,
876    List,
877    Map,
878    Struct,
879}
880
881impl fmt::Display for ValueKind {
882    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
883        f.write_str(match self {
884            ValueKind::Null => "null",
885            ValueKind::Bool => "bool",
886            ValueKind::Int => "int",
887            ValueKind::Uint => "uint",
888            ValueKind::Double => "double",
889            ValueKind::String => "string",
890            ValueKind::Bytes => "bytes",
891            ValueKind::Timestamp => "timestamp",
892            ValueKind::Duration => "duration",
893            ValueKind::List => "list",
894            ValueKind::Map => "map",
895            ValueKind::Struct => "struct",
896        })
897    }
898}
899
900impl Key {
901    fn kind(&self) -> ValueKind {
902        match self {
903            Key::Bool(_) => ValueKind::Bool,
904            Key::Int(_) => ValueKind::Int,
905            Key::Uint(_) => ValueKind::Uint,
906            Key::String(_) => ValueKind::String,
907            Key::Bytes(_) => ValueKind::Bytes,
908        }
909    }
910}
911
912/// Errors that may occur while converting between CEL values and rust values.
913#[derive(Debug, Error, Clone, PartialEq, Eq)]
914pub enum ValueError {
915    #[error("expected {expected}, got {actual}")]
916    UnexpectedType {
917        expected: &'static str,
918        actual: ValueKind,
919    },
920    #[error("unsupported map key type: {0}")]
921    InvalidMapKey(ValueKind),
922    #[error("index {index} is out of bounds for length {len}")]
923    IndexOutOfBounds { index: usize, len: usize },
924    #[error("{0}")]
925    Message(String),
926}
927
928impl ValueError {
929    pub fn unexpected(expected: &'static str, actual: ValueKind) -> Self {
930        ValueError::UnexpectedType { expected, actual }
931    }
932}
933
934#[cfg(test)]
935mod tests {
936    use super::*;
937    use serde_json::{Value as JsonValue, json};
938    use time::Duration;
939
940    #[test]
941    fn value_serializes_scalars() {
942        let cases = vec![
943            (Value::Bool(true), json!(true)),
944            (Value::Int(-42), json!(-42)),
945            (Value::Uint(7), json!(7)),
946            (Value::Double(2.5), json!(2.5)),
947            (Value::String("hi".into()), json!("hi")),
948            (Value::Bytes(vec![1, 2, 3]), json!([1, 2, 3])),
949            (Value::Duration(Duration::seconds(5)), json!("5s")),
950            (Value::Null, JsonValue::Null),
951        ];
952        for (value, expected) in cases {
953            let serialized = serde_json::to_value(&value).unwrap();
954            assert_eq!(serialized, expected);
955        }
956    }
957
958    #[test]
959    fn value_serializes_nested_structures() {
960        let mut struct_value = StructValue::new("example.User");
961        struct_value.set_field("name", "Ada");
962        struct_value.set_field("roles", ListValue::from(vec!["admin", "user"]));
963
964        let mut map = MapValue::new();
965        map.insert("user", Value::Struct(struct_value.clone()));
966        map.insert("active", true);
967
968        let list = ListValue::from(vec![
969            Value::Map(map.clone()),
970            Value::Struct(struct_value),
971        ]);
972        let serialized = serde_json::to_value(&list).unwrap();
973
974        assert_eq!(
975            serialized,
976            json!([
977                {"user": {"name": "Ada", "roles": ["admin", "user"]}, "active": true},
978                {"name": "Ada", "roles": ["admin", "user"]}
979            ])
980        );
981    }
982
983    #[test]
984    fn json_deserializes_into_struct_value() {
985        let json = json!({
986            "name": "Ada",
987            "roles": ["admin", "user"],
988            "active": true
989        });
990        let expected = {
991            let mut map = MapValue::new();
992            map.insert("name", "Ada");
993            map.insert("roles", ListValue::from(vec!["admin", "user"]));
994            map.insert("active", true);
995            Value::Map(map)
996        };
997        assert_eq!(json_to_value(json), expected);
998    }
999
1000    #[test]
1001    fn json_deserializes_complex_map() {
1002        let json = json!({
1003            "users": [
1004                {"name": "Ada", "roles": ["admin"]},
1005                {"name": "Bob", "roles": ["user"]}
1006            ],
1007            "count": 2
1008        });
1009        let mut user_one = MapValue::new();
1010        user_one.insert("name", "Ada");
1011        user_one.insert("roles", ListValue::from(vec!["admin"]));
1012
1013        let mut user_two = MapValue::new();
1014        user_two.insert("name", "Bob");
1015        user_two.insert("roles", ListValue::from(vec!["user"]));
1016
1017        let expected = {
1018            let mut map = MapValue::new();
1019            map.insert(
1020                "users",
1021                Value::List(ListValue::from(vec![
1022                    Value::Map(user_one),
1023                    Value::Map(user_two),
1024                ])),
1025            );
1026            map.insert("count", 2);
1027            Value::Map(map)
1028        };
1029        assert_eq!(json_to_value(json), expected);
1030    }
1031
1032    fn json_to_value(value: JsonValue) -> Value {
1033        match value {
1034            JsonValue::Null => Value::Null,
1035            JsonValue::Bool(flag) => Value::Bool(flag),
1036            JsonValue::Number(num) => num
1037                .as_i64()
1038                .map(Value::Int)
1039                .or_else(|| num.as_u64().map(Value::Uint))
1040                .or_else(|| num.as_f64().map(Value::Double))
1041                .unwrap_or(Value::Null),
1042            JsonValue::String(text) => Value::String(text),
1043            JsonValue::Array(items) => {
1044                let converted =
1045                    items.into_iter().map(json_to_value).collect::<Vec<_>>();
1046                Value::List(ListValue::from(converted))
1047            }
1048            JsonValue::Object(map) => {
1049                let mut cel_map = MapValue::new();
1050                for (key, value) in map {
1051                    cel_map.insert(key, json_to_value(value));
1052                }
1053                Value::Map(cel_map)
1054            }
1055        }
1056    }
1057}