Skip to main content

bel/
ser.rs

1// The serde_json crate implements a Serializer for its own Value enum, that is
2// almost exactly the same to our Value enum, so this is more or less copied
3// from [serde_json](https://github.com/serde-rs/json/blob/master/src/value/ser.rs),
4// also mentioned in the [serde documentation](https://serde.rs/).
5
6use std::{collections::HashMap, fmt::Display, iter::FromIterator, sync::Arc};
7
8#[cfg(feature = "time")]
9use serde::ser::SerializeStruct;
10use serde::{
11    Serialize,
12    ser::{self, Impossible},
13};
14use thiserror::Error;
15#[cfg(feature = "time")]
16use time::DateTime;
17
18use crate::{Value, objects::Key};
19
20pub struct Serializer;
21pub struct KeySerializer;
22
23/// A wrapper Duration type which allows conversion to [Value::Duration] for
24/// types using automatic conversion with [serde::Serialize].
25///
26/// # Examples
27///
28/// ```
29/// use bel::{Context, Duration, Program};
30/// use serde::Serialize;
31///
32/// #[derive(Serialize)]
33/// struct MyStruct {
34///     dur: Duration,
35/// }
36///
37/// let mut context = Context::default();
38///
39/// // MyStruct will be implicitly serialized into the CEL appropriate types
40/// context
41///     .add_variable(
42///         "foo",
43///         MyStruct {
44///             dur: bel::duration::Duration::hours(2).into(),
45///         },
46///     )
47///     .unwrap();
48///
49/// let program = Program::compile(r#"foo.dur == Duration("2h")"#).unwrap();
50/// let value = program.execute(&context).unwrap();
51/// assert_eq!(value, true.into());
52/// ```
53#[cfg(feature = "time")]
54#[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Debug, Hash)]
55pub struct Duration(pub crate::duration::Duration);
56
57#[cfg(feature = "time")]
58impl Duration {
59    // Since serde can't natively represent durations, we serialize a special
60    // newtype to indicate we want to rebuild the duration in the result, while
61    // remaining compatible with most other Serializer implementations.
62    const NAME: &str = "$__cel_private_Duration";
63    const STRUCT_NAME: &str = "Duration";
64    const SECS_FIELD: &str = "secs";
65    const NANOS_FIELD: &str = "nanos";
66}
67
68#[cfg(feature = "time")]
69impl From<Duration> for crate::duration::Duration {
70    fn from(value: Duration) -> Self {
71        value.0
72    }
73}
74
75#[cfg(feature = "time")]
76impl From<crate::duration::Duration> for Duration {
77    fn from(value: crate::duration::Duration) -> Self {
78        Self(value)
79    }
80}
81
82#[cfg(feature = "time")]
83impl ser::Serialize for Duration {
84    fn serialize<S>(&self, serializer: S) -> std::result::Result<S::Ok, S::Error>
85    where
86        S: ser::Serializer,
87    {
88        // A signed duration isn't natively representable by serde, so we
89        // serialize a `{ secs, nanos }` struct under a private marker newtype.
90        struct DurationProxy(crate::duration::Duration);
91        impl Serialize for DurationProxy {
92            fn serialize<S: ser::Serializer>(&self, serializer: S) -> std::result::Result<S::Ok, S::Error> {
93                let mut s = serializer.serialize_struct(Duration::STRUCT_NAME, 2)?;
94                s.serialize_field(Duration::SECS_FIELD, &self.0.serialized_secs())?;
95                s.serialize_field(Duration::NANOS_FIELD, &self.0.serialized_nanos())?;
96                s.end()
97            }
98        }
99        serializer.serialize_newtype_struct(Self::NAME, &DurationProxy(self.0))
100    }
101}
102
103/// A wrapper Timestamp type which allows conversion to [Value::Timestamp] for
104/// types using automatic conversion with [serde::Serialize].
105///
106/// # Examples
107///
108/// ```
109/// use bel::{Context, Timestamp, Program};
110/// use serde::Serialize;
111///
112/// #[derive(Serialize)]
113/// struct MyStruct {
114///     ts: Timestamp,
115/// }
116///
117/// let mut context = Context::default();
118///
119/// // MyStruct will be implicitly serialized into the CEL appropriate types
120/// context
121///     .add_variable(
122///         "foo",
123///         MyStruct {
124///             ts: "2025-01-01T00:00:00Z".parse::<time::DateTime>()
125///                 .unwrap()
126///                 .into(),
127///         },
128///     )
129///     .unwrap();
130///
131/// let program = Program::compile(r#"foo.ts == Timestamp("2025-01-01T00:00:00Z")"#).unwrap();
132/// let value = program.execute(&context).unwrap();
133/// assert_eq!(value, true.into());
134/// ```
135#[cfg(feature = "time")]
136#[derive(Clone, Copy, Default, PartialEq, Eq, PartialOrd, Ord, Debug, Hash)]
137pub struct Timestamp(pub DateTime);
138
139#[cfg(feature = "time")]
140impl Timestamp {
141    // Since serde can't natively represent timestamps, we serialize a special
142    // newtype to indicate we want to rebuild the timestamp in the result,
143    // while remaining compatible with most other Serializer implementations.
144    const NAME: &str = "$__cel_private_Timestamp";
145}
146
147#[cfg(feature = "time")]
148impl From<Timestamp> for DateTime {
149    fn from(value: Timestamp) -> Self {
150        value.0
151    }
152}
153
154#[cfg(feature = "time")]
155impl From<DateTime> for Timestamp {
156    fn from(value: DateTime) -> Self {
157        Self(value)
158    }
159}
160
161#[cfg(feature = "time")]
162impl ser::Serialize for Timestamp {
163    fn serialize<S>(&self, serializer: S) -> std::result::Result<S::Ok, S::Error>
164    where
165        S: ser::Serializer,
166    {
167        serializer.serialize_newtype_struct(Self::NAME, &self.0)
168    }
169}
170
171#[cfg(feature = "ip")]
172#[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Debug, Hash)]
173pub struct Ip(pub ipnetwork::IpNetwork);
174
175#[cfg(feature = "ip")]
176impl Ip {
177    // Since serde can't natively represent ips, we serialize a special
178    // newtype to indicate we want to rebuild the ip in the result,
179    // while remaining compatible with most other Serializer implementations.
180    const NAME: &str = "$__cel_private_Ip";
181}
182
183#[cfg(feature = "ip")]
184impl From<Ip> for ipnetwork::IpNetwork {
185    fn from(value: Ip) -> Self {
186        value.0
187    }
188}
189
190#[cfg(feature = "ip")]
191impl From<ipnetwork::IpNetwork> for Ip {
192    fn from(value: ipnetwork::IpNetwork) -> Self {
193        Self(value)
194    }
195}
196
197#[cfg(feature = "ip")]
198impl From<std::net::IpAddr> for Ip {
199    fn from(value: std::net::IpAddr) -> Self {
200        Self(ipnetwork::IpNetwork::from(value))
201    }
202}
203
204#[cfg(feature = "ip")]
205impl ser::Serialize for Ip {
206    fn serialize<S>(&self, serializer: S) -> std::result::Result<S::Ok, S::Error>
207    where
208        S: ser::Serializer,
209    {
210        serializer.serialize_newtype_struct(Self::NAME, &self.0)
211    }
212}
213
214#[derive(Error, Debug, PartialEq, Clone)]
215pub enum SerializationError {
216    InvalidKey(String),
217    SerdeError(String),
218}
219
220impl ser::Error for SerializationError {
221    fn custom<T>(msg: T) -> Self
222    where
223        T: std::fmt::Display,
224    {
225        SerializationError::SerdeError(msg.to_string())
226    }
227}
228
229impl Display for SerializationError {
230    fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
231        match self {
232            SerializationError::SerdeError(msg) => formatter.write_str(msg),
233            SerializationError::InvalidKey(msg) => formatter.write_str(msg),
234        }
235    }
236}
237
238pub type Result<T> = std::result::Result<T, SerializationError>;
239
240pub fn to_value<T>(value: T) -> Result<Value>
241where
242    T: Serialize,
243{
244    value.serialize(Serializer)
245}
246
247impl ser::Serializer for Serializer {
248    type Ok = Value;
249    type Error = SerializationError;
250
251    type SerializeSeq = SerializeVec;
252    type SerializeTuple = SerializeVec;
253    type SerializeTupleStruct = SerializeVec;
254    type SerializeTupleVariant = SerializeTupleVariant;
255    type SerializeMap = SerializeMap;
256    type SerializeStruct = SerializeMap;
257    type SerializeStructVariant = SerializeStructVariant;
258
259    // if the serializer is human_readable, then IpAddr is directly converted to str instead of serialize_newtype_variant
260    fn is_human_readable(&self) -> bool {
261        false
262    }
263
264    fn serialize_bool(self, v: bool) -> Result<Value> {
265        Ok(Value::Bool(v))
266    }
267
268    fn serialize_i8(self, v: i8) -> Result<Value> {
269        self.serialize_i64(i64::from(v))
270    }
271
272    fn serialize_i16(self, v: i16) -> Result<Value> {
273        self.serialize_i64(i64::from(v))
274    }
275
276    fn serialize_i32(self, v: i32) -> Result<Value> {
277        self.serialize_i64(i64::from(v))
278    }
279
280    fn serialize_i64(self, v: i64) -> Result<Value> {
281        Ok(Value::Int(v))
282    }
283
284    fn serialize_u8(self, v: u8) -> Result<Value> {
285        self.serialize_u64(u64::from(v))
286    }
287
288    fn serialize_u16(self, v: u16) -> Result<Value> {
289        self.serialize_u64(u64::from(v))
290    }
291
292    fn serialize_u32(self, v: u32) -> Result<Value> {
293        self.serialize_u64(u64::from(v))
294    }
295
296    fn serialize_u64(self, _v: u64) -> Result<Value> {
297        // Ok(Value::UInt(v))
298        Err(SerializationError::SerdeError(
299            "unsigned intergers are not supported".to_owned(),
300        ))
301    }
302
303    fn serialize_f32(self, v: f32) -> Result<Value> {
304        self.serialize_f64(f64::from(v))
305    }
306
307    fn serialize_f64(self, v: f64) -> Result<Value> {
308        Ok(Value::Float(v))
309    }
310
311    fn serialize_char(self, v: char) -> Result<Value> {
312        self.serialize_str(&v.to_string())
313    }
314
315    fn serialize_str(self, v: &str) -> Result<Value> {
316        Ok(Value::String(Arc::new(v.to_string())))
317    }
318
319    fn serialize_bytes(self, v: &[u8]) -> Result<Value> {
320        Ok(Value::Bytes(Arc::new(v.to_vec())))
321    }
322
323    fn serialize_none(self) -> Result<Value> {
324        self.serialize_unit()
325    }
326
327    fn serialize_some<T>(self, value: &T) -> Result<Value>
328    where
329        T: ?Sized + Serialize,
330    {
331        value.serialize(self)
332    }
333
334    fn serialize_unit(self) -> Result<Value> {
335        Ok(Value::Null)
336    }
337
338    fn serialize_unit_struct(self, _name: &'static str) -> Result<Value> {
339        self.serialize_unit()
340    }
341
342    fn serialize_unit_variant(self, _name: &'static str, _variant_index: u32, variant: &'static str) -> Result<Value> {
343        self.serialize_str(variant)
344    }
345
346    fn serialize_newtype_struct<T>(self, name: &'static str, value: &T) -> Result<Value>
347    where
348        T: ?Sized + Serialize,
349    {
350        match name {
351            #[cfg(feature = "time")]
352            Duration::NAME => value.serialize(TimeSerializer::Duration),
353            #[cfg(feature = "time")]
354            Timestamp::NAME => value.serialize(TimeSerializer::Timestamp),
355            #[cfg(feature = "ip")]
356            Ip::NAME => value.serialize(IpSerializer {}),
357            _ => value.serialize(self),
358        }
359    }
360
361    // `name` is only read by the `ip` conversion below.
362    #[cfg_attr(not(feature = "ip"), allow(unused_variables))]
363    fn serialize_newtype_variant<T>(
364        self,
365        name: &'static str,
366        _variant_index: u32,
367        variant: &'static str,
368        value: &T,
369    ) -> Result<Value>
370    where
371        T: ?Sized + Serialize,
372    {
373        #[cfg(feature = "ip")]
374        if name == "IpAddr" {
375            return value.serialize(IpSerializer {});
376        }
377
378        Ok(HashMap::from_iter([(variant.to_string(), value.serialize(Serializer)?)]).into())
379    }
380
381    fn serialize_seq(self, _len: Option<usize>) -> Result<Self::SerializeSeq> {
382        Ok(SerializeVec {
383            vec: Vec::with_capacity(_len.unwrap_or(0)),
384        })
385    }
386
387    fn serialize_tuple(self, len: usize) -> Result<Self::SerializeTuple> {
388        self.serialize_seq(Some(len))
389    }
390
391    fn serialize_tuple_struct(self, _name: &'static str, len: usize) -> Result<Self::SerializeTupleStruct> {
392        self.serialize_seq(Some(len))
393    }
394
395    fn serialize_tuple_variant(
396        self,
397        _name: &'static str,
398        _variant_index: u32,
399        variant: &'static str,
400        _len: usize,
401    ) -> Result<Self::SerializeTupleVariant> {
402        Ok(SerializeTupleVariant {
403            name: String::from(variant),
404            vec: Vec::with_capacity(_len),
405        })
406    }
407
408    fn serialize_map(self, _len: Option<usize>) -> Result<Self::SerializeMap> {
409        Ok(SerializeMap {
410            map: HashMap::new(),
411            next_key: None,
412        })
413    }
414
415    fn serialize_struct(self, _name: &'static str, len: usize) -> Result<Self::SerializeStruct> {
416        self.serialize_map(Some(len))
417    }
418
419    fn serialize_struct_variant(
420        self,
421        _name: &'static str,
422        _variant_index: u32,
423        variant: &'static str,
424        _len: usize,
425    ) -> Result<Self::SerializeStructVariant> {
426        Ok(SerializeStructVariant {
427            name: String::from(variant),
428            map: HashMap::new(),
429        })
430    }
431}
432
433pub struct SerializeVec {
434    vec: Vec<Value>,
435}
436
437pub struct SerializeTupleVariant {
438    name: String,
439    vec: Vec<Value>,
440}
441
442pub struct SerializeMap {
443    map: HashMap<Key, Value>,
444    next_key: Option<Key>,
445}
446
447pub struct SerializeStructVariant {
448    name: String,
449    map: HashMap<Key, Value>,
450}
451
452#[cfg(feature = "time")]
453#[derive(Debug, Default)]
454struct SerializeTimestamp {
455    secs: i64,
456    nanos: i32,
457}
458
459impl ser::SerializeSeq for SerializeVec {
460    type Ok = Value;
461    type Error = SerializationError;
462
463    fn serialize_element<T>(&mut self, value: &T) -> Result<()>
464    where
465        T: ?Sized + Serialize,
466    {
467        self.vec.push(to_value(value)?);
468        Ok(())
469    }
470
471    fn end(self) -> Result<Value> {
472        Ok(Value::List(Arc::new(self.vec)))
473    }
474}
475
476impl ser::SerializeTuple for SerializeVec {
477    type Ok = Value;
478    type Error = SerializationError;
479
480    fn serialize_element<T>(&mut self, value: &T) -> Result<()>
481    where
482        T: ?Sized + Serialize,
483    {
484        serde::ser::SerializeSeq::serialize_element(self, value)
485    }
486
487    fn end(self) -> Result<Value> {
488        serde::ser::SerializeSeq::end(self)
489    }
490}
491
492impl ser::SerializeTupleStruct for SerializeVec {
493    type Ok = Value;
494    type Error = SerializationError;
495
496    fn serialize_field<T>(&mut self, value: &T) -> Result<()>
497    where
498        T: ?Sized + Serialize,
499    {
500        serde::ser::SerializeSeq::serialize_element(self, value)
501    }
502
503    fn end(self) -> Result<Value> {
504        serde::ser::SerializeSeq::end(self)
505    }
506}
507
508impl ser::SerializeTupleVariant for SerializeTupleVariant {
509    type Ok = Value;
510    type Error = SerializationError;
511
512    fn serialize_field<T>(&mut self, value: &T) -> Result<()>
513    where
514        T: ?Sized + Serialize,
515    {
516        self.vec.push(to_value(value)?);
517        Ok(())
518    }
519
520    fn end(self) -> Result<Value> {
521        let map = HashMap::from_iter([(self.name, Arc::new(self.vec))]);
522        Ok(map.into())
523    }
524}
525
526impl ser::SerializeMap for SerializeMap {
527    type Ok = Value;
528    type Error = SerializationError;
529
530    fn serialize_key<T>(&mut self, key: &T) -> Result<()>
531    where
532        T: ?Sized + Serialize,
533    {
534        self.next_key = Some(key.serialize(KeySerializer)?);
535        Ok(())
536    }
537
538    fn serialize_value<T>(&mut self, value: &T) -> Result<()>
539    where
540        T: ?Sized + Serialize,
541    {
542        self.map.insert(
543            self.next_key.clone().ok_or_else(|| {
544                SerializationError::InvalidKey("serialize_value called before serialize_key".to_string())
545            })?,
546            value.serialize(Serializer)?,
547        );
548        Ok(())
549    }
550
551    fn end(self) -> Result<Value> {
552        Ok(self.map.into())
553    }
554}
555
556impl ser::SerializeStruct for SerializeMap {
557    type Ok = Value;
558    type Error = SerializationError;
559
560    fn serialize_field<T>(&mut self, key: &'static str, value: &T) -> Result<()>
561    where
562        T: ?Sized + Serialize,
563    {
564        serde::ser::SerializeMap::serialize_entry(self, key, value)
565    }
566
567    fn end(self) -> Result<Value> {
568        serde::ser::SerializeMap::end(self)
569    }
570}
571
572impl ser::SerializeStructVariant for SerializeStructVariant {
573    type Ok = Value;
574    type Error = SerializationError;
575
576    fn serialize_field<T>(&mut self, key: &'static str, value: &T) -> Result<()>
577    where
578        T: ?Sized + Serialize,
579    {
580        self.map.insert(key.serialize(KeySerializer)?, to_value(value)?);
581        Ok(())
582    }
583
584    fn end(self) -> Result<Value> {
585        let map: HashMap<String, Value> = HashMap::from_iter([(self.name, self.map.into())]);
586        Ok(map.into())
587    }
588}
589
590#[cfg(feature = "time")]
591impl ser::SerializeStruct for SerializeTimestamp {
592    type Ok = Value;
593    type Error = SerializationError;
594    fn serialize_field<T>(&mut self, key: &'static str, value: &T) -> std::result::Result<(), Self::Error>
595    where
596        T: ?Sized + Serialize,
597    {
598        match key {
599            Duration::SECS_FIELD => {
600                let Value::Int(val) = value.serialize(Serializer)? else {
601                    return Err(SerializationError::SerdeError(
602                        "invalid type of value in timestamp struct".to_owned(),
603                    ));
604                };
605                self.secs = val;
606                Ok(())
607            }
608            Duration::NANOS_FIELD => {
609                let Value::Int(val) = value.serialize(Serializer)? else {
610                    return Err(SerializationError::SerdeError(
611                        "invalid type of value in timestamp struct".to_owned(),
612                    ));
613                };
614                self.nanos = val.try_into().map_err(|_| {
615                    SerializationError::SerdeError("timestamp struct nanos field is invalid".to_owned())
616                })?;
617                Ok(())
618            }
619            _ => Err(SerializationError::SerdeError("invalid field in duration struct".to_owned())),
620        }
621    }
622
623    fn end(self) -> std::result::Result<Self::Ok, Self::Error> {
624        Ok(crate::duration::Duration::from_secs_nanos(self.secs, self.nanos).into())
625    }
626}
627
628impl ser::Serializer for KeySerializer {
629    type Ok = Key;
630    type Error = SerializationError;
631
632    type SerializeSeq = Impossible<Key, SerializationError>;
633    type SerializeTuple = Impossible<Key, SerializationError>;
634    type SerializeTupleStruct = Impossible<Key, SerializationError>;
635    type SerializeTupleVariant = Impossible<Key, SerializationError>;
636    type SerializeMap = Impossible<Key, SerializationError>;
637    type SerializeStruct = Impossible<Key, SerializationError>;
638    type SerializeStructVariant = Impossible<Key, SerializationError>;
639
640    fn serialize_bool(self, v: bool) -> Result<Key> {
641        Ok(Key::Bool(v))
642    }
643
644    fn serialize_i8(self, v: i8) -> Result<Key> {
645        self.serialize_i64(i64::from(v))
646    }
647
648    fn serialize_i16(self, v: i16) -> Result<Key> {
649        self.serialize_i64(i64::from(v))
650    }
651
652    fn serialize_i32(self, v: i32) -> Result<Key> {
653        self.serialize_i64(i64::from(v))
654    }
655
656    fn serialize_i64(self, v: i64) -> Result<Key> {
657        Ok(Key::Int(v))
658    }
659
660    fn serialize_u8(self, v: u8) -> Result<Key> {
661        self.serialize_u64(u64::from(v))
662    }
663
664    fn serialize_u16(self, v: u16) -> Result<Key> {
665        self.serialize_u64(u64::from(v))
666    }
667
668    fn serialize_u32(self, v: u32) -> Result<Key> {
669        self.serialize_u64(u64::from(v))
670    }
671
672    fn serialize_u64(self, _v: u64) -> Result<Key> {
673        // Ok(Key::Uint(v))
674        Err(SerializationError::SerdeError(
675            "unsigned intergers are not supported".to_owned(),
676        ))
677    }
678
679    fn serialize_f32(self, _v: f32) -> Result<Key> {
680        Err(SerializationError::InvalidKey("Float is not supported".to_string()))
681    }
682
683    fn serialize_f64(self, _v: f64) -> Result<Key> {
684        Err(SerializationError::InvalidKey("Float is not supported".to_string()))
685    }
686
687    fn serialize_char(self, v: char) -> Result<Key> {
688        self.serialize_str(&v.to_string())
689    }
690
691    fn serialize_str(self, v: &str) -> Result<Key> {
692        Ok(Key::String(Arc::new(v.to_string())))
693    }
694
695    fn serialize_bytes(self, _v: &[u8]) -> Result<Key> {
696        Err(SerializationError::InvalidKey("Bytes are not supported".to_string()))
697    }
698
699    fn serialize_none(self) -> Result<Key> {
700        Err(SerializationError::InvalidKey("None is not supported".to_string()))
701    }
702
703    fn serialize_some<T>(self, value: &T) -> Result<Key>
704    where
705        T: ?Sized + Serialize,
706    {
707        value.serialize(self)
708    }
709
710    fn serialize_unit(self) -> Result<Key> {
711        Err(SerializationError::InvalidKey("Null is not supported".to_string()))
712    }
713
714    fn serialize_unit_struct(self, _name: &'static str) -> Result<Key> {
715        Err(SerializationError::InvalidKey(
716            "Empty unit structs are not supported".to_string(),
717        ))
718    }
719
720    fn serialize_unit_variant(self, _name: &'static str, _variant_index: u32, variant: &'static str) -> Result<Key> {
721        Ok(Key::String(Arc::new(variant.to_string())))
722    }
723
724    fn serialize_newtype_struct<T>(self, _name: &'static str, value: &T) -> Result<Key>
725    where
726        T: ?Sized + Serialize,
727    {
728        print!("key: serialize_newtype_struct: {_name}");
729        value.serialize(KeySerializer)
730    }
731
732    fn serialize_newtype_variant<T>(
733        self,
734        _name: &'static str,
735        _variant_index: u32,
736        _variant: &'static str,
737        _value: &T,
738    ) -> Result<Key>
739    where
740        T: ?Sized + Serialize,
741    {
742        Err(SerializationError::InvalidKey("Newtype variant is not supported".to_string()))
743    }
744
745    fn serialize_seq(self, _len: Option<usize>) -> Result<Self::SerializeSeq> {
746        Err(SerializationError::InvalidKey("Sequences are not supported".to_string()))
747    }
748
749    fn serialize_tuple(self, _len: usize) -> Result<Self::SerializeTuple> {
750        Err(SerializationError::InvalidKey("Tuples are not supported".to_string()))
751    }
752
753    fn serialize_tuple_struct(self, _name: &'static str, _len: usize) -> Result<Self::SerializeTupleStruct> {
754        Err(SerializationError::InvalidKey("Structs are not supported".to_string()))
755    }
756
757    fn serialize_tuple_variant(
758        self,
759        _name: &'static str,
760        _variant_index: u32,
761        _variant: &'static str,
762        _len: usize,
763    ) -> Result<Self::SerializeTupleVariant> {
764        Err(SerializationError::InvalidKey("Tuple variants are not supported".to_string()))
765    }
766
767    fn serialize_map(self, _len: Option<usize>) -> Result<Self::SerializeMap> {
768        Err(SerializationError::InvalidKey("Map variants are not supported".to_string()))
769    }
770
771    fn serialize_struct(self, _name: &'static str, _len: usize) -> Result<Self::SerializeStruct> {
772        Err(SerializationError::InvalidKey("Structs are not supported".to_string()))
773    }
774
775    fn serialize_struct_variant(
776        self,
777        _name: &'static str,
778        _variant_index: u32,
779        _variant: &'static str,
780        _len: usize,
781    ) -> Result<Self::SerializeStructVariant> {
782        Err(SerializationError::InvalidKey("Struct variants are not supported".to_string()))
783    }
784}
785
786#[cfg(feature = "time")]
787#[derive(Debug)]
788enum TimeSerializer {
789    Duration,
790    Timestamp,
791}
792
793#[cfg(feature = "time")]
794impl ser::Serializer for TimeSerializer {
795    type Ok = Value;
796    type Error = SerializationError;
797
798    type SerializeStruct = SerializeTimestamp;
799
800    // Should never be used, so just reuse existing.
801    type SerializeSeq = SerializeVec;
802    type SerializeTuple = SerializeVec;
803    type SerializeTupleStruct = SerializeVec;
804    type SerializeTupleVariant = SerializeTupleVariant;
805    type SerializeMap = SerializeMap;
806    type SerializeStructVariant = SerializeStructVariant;
807
808    fn serialize_struct(self, name: &'static str, len: usize) -> Result<Self::SerializeStruct> {
809        if !matches!(self, Self::Duration { .. }) || name != Duration::STRUCT_NAME {
810            return Err(SerializationError::SerdeError(
811                "expected Duration struct with Duration marker newtype struct".to_owned(),
812            ));
813        }
814        if len != 2 {
815            return Err(SerializationError::SerdeError(
816                "expected Duration struct to have 2 fields".to_owned(),
817            ));
818        }
819        Ok(SerializeTimestamp::default())
820    }
821
822    fn serialize_str(self, v: &str) -> Result<Value> {
823        if !matches!(self, Self::Timestamp) {
824            return Err(SerializationError::SerdeError(
825                "expected Timestamp string with Timestamp marker newtype struct".to_owned(),
826            ));
827        }
828        Ok(v.parse::<DateTime>()
829            .map_err(|e| SerializationError::SerdeError(e.to_string()))?
830            .into())
831    }
832
833    fn serialize_bool(self, _v: bool) -> Result<Value> {
834        unreachable!()
835    }
836
837    fn serialize_i8(self, _v: i8) -> Result<Value> {
838        unreachable!()
839    }
840
841    fn serialize_i16(self, _v: i16) -> Result<Value> {
842        unreachable!()
843    }
844
845    fn serialize_i32(self, _v: i32) -> Result<Value> {
846        unreachable!()
847    }
848
849    fn serialize_i64(self, _v: i64) -> Result<Value> {
850        unreachable!()
851    }
852
853    fn serialize_u8(self, _v: u8) -> Result<Value> {
854        unreachable!()
855    }
856
857    fn serialize_u16(self, _v: u16) -> Result<Value> {
858        unreachable!()
859    }
860
861    fn serialize_u32(self, _v: u32) -> Result<Value> {
862        unreachable!()
863    }
864
865    fn serialize_u64(self, _v: u64) -> Result<Value> {
866        unreachable!()
867    }
868
869    fn serialize_f32(self, _v: f32) -> Result<Value> {
870        unreachable!()
871    }
872
873    fn serialize_f64(self, _v: f64) -> Result<Value> {
874        unreachable!()
875    }
876
877    fn serialize_char(self, _v: char) -> Result<Value> {
878        unreachable!()
879    }
880
881    fn serialize_bytes(self, _v: &[u8]) -> Result<Value> {
882        unreachable!()
883    }
884
885    fn serialize_none(self) -> Result<Value> {
886        unreachable!()
887    }
888
889    fn serialize_some<T>(self, _value: &T) -> Result<Value>
890    where
891        T: ?Sized + Serialize,
892    {
893        unreachable!()
894    }
895
896    fn serialize_unit(self) -> Result<Value> {
897        unreachable!()
898    }
899
900    fn serialize_unit_struct(self, _name: &'static str) -> Result<Value> {
901        unreachable!()
902    }
903
904    fn serialize_unit_variant(self, _name: &'static str, _variant_index: u32, _variant: &'static str) -> Result<Value> {
905        unreachable!()
906    }
907
908    fn serialize_newtype_struct<T>(self, _name: &'static str, _value: &T) -> Result<Value>
909    where
910        T: ?Sized + Serialize,
911    {
912        unreachable!()
913    }
914
915    fn serialize_newtype_variant<T>(
916        self,
917        _name: &'static str,
918        _variant_index: u32,
919        _variant: &'static str,
920        _value: &T,
921    ) -> Result<Value>
922    where
923        T: ?Sized + Serialize,
924    {
925        unreachable!()
926    }
927
928    fn serialize_seq(self, _len: Option<usize>) -> Result<Self::SerializeSeq> {
929        unreachable!()
930    }
931
932    fn serialize_tuple(self, _len: usize) -> Result<Self::SerializeTuple> {
933        unreachable!()
934    }
935
936    fn serialize_tuple_struct(self, _name: &'static str, _len: usize) -> Result<Self::SerializeTupleStruct> {
937        unreachable!()
938    }
939
940    fn serialize_tuple_variant(
941        self,
942        _name: &'static str,
943        _variant_index: u32,
944        _variant: &'static str,
945        _len: usize,
946    ) -> Result<Self::SerializeTupleVariant> {
947        unreachable!()
948    }
949
950    fn serialize_map(self, _len: Option<usize>) -> Result<Self::SerializeMap> {
951        unreachable!()
952    }
953
954    fn serialize_struct_variant(
955        self,
956        _name: &'static str,
957        _variant_index: u32,
958        _variant: &'static str,
959        _len: usize,
960    ) -> Result<Self::SerializeStructVariant> {
961        unreachable!()
962    }
963}
964
965#[cfg(feature = "ip")]
966#[derive(Debug)]
967struct IpSerializer {}
968
969#[cfg(feature = "ip")]
970impl ser::Serializer for IpSerializer {
971    type Ok = Value;
972    type Error = SerializationError;
973
974    type SerializeStruct = SerializeTimestamp;
975
976    // Should never be used, so just reuse existing.
977    type SerializeSeq = SerializeVec;
978    type SerializeTuple = SerializeVec;
979    type SerializeTupleStruct = SerializeVec;
980    type SerializeTupleVariant = SerializeTupleVariant;
981    type SerializeMap = SerializeMap;
982    type SerializeStructVariant = SerializeStructVariant;
983
984    fn serialize_struct(self, _name: &'static str, _len: usize) -> Result<Self::SerializeStruct> {
985        unreachable!()
986    }
987
988    fn serialize_str(self, v: &str) -> Result<Value> {
989        Ok(v.parse::<ipnetwork::IpNetwork>()
990            .map_err(|e| SerializationError::SerdeError(e.to_string()))?
991            .into())
992    }
993
994    fn serialize_bool(self, _v: bool) -> Result<Value> {
995        unreachable!()
996    }
997
998    fn serialize_i8(self, _v: i8) -> Result<Value> {
999        unreachable!()
1000    }
1001
1002    fn serialize_i16(self, _v: i16) -> Result<Value> {
1003        unreachable!()
1004    }
1005
1006    fn serialize_i32(self, _v: i32) -> Result<Value> {
1007        unreachable!()
1008    }
1009
1010    fn serialize_i64(self, _v: i64) -> Result<Value> {
1011        unreachable!()
1012    }
1013
1014    fn serialize_u8(self, _v: u8) -> Result<Value> {
1015        unreachable!()
1016    }
1017
1018    fn serialize_u16(self, _v: u16) -> Result<Value> {
1019        unreachable!()
1020    }
1021
1022    fn serialize_u32(self, _v: u32) -> Result<Value> {
1023        unreachable!()
1024    }
1025
1026    fn serialize_u64(self, _v: u64) -> Result<Value> {
1027        unreachable!()
1028    }
1029
1030    fn serialize_f32(self, _v: f32) -> Result<Value> {
1031        unreachable!()
1032    }
1033
1034    fn serialize_f64(self, _v: f64) -> Result<Value> {
1035        unreachable!()
1036    }
1037
1038    fn serialize_char(self, _v: char) -> Result<Value> {
1039        unreachable!()
1040    }
1041
1042    fn serialize_bytes(self, _v: &[u8]) -> Result<Value> {
1043        unreachable!()
1044    }
1045
1046    fn serialize_none(self) -> Result<Value> {
1047        unreachable!()
1048    }
1049
1050    fn serialize_some<T>(self, _value: &T) -> Result<Value>
1051    where
1052        T: ?Sized + Serialize,
1053    {
1054        unreachable!()
1055    }
1056
1057    fn serialize_unit(self) -> Result<Value> {
1058        unreachable!()
1059    }
1060
1061    fn serialize_unit_struct(self, _name: &'static str) -> Result<Value> {
1062        unreachable!()
1063    }
1064
1065    fn serialize_unit_variant(self, _name: &'static str, _variant_index: u32, _variant: &'static str) -> Result<Value> {
1066        unreachable!()
1067    }
1068
1069    fn serialize_newtype_struct<T>(self, _name: &'static str, _value: &T) -> Result<Value>
1070    where
1071        T: ?Sized + Serialize,
1072    {
1073        unreachable!()
1074    }
1075
1076    fn serialize_newtype_variant<T>(
1077        self,
1078        _name: &'static str,
1079        _variant_index: u32,
1080        _variant: &'static str,
1081        _value: &T,
1082    ) -> Result<Value>
1083    where
1084        T: ?Sized + Serialize,
1085    {
1086        unreachable!()
1087    }
1088
1089    fn serialize_seq(self, _len: Option<usize>) -> Result<Self::SerializeSeq> {
1090        unreachable!()
1091    }
1092
1093    fn serialize_tuple(self, _len: usize) -> Result<Self::SerializeTuple> {
1094        unreachable!()
1095    }
1096
1097    fn serialize_tuple_struct(self, _name: &'static str, _len: usize) -> Result<Self::SerializeTupleStruct> {
1098        unreachable!()
1099    }
1100
1101    fn serialize_tuple_variant(
1102        self,
1103        _name: &'static str,
1104        _variant_index: u32,
1105        _variant: &'static str,
1106        _len: usize,
1107    ) -> Result<Self::SerializeTupleVariant> {
1108        unreachable!()
1109    }
1110
1111    fn serialize_map(self, _len: Option<usize>) -> Result<Self::SerializeMap> {
1112        unreachable!()
1113    }
1114
1115    fn serialize_struct_variant(
1116        self,
1117        _name: &'static str,
1118        _variant_index: u32,
1119        _variant: &'static str,
1120        _len: usize,
1121    ) -> Result<Self::SerializeStructVariant> {
1122        unreachable!()
1123    }
1124}
1125
1126#[cfg(test)]
1127mod tests {
1128    use std::{collections::HashMap, iter::FromIterator, sync::Arc};
1129
1130    use serde::Serialize;
1131    use serde_bytes::Bytes;
1132    #[cfg(feature = "time")]
1133    use time::DateTime;
1134
1135    #[cfg(feature = "time")]
1136    use super::{Duration, Timestamp};
1137    use crate::{Context, Program, Value, objects::Key, to_value};
1138
1139    macro_rules! primitive_test {
1140        ($functionName:ident, $strValue: literal, $value: expr) => {
1141            #[test]
1142            fn $functionName() {
1143                let program = Program::compile($strValue).unwrap();
1144                let result = program.execute(&Context::default());
1145                assert_eq!(Value::from($value), result.unwrap());
1146            }
1147        };
1148    }
1149
1150    // primitive_test!(test_u64_zero, "0u", 0_u64);
1151    primitive_test!(test_i64_zero, "0", 0_i64);
1152    primitive_test!(test_f64_zero, "0.0", 0_f64);
1153    //primitive_test!(test_f64_zero, "0.", 0_f64); this test fails
1154    primitive_test!(test_bool_false, "false", false);
1155    primitive_test!(test_bool_true, "true", true);
1156    primitive_test!(test_string_empty, "\"\"", "");
1157    primitive_test!(test_string_non_empty, "\"test\"", "test");
1158    primitive_test!(test_byte_ones, r#"b"\001\001""#, vec!(1_u8, 1_u8));
1159    // primitive_test!(test_triple_double_quoted_string, #"r"""""""#, "");
1160    // primitive_test!(test_triple_single_quoted_string, "r''''''", "");
1161    primitive_test!(test_utf8_character_as_bytes, "b'ΓΏ'", vec!(195_u8, 191_u8));
1162
1163    #[test]
1164    fn test_json_data_conversion() {
1165        #[derive(Serialize)]
1166        struct TestPrimitives {
1167            bool: bool,
1168            // u8: u8,
1169            // u16: u16,
1170            // u32: u32,
1171            // u64: u64,
1172            int8: i8,
1173            int16: i16,
1174            int32: i32,
1175            int64: i64,
1176            f32: f32,
1177            f64: f64,
1178            char: char,
1179            string: String,
1180            bytes: &'static Bytes,
1181        }
1182
1183        let test = TestPrimitives {
1184            bool: true,
1185            int8: 8_i8,
1186            int16: 16_i16,
1187            int32: 32_i32,
1188            int64: 64_i64,
1189            // u8: 8_u8,
1190            // u16: 16_u16,
1191            // u32: 32_u32,
1192            // u64: 64_u64,
1193            f32: 0.32_f32,
1194            f64: 0.64_f64,
1195            char: 'a',
1196            string: "string".to_string(),
1197            bytes: Bytes::new(&[1_u8, 1_u8, 1_u8, 1_u8]),
1198        };
1199
1200        let serialized = to_value(test).unwrap();
1201        let expected: Value = HashMap::from_iter([
1202            (Key::String(Arc::new("bool".to_string())), Value::Bool(true)),
1203            (Key::String(Arc::new("int8".to_string())), Value::Int(8)),
1204            (Key::String(Arc::new("int16".to_string())), Value::Int(16)),
1205            (Key::String(Arc::new("int32".to_string())), Value::Int(32)),
1206            (Key::String(Arc::new("int64".to_string())), Value::Int(64)),
1207            // (Key::String(Arc::new("u8".to_string())), Value::UInt(8)),
1208            // (Key::String(Arc::new("u16".to_string())), Value::UInt(16)),
1209            // (Key::String(Arc::new("u32".to_string())), Value::UInt(32)),
1210            // (Key::String(Arc::new("u64".to_string())), Value::UInt(64)),
1211            (Key::String(Arc::new("f32".to_string())), Value::Float(f64::from(0.32_f32))),
1212            (Key::String(Arc::new("f64".to_string())), Value::Float(0.64)),
1213            (
1214                Key::String(Arc::new("char".to_string())),
1215                Value::String(Arc::new("a".to_string())),
1216            ),
1217            (
1218                Key::String(Arc::new("string".to_string())),
1219                Value::String(Arc::new("string".to_string())),
1220            ),
1221            (
1222                Key::String(Arc::new("bytes".to_string())),
1223                Value::Bytes(Arc::new(vec![1, 1, 1, 1])),
1224            ),
1225        ])
1226        .into();
1227
1228        // Test with CEL because iterator is not implemented for Value::Map
1229        let program = Program::compile("expected.all(key, serialized[key] == expected[key])").unwrap();
1230        let mut context = Context::default();
1231        context.add_variable("expected", expected).unwrap();
1232        context.add_variable("serialized", serialized).unwrap();
1233        let value = program.execute(&context).unwrap();
1234        assert_eq!(value, true.into())
1235    }
1236
1237    #[derive(Serialize)]
1238    enum TestCompoundTypes {
1239        Unit,
1240        Newtype(i32),
1241        Wrapped(Option<i8>),
1242        Tuple(i32, i32),
1243        Struct {
1244            a: i32,
1245            nested: HashMap<bool, HashMap<String, Vec<String>>>,
1246        },
1247        Map(HashMap<String, &'static Bytes>),
1248    }
1249    #[test]
1250    fn test_unit() {
1251        let unit = to_value(TestCompoundTypes::Unit).unwrap();
1252        let expected: Value = "Unit".into();
1253        let program = Program::compile("test == expected").unwrap();
1254        let mut context = Context::default();
1255        context.add_variable("expected", expected).unwrap();
1256        context.add_variable("test", unit).unwrap();
1257        let value = program.execute(&context).unwrap();
1258        assert_eq!(value, true.into())
1259    }
1260    #[test]
1261    fn test_newtype() {
1262        let newtype = to_value(TestCompoundTypes::Newtype(32)).unwrap();
1263        let expected: Value = HashMap::from([("Newtype", Value::Int(32))]).into();
1264        let program = Program::compile("test == expected").unwrap();
1265        let mut context = Context::default();
1266        context.add_variable("expected", expected).unwrap();
1267        context.add_variable("test", newtype).unwrap();
1268        let value = program.execute(&context).unwrap();
1269        assert_eq!(value, true.into())
1270    }
1271    #[test]
1272    fn test_options() {
1273        // Test Option serialization
1274        let wrapped = to_value(TestCompoundTypes::Wrapped(None)).unwrap();
1275        let expected: Value = HashMap::from([("Wrapped", Value::Null)]).into();
1276        let program = Program::compile("test == expected").unwrap();
1277        let mut context = Context::default();
1278        context.add_variable("expected", expected).unwrap();
1279        context.add_variable("test", wrapped).unwrap();
1280        let value = program.execute(&context).unwrap();
1281        assert_eq!(value, true.into());
1282
1283        let wrapped = to_value(TestCompoundTypes::Wrapped(Some(8))).unwrap();
1284        let expected: Value = HashMap::from([("Wrapped", Value::Int(8))]).into();
1285        let program = Program::compile("test == expected").unwrap();
1286        let mut context = Context::default();
1287        context.add_variable("expected", expected).unwrap();
1288        context.add_variable("test", wrapped).unwrap();
1289        let value = program.execute(&context).unwrap();
1290        assert_eq!(value, true.into())
1291    }
1292
1293    #[test]
1294    fn test_tuples() {
1295        // Test Tuple serialization
1296        let tuple = to_value(TestCompoundTypes::Tuple(12, 16)).unwrap();
1297        let expected: Value =
1298            HashMap::from([("Tuple", Value::List(Arc::new(vec![12_i64.into(), 16_i64.into()])))]).into();
1299        let program = Program::compile("test == expected").unwrap();
1300        let mut context = Context::default();
1301        context.add_variable("expected", expected).unwrap();
1302        context.add_variable("test", tuple).unwrap();
1303        let value = program.execute(&context).unwrap();
1304        assert_eq!(value, true.into())
1305    }
1306
1307    #[test]
1308    fn test_structs() {
1309        // Test Struct serialization
1310        let test_struct = TestCompoundTypes::Struct {
1311            a: 32_i32,
1312            nested: HashMap::from_iter([(
1313                true,
1314                HashMap::from_iter([("Test".to_string(), vec!["a".to_string(), "b".to_string(), "c".to_string()])]),
1315            )]),
1316        };
1317        let expected: Value = HashMap::<Key, Value>::from([(
1318            "Struct".into(),
1319            HashMap::<Key, Value>::from_iter([
1320                ("a".into(), 32_i32.into()),
1321                (
1322                    "nested".into(),
1323                    HashMap::<Key, Value>::from_iter([(
1324                        true.into(),
1325                        HashMap::<Key, Value>::from_iter([(
1326                            "Test".into(),
1327                            vec!["a".to_string(), "b".to_string(), "c".to_string()].into(),
1328                        )])
1329                        .into(),
1330                    )])
1331                    .into(),
1332                ),
1333            ])
1334            .into(),
1335        )])
1336        .into();
1337        let program = Program::compile("expected.all(key, test[key] == expected[key])").unwrap();
1338        let mut context = Context::default();
1339        context.add_variable("expected", expected).unwrap();
1340        context.add_variable("test", test_struct).unwrap();
1341        let value = program.execute(&context).unwrap();
1342        assert_eq!(value, true.into());
1343    }
1344
1345    #[test]
1346    fn test_maps() {
1347        // Test Map serialization
1348        let map = to_value(TestCompoundTypes::Map(HashMap::<String, &'static Bytes>::from_iter([(
1349            "Test".to_string(),
1350            Bytes::new(&[0_u8, 0_u8, 0_u8, 0_u8]),
1351        )])))
1352        .unwrap();
1353        let expected: Value = HashMap::from([(
1354            "Map",
1355            HashMap::<Key, Value>::from_iter([("Test".into(), Value::Bytes(Arc::new(vec![0_u8, 0_u8, 0_u8, 0_u8])))]),
1356        )])
1357        .into();
1358        assert_eq!(map, expected)
1359    }
1360
1361    #[cfg(feature = "time")]
1362    #[derive(Serialize)]
1363    struct TestTimeTypes {
1364        dur: Duration,
1365        ts: Timestamp,
1366    }
1367
1368    #[cfg(feature = "time")]
1369    #[test]
1370    fn test_time_types() {
1371        fn dt(s: &str) -> DateTime {
1372            s.parse::<DateTime>().unwrap()
1373        }
1374
1375        let tests = to_value([
1376            TestTimeTypes {
1377                dur: crate::duration::Duration::milliseconds(1527).into(),
1378                ts: dt("1996-12-19T16:39:57-08:00").into(),
1379            },
1380            // Signed duration math and timestamps from BCE.
1381            TestTimeTypes {
1382                dur: crate::duration::Duration::milliseconds(-1527).into(),
1383                ts: dt("-0001-12-01T00:00:00-08:00").into(),
1384            },
1385            TestTimeTypes {
1386                dur: (crate::duration::Duration::seconds(1) - crate::duration::Duration::nanoseconds(1000000001))
1387                    .into(),
1388                ts: dt("0001-12-01T00:00:00+08:00").into(),
1389            },
1390            TestTimeTypes {
1391                dur: (crate::duration::Duration::seconds(-1) + crate::duration::Duration::nanoseconds(1000000001))
1392                    .into(),
1393                ts: dt("1996-12-19T16:39:57-08:00").into(),
1394            },
1395        ])
1396        .unwrap();
1397        let expected: Value = vec![
1398            Value::Map(
1399                HashMap::<_, Value>::from([
1400                    ("dur", crate::duration::Duration::milliseconds(1527).into()),
1401                    ("ts", dt("1996-12-19T16:39:57-08:00").into()),
1402                ])
1403                .into(),
1404            ),
1405            Value::Map(
1406                HashMap::<_, Value>::from([
1407                    ("dur", crate::duration::Duration::nanoseconds(-1527000000).into()),
1408                    ("ts", dt("-0001-12-01T00:00:00-08:00").into()),
1409                ])
1410                .into(),
1411            ),
1412            Value::Map(
1413                HashMap::<_, Value>::from([
1414                    ("dur", crate::duration::Duration::nanoseconds(-1).into()),
1415                    ("ts", dt("0001-12-01T00:00:00+08:00").into()),
1416                ])
1417                .into(),
1418            ),
1419            Value::Map(
1420                HashMap::<_, Value>::from([
1421                    ("dur", crate::duration::Duration::nanoseconds(1).into()),
1422                    ("ts", dt("1996-12-19T16:39:57-08:00").into()),
1423                ])
1424                .into(),
1425            ),
1426        ]
1427        .into();
1428        assert_eq!(tests, expected);
1429
1430        let program = Program::compile("test == expected").unwrap();
1431        let mut context = Context::default();
1432        context.add_variable("expected", expected).unwrap();
1433        context.add_variable("test", tests).unwrap();
1434        let value = program.execute(&context).unwrap();
1435        assert_eq!(value, true.into());
1436    }
1437
1438    #[cfg(feature = "ip")]
1439    #[test]
1440    fn test_ip_types() {
1441        use std::net::{IpAddr, Ipv4Addr};
1442
1443        use crate::ser::Ip;
1444
1445        #[derive(Serialize)]
1446        struct IpType {
1447            ip_addr: IpAddr,
1448            ip: Ip,
1449        }
1450
1451        let tests = to_value([IpType {
1452            ip_addr: IpAddr::V4(Ipv4Addr::new(127, 0, 0, 1)).into(),
1453            ip: ipnetwork::IpNetwork::from(IpAddr::V4(Ipv4Addr::new(127, 0, 0, 2))).into(),
1454        }])
1455        .unwrap();
1456        let expected: Value = vec![Value::Map(
1457            HashMap::<_, Value>::from([
1458                ("ip_addr", Value::from(IpAddr::V4(Ipv4Addr::new(127, 0, 0, 1)))),
1459                ("ip", Value::from(IpAddr::V4(Ipv4Addr::new(127, 0, 0, 2)))),
1460            ])
1461            .into(),
1462        )]
1463        .into();
1464        assert_eq!(tests, expected);
1465
1466        let program = Program::compile("test == expected").unwrap();
1467        let mut context = Context::default();
1468        context.add_variable("expected", expected).unwrap();
1469        context.add_variable("test", tests).unwrap();
1470        let value = program.execute(&context).unwrap();
1471        assert_eq!(value, true.into());
1472    }
1473
1474    #[cfg(feature = "time")]
1475    #[cfg(feature = "json")]
1476    #[test]
1477    fn test_time_json() {
1478        fn dt(s: &str) -> DateTime {
1479            s.parse::<DateTime>().unwrap()
1480        }
1481
1482        // Test that Durations and Timestamps serialize correctly with
1483        // serde_json.
1484        let tests = [
1485            TestTimeTypes {
1486                dur: crate::duration::Duration::milliseconds(1527).into(),
1487                ts: dt("1996-12-19T16:39:57-08:00").into(),
1488            },
1489            TestTimeTypes {
1490                dur: crate::duration::Duration::milliseconds(-1527).into(),
1491                ts: dt("-0001-12-01T00:00:00-08:00").into(),
1492            },
1493            TestTimeTypes {
1494                dur: (crate::duration::Duration::seconds(1) - crate::duration::Duration::nanoseconds(1000000001))
1495                    .into(),
1496                ts: dt("0001-12-01T00:00:00+08:00").into(),
1497            },
1498            TestTimeTypes {
1499                dur: (crate::duration::Duration::seconds(-1) + crate::duration::Duration::nanoseconds(1000000001))
1500                    .into(),
1501                ts: dt("1996-12-19T16:39:57-08:00").into(),
1502            },
1503        ];
1504
1505        let expect = "[\
1506{\"dur\":{\"secs\":1,\"nanos\":527000000},\"ts\":\"1996-12-19T16:39:57-08:00\"},\
1507{\"dur\":{\"secs\":-1,\"nanos\":-527000000},\"ts\":\"-0001-12-01T00:00:00-08:00\"},\
1508{\"dur\":{\"secs\":0,\"nanos\":-1},\"ts\":\"0001-12-01T00:00:00+08:00\"},\
1509{\"dur\":{\"secs\":0,\"nanos\":1},\"ts\":\"1996-12-19T16:39:57-08:00\"}\
1510]";
1511        let actual = serde_json::to_string(&tests).unwrap();
1512        assert_eq!(actual, expect);
1513    }
1514}