cu29_value/
lib.rs

1#![doc(html_root_url = "https://docs.rs/serde-value/0.7.0/")]
2#![cfg_attr(not(feature = "std"), no_std)]
3#[cfg(not(feature = "std"))]
4extern crate alloc;
5
6#[cfg(not(feature = "std"))]
7mod imp {
8    pub use alloc::boxed::Box;
9    pub use alloc::collections::BTreeMap;
10    pub use alloc::string::String;
11    pub use alloc::vec::Vec;
12}
13#[cfg(feature = "std")]
14mod imp {
15    pub use std::collections::BTreeMap;
16}
17
18use imp::*;
19
20use core::cmp::Ordering;
21use core::fmt::{Display, Formatter};
22use core::hash::{Hash, Hasher};
23use cu29_clock::{CuDuration, CuTime};
24use ordered_float::OrderedFloat;
25use serde::Deserialize;
26
27mod bdec;
28mod benc;
29mod de;
30mod ser;
31
32pub use de::*;
33pub use ser::*;
34
35#[derive(Clone, Debug)]
36pub enum Value {
37    Bool(bool),
38
39    U8(u8),
40    U16(u16),
41    U32(u32),
42    U64(u64),
43
44    I8(i8),
45    I16(i16),
46    I32(i32),
47    I64(i64),
48
49    F32(f32),
50    F64(f64),
51
52    Char(char),
53    String(String),
54    Unit,
55    Option(Option<Box<Value>>),
56    Newtype(Box<Value>),
57    Seq(Vec<Value>),
58    Map(BTreeMap<Value, Value>),
59    Bytes(Vec<u8>),
60
61    CuTime(CuTime),
62}
63
64impl Display for Value {
65    fn fmt(&self, f: &mut Formatter<'_>) -> core::fmt::Result {
66        match self {
67            Value::Bool(v) => write!(f, "{v}"),
68            Value::U8(v) => write!(f, "{v}"),
69            Value::U16(v) => write!(f, "{v}"),
70            Value::U32(v) => write!(f, "{v}"),
71            Value::U64(v) => write!(f, "{v}"),
72            Value::I8(v) => write!(f, "{v}"),
73            Value::I16(v) => write!(f, "{v}"),
74            Value::I32(v) => write!(f, "{v}"),
75            Value::I64(v) => write!(f, "{v}"),
76            Value::F32(v) => write!(f, "{v}"),
77            Value::F64(v) => write!(f, "{v}"),
78            Value::Char(v) => write!(f, "{v}"),
79            Value::String(v) => write!(f, "{v}"),
80            Value::Unit => write!(f, "()"),
81            Value::Option(v) => match v {
82                Some(v) => write!(f, "Some({v})"),
83                None => write!(f, "None"),
84            },
85            Value::Newtype(v) => write!(f, "{v}"),
86            Value::Seq(v) => {
87                write!(f, "[")?;
88                for (i, v) in v.iter().enumerate() {
89                    if i > 0 {
90                        write!(f, ", ")?;
91                    }
92                    write!(f, "{v}")?;
93                }
94                write!(f, "]")
95            }
96            Value::Map(v) => {
97                write!(f, "{{")?;
98                for (i, (k, v)) in v.iter().enumerate() {
99                    if i > 0 {
100                        write!(f, ", ")?;
101                    }
102                    write!(f, "{k}: {v}")?;
103                }
104                write!(f, "}}")
105            }
106            Value::Bytes(v) => {
107                write!(f, "[")?;
108                for (i, b) in v.iter().enumerate() {
109                    if i > 0 {
110                        write!(f, " ")?;
111                    }
112                    write!(f, "{b:02x}")?;
113                }
114                write!(f, "]")
115            }
116            Value::CuTime(v) => write!(f, "{v}"),
117        }
118    }
119}
120
121impl Hash for Value {
122    fn hash<H>(&self, hasher: &mut H)
123    where
124        H: Hasher,
125    {
126        self.discriminant().hash(hasher);
127        match *self {
128            Value::Bool(v) => v.hash(hasher),
129            Value::U8(v) => v.hash(hasher),
130            Value::U16(v) => v.hash(hasher),
131            Value::U32(v) => v.hash(hasher),
132            Value::U64(v) => v.hash(hasher),
133            Value::I8(v) => v.hash(hasher),
134            Value::I16(v) => v.hash(hasher),
135            Value::I32(v) => v.hash(hasher),
136            Value::I64(v) => v.hash(hasher),
137            Value::F32(v) => OrderedFloat(v).hash(hasher),
138            Value::F64(v) => OrderedFloat(v).hash(hasher),
139            Value::Char(v) => v.hash(hasher),
140            Value::String(ref v) => v.hash(hasher),
141            Value::Unit => 0_u8.hash(hasher),
142            Value::Option(ref v) => v.hash(hasher),
143            Value::Newtype(ref v) => v.hash(hasher),
144            Value::Seq(ref v) => v.hash(hasher),
145            Value::Map(ref v) => v.hash(hasher),
146            Value::Bytes(ref v) => v.hash(hasher),
147            Value::CuTime(v) => {
148                let CuDuration(nanos) = v;
149                nanos.hash(hasher)
150            }
151        }
152    }
153}
154
155impl PartialEq for Value {
156    fn eq(&self, rhs: &Self) -> bool {
157        match (self, rhs) {
158            (&Value::Bool(v0), &Value::Bool(v1)) if v0 == v1 => true,
159            (&Value::U8(v0), &Value::U8(v1)) if v0 == v1 => true,
160            (&Value::U16(v0), &Value::U16(v1)) if v0 == v1 => true,
161            (&Value::U32(v0), &Value::U32(v1)) if v0 == v1 => true,
162            (&Value::U64(v0), &Value::U64(v1)) if v0 == v1 => true,
163            (&Value::I8(v0), &Value::I8(v1)) if v0 == v1 => true,
164            (&Value::I16(v0), &Value::I16(v1)) if v0 == v1 => true,
165            (&Value::I32(v0), &Value::I32(v1)) if v0 == v1 => true,
166            (&Value::I64(v0), &Value::I64(v1)) if v0 == v1 => true,
167            (&Value::F32(v0), &Value::F32(v1)) if OrderedFloat(v0) == OrderedFloat(v1) => true,
168            (&Value::F64(v0), &Value::F64(v1)) if OrderedFloat(v0) == OrderedFloat(v1) => true,
169            (&Value::Char(v0), &Value::Char(v1)) if v0 == v1 => true,
170            (Value::String(v0), Value::String(v1)) if v0 == v1 => true,
171            (&Value::Unit, &Value::Unit) => true,
172            (Value::Option(v0), Value::Option(v1)) if v0 == v1 => true,
173            (Value::Newtype(v0), Value::Newtype(v1)) if v0 == v1 => true,
174            (Value::Seq(v0), Value::Seq(v1)) if v0 == v1 => true,
175            (Value::Map(v0), Value::Map(v1)) if v0 == v1 => true,
176            (Value::Bytes(v0), Value::Bytes(v1)) if v0 == v1 => true,
177            (&Value::CuTime(v0), &Value::CuTime(v1)) if v0 == v1 => true,
178            _ => false,
179        }
180    }
181}
182
183impl Ord for Value {
184    fn cmp(&self, rhs: &Self) -> Ordering {
185        match (self, rhs) {
186            (&Value::Bool(v0), Value::Bool(v1)) => v0.cmp(v1),
187            (&Value::U8(v0), Value::U8(v1)) => v0.cmp(v1),
188            (&Value::U16(v0), Value::U16(v1)) => v0.cmp(v1),
189            (&Value::U32(v0), Value::U32(v1)) => v0.cmp(v1),
190            (&Value::U64(v0), Value::U64(v1)) => v0.cmp(v1),
191            (&Value::I8(v0), Value::I8(v1)) => v0.cmp(v1),
192            (&Value::I16(v0), Value::I16(v1)) => v0.cmp(v1),
193            (&Value::I32(v0), Value::I32(v1)) => v0.cmp(v1),
194            (&Value::I64(v0), Value::I64(v1)) => v0.cmp(v1),
195            (&Value::F32(v0), &Value::F32(v1)) => OrderedFloat(v0).cmp(&OrderedFloat(v1)),
196            (&Value::F64(v0), &Value::F64(v1)) => OrderedFloat(v0).cmp(&OrderedFloat(v1)),
197            (&Value::Char(v0), Value::Char(v1)) => v0.cmp(v1),
198            (Value::String(v0), Value::String(v1)) => v0.cmp(v1),
199            (&Value::Unit, &Value::Unit) => Ordering::Equal,
200            (Value::Option(v0), Value::Option(v1)) => v0.cmp(v1),
201            (Value::Newtype(v0), Value::Newtype(v1)) => v0.cmp(v1),
202            (Value::Seq(v0), Value::Seq(v1)) => v0.cmp(v1),
203            (Value::Map(v0), Value::Map(v1)) => v0.cmp(v1),
204            (Value::Bytes(v0), Value::Bytes(v1)) => v0.cmp(v1),
205            (&Value::CuTime(v0), &Value::CuTime(v1)) => v0.cmp(&v1),
206            (v0, v1) => v0.discriminant().cmp(&v1.discriminant()),
207        }
208    }
209}
210
211impl Value {
212    fn discriminant(&self) -> usize {
213        match *self {
214            Value::Bool(..) => 0,
215            Value::U8(..) => 1,
216            Value::U16(..) => 2,
217            Value::U32(..) => 3,
218            Value::U64(..) => 4,
219            Value::I8(..) => 5,
220            Value::I16(..) => 6,
221            Value::I32(..) => 7,
222            Value::I64(..) => 8,
223            Value::F32(..) => 9,
224            Value::F64(..) => 10,
225            Value::Char(..) => 11,
226            Value::String(..) => 12,
227            Value::Unit => 13,
228            Value::Option(..) => 14,
229            Value::Newtype(..) => 15,
230            Value::Seq(..) => 16,
231            Value::Map(..) => 17,
232            Value::Bytes(..) => 18,
233            Value::CuTime(..) => 32,
234        }
235    }
236
237    fn unexpected(&self) -> serde::de::Unexpected<'_> {
238        match *self {
239            Value::Bool(b) => serde::de::Unexpected::Bool(b),
240            Value::U8(n) => serde::de::Unexpected::Unsigned(n as u64),
241            Value::U16(n) => serde::de::Unexpected::Unsigned(n as u64),
242            Value::U32(n) => serde::de::Unexpected::Unsigned(n as u64),
243            Value::U64(n) => serde::de::Unexpected::Unsigned(n),
244            Value::I8(n) => serde::de::Unexpected::Signed(n as i64),
245            Value::I16(n) => serde::de::Unexpected::Signed(n as i64),
246            Value::I32(n) => serde::de::Unexpected::Signed(n as i64),
247            Value::I64(n) => serde::de::Unexpected::Signed(n),
248            Value::F32(n) => serde::de::Unexpected::Float(n as f64),
249            Value::F64(n) => serde::de::Unexpected::Float(n),
250            Value::Char(c) => serde::de::Unexpected::Char(c),
251            Value::String(ref s) => serde::de::Unexpected::Str(s),
252            Value::Unit => serde::de::Unexpected::Unit,
253            Value::Option(_) => serde::de::Unexpected::Option,
254            Value::Newtype(_) => serde::de::Unexpected::NewtypeStruct,
255            Value::Seq(_) => serde::de::Unexpected::Seq,
256            Value::Map(_) => serde::de::Unexpected::Map,
257            Value::Bytes(ref b) => serde::de::Unexpected::Bytes(b),
258            Value::CuTime(n) => {
259                let CuDuration(nanos) = n;
260                serde::de::Unexpected::Unsigned(nanos)
261            }
262        }
263    }
264
265    pub fn deserialize_into<'de, T: Deserialize<'de>>(self) -> Result<T, DeserializerError> {
266        T::deserialize(self)
267    }
268}
269
270impl Eq for Value {}
271impl PartialOrd for Value {
272    fn partial_cmp(&self, rhs: &Self) -> Option<Ordering> {
273        Some(self.cmp(rhs))
274    }
275}
276
277#[cfg(test)]
278mod tests {
279    use super::*;
280    #[cfg(not(feature = "std"))]
281    use alloc::borrow::ToOwned;
282    #[cfg(not(feature = "std"))]
283    use alloc::string::ToString;
284    #[cfg(not(feature = "std"))]
285    use alloc::vec;
286
287    use bincode::{config::standard, decode_from_slice, encode_to_vec};
288    use core::time::Duration;
289    use cu29_clock::{CuDuration, CuTime, RobotClock};
290    use serde_derive::{Deserialize, Serialize};
291
292    #[test]
293    fn de_smoke_test() {
294        // some convoluted Value
295        let value = Value::Option(Some(Box::new(Value::Seq(vec![
296            Value::U16(8),
297            Value::Char('a'),
298            Value::F32(1.0),
299            Value::String("hello".into()),
300            Value::Map(
301                vec![
302                    (Value::Bool(false), Value::Unit),
303                    (
304                        Value::Bool(true),
305                        Value::Newtype(Box::new(Value::Bytes(b"hi".as_ref().into()))),
306                    ),
307                ]
308                .into_iter()
309                .collect(),
310            ),
311        ]))));
312
313        // assert that the value remains unchanged through deserialization
314        let value_de = Value::deserialize(value.clone()).unwrap();
315        assert_eq!(value_de, value);
316    }
317
318    #[test]
319    fn ser_smoke_test() {
320        #[derive(Serialize)]
321        struct Foo {
322            a: u32,
323            b: String,
324            c: Vec<bool>,
325        }
326
327        let foo = Foo {
328            a: 15,
329            b: "hello".into(),
330            c: vec![true, false],
331        };
332
333        let expected = Value::Map(
334            vec![
335                (Value::String("a".into()), Value::U32(15)),
336                (Value::String("b".into()), Value::String("hello".into())),
337                (
338                    Value::String("c".into()),
339                    Value::Seq(vec![Value::Bool(true), Value::Bool(false)]),
340                ),
341            ]
342            .into_iter()
343            .collect(),
344        );
345
346        let value = to_value(&foo).unwrap();
347        assert_eq!(expected, value);
348    }
349
350    #[test]
351    fn deserialize_into_enum() {
352        #[derive(Deserialize, Debug, PartialEq, Eq)]
353        enum Foo {
354            Bar,
355            Baz(u8),
356        }
357
358        let value = Value::String("Bar".into());
359        assert_eq!(Foo::deserialize(value).unwrap(), Foo::Bar);
360
361        let value = Value::Map(
362            vec![(Value::String("Baz".into()), Value::U8(1))]
363                .into_iter()
364                .collect(),
365        );
366        assert_eq!(Foo::deserialize(value).unwrap(), Foo::Baz(1));
367    }
368
369    #[test]
370    fn serialize_from_enum() {
371        #[derive(Serialize)]
372        enum Foo {
373            Bar,
374            Baz(u8),
375            Qux { quux: u8 },
376            Corge(u8, u8),
377        }
378
379        let bar = Foo::Bar;
380        assert_eq!(to_value(&bar).unwrap(), Value::String("Bar".into()));
381
382        let baz = Foo::Baz(1);
383        assert_eq!(
384            to_value(&baz).unwrap(),
385            Value::Map(
386                vec![(Value::String("Baz".into()), Value::U8(1))]
387                    .into_iter()
388                    .collect(),
389            )
390        );
391
392        let qux = Foo::Qux { quux: 2 };
393        assert_eq!(
394            to_value(&qux).unwrap(),
395            Value::Map(
396                vec![(
397                    Value::String("Qux".into()),
398                    Value::Map(
399                        vec![(Value::String("quux".into()), Value::U8(2))]
400                            .into_iter()
401                            .collect()
402                    )
403                )]
404                .into_iter()
405                .collect()
406            )
407        );
408
409        let corge = Foo::Corge(3, 4);
410        assert_eq!(
411            to_value(&corge).unwrap(),
412            Value::Map(
413                vec![(
414                    Value::String("Corge".into()),
415                    Value::Seq(vec![Value::U8(3), Value::U8(4)])
416                )]
417                .into_iter()
418                .collect()
419            )
420        );
421    }
422
423    #[test]
424    fn deserialize_inside_deserialize_impl() {
425        #[derive(Debug, PartialEq, Eq)]
426        enum Event {
427            Added(u32),
428            Error(u8),
429        }
430
431        impl<'de> serde::Deserialize<'de> for Event {
432            fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
433            where
434                D: serde::Deserializer<'de>,
435            {
436                #[derive(Deserialize)]
437                struct RawEvent {
438                    kind: String,
439                    object: Value,
440                }
441
442                let raw_event = RawEvent::deserialize(deserializer)?;
443
444                // Cannot directly use Value as Deserializer, since error type needs to be
445                // generic D::Error rather than specific serde_value::DeserializerError
446                let object_deserializer = ValueDeserializer::new(raw_event.object);
447
448                Ok(match &*raw_event.kind {
449                    "ADDED" => Event::Added(<_>::deserialize(object_deserializer)?),
450                    "ERROR" => Event::Error(<_>::deserialize(object_deserializer)?),
451                    kind => {
452                        return Err(serde::de::Error::unknown_variant(kind, &["ADDED", "ERROR"]))
453                    }
454                })
455            }
456        }
457
458        let input = Value::Map(
459            vec![
460                (
461                    Value::String("kind".to_owned()),
462                    Value::String("ADDED".to_owned()),
463                ),
464                (Value::String("object".to_owned()), Value::U32(5)),
465            ]
466            .into_iter()
467            .collect(),
468        );
469        let event = Event::deserialize(input).expect("could not deserialize ADDED event");
470        assert_eq!(event, Event::Added(5));
471
472        let input = Value::Map(
473            vec![
474                (
475                    Value::String("kind".to_owned()),
476                    Value::String("ERROR".to_owned()),
477                ),
478                (Value::String("object".to_owned()), Value::U8(5)),
479            ]
480            .into_iter()
481            .collect(),
482        );
483        let event = Event::deserialize(input).expect("could not deserialize ERROR event");
484        assert_eq!(event, Event::Error(5));
485
486        let input = Value::Map(
487            vec![
488                (
489                    Value::String("kind".to_owned()),
490                    Value::String("ADDED".to_owned()),
491                ),
492                (Value::String("object".to_owned()), Value::Unit),
493            ]
494            .into_iter()
495            .collect(),
496        );
497        let _ =
498            Event::deserialize(input).expect_err("expected deserializing bad ADDED event to fail");
499    }
500
501    #[test]
502    fn deserialize_newtype() {
503        #[derive(Debug, Deserialize, PartialEq)]
504        struct Foo(i32);
505
506        let input = Value::I32(5);
507        let foo = Foo::deserialize(input).unwrap();
508        assert_eq!(foo, Foo(5));
509    }
510
511    #[test]
512    fn deserialize_newtype2() {
513        #[derive(Debug, Deserialize, PartialEq)]
514        struct Foo(i32);
515
516        #[derive(Debug, Deserialize, PartialEq)]
517        struct Bar {
518            foo: Foo,
519        }
520
521        let input = Value::Map(
522            vec![(Value::String("foo".to_owned()), Value::I32(5))]
523                .into_iter()
524                .collect(),
525        );
526        let bar = Bar::deserialize(input).unwrap();
527        assert_eq!(bar, Bar { foo: Foo(5) });
528    }
529
530    #[test]
531    fn clock_ser_deser() {
532        let (clock, mock) = RobotClock::mock();
533        mock.increment(CuDuration::from_nanos(42));
534        let c = clock.now();
535
536        let input = Value::CuTime(c);
537        let foo = CuTime::deserialize(input).unwrap();
538        assert_eq!(foo, CuTime::from(Duration::from_nanos(42)));
539    }
540    #[test]
541    fn value_encode_decode() {
542        fn check_value(value: Value) {
543            let v = bincode::encode_to_vec(&value, standard()).expect("encode failed");
544            let (v2, s) = bincode::decode_from_slice::<Value, _>(v.as_slice(), standard())
545                .expect("decode failed");
546            assert_eq!(s, v.len());
547            assert_eq!(&v2, &value);
548        }
549
550        check_value(Value::Bool(true));
551        check_value(Value::U8(42));
552        check_value(Value::U16(42));
553        check_value(Value::U32(42));
554        check_value(Value::U64(42));
555        check_value(Value::I8(42));
556        check_value(Value::I16(42));
557        check_value(Value::I32(42));
558        check_value(Value::I64(42));
559        check_value(Value::F32(42.42));
560        check_value(Value::F64(42.42));
561        check_value(Value::Char('4'));
562        check_value(Value::String("42".into()));
563        check_value(Value::Unit);
564        check_value(Value::Option(Some(Box::new(Value::U32(42)))));
565        check_value(Value::Newtype(Box::new(Value::U32(42))));
566        check_value(Value::Seq(vec![Value::Bool(true), Value::U32(42)]));
567        check_value(Value::Map(BTreeMap::from([
568            (Value::Bool(true), Value::U32(42)),
569            (Value::String("42".into()), Value::I32(42)),
570        ])));
571        check_value(Value::Bytes(vec![0x4, 0x2]));
572        check_value(Value::CuTime(CuTime::from(Duration::from_nanos(42))));
573    }
574
575    #[test]
576    fn test_cutime_tovalue() {
577        let c = CuTime::from(Duration::from_nanos(42));
578        let v = to_value(c).expect("to_value failed");
579        assert_eq!(v, Value::CuTime(c));
580    }
581    /// Test basic value creation and type checking
582    #[test]
583    fn test_value_creation_and_types() {
584        // Create various value types
585        let bool_val = Value::Bool(true);
586        let i32_val = Value::I32(42);
587        let str_val = Value::String("test".to_string());
588        let unit_val = Value::Unit;
589        let option_val = Value::Option(Some(Box::new(Value::U8(5))));
590
591        // Verify type discrimination
592        assert!(matches!(bool_val, Value::Bool(true)));
593        assert!(matches!(i32_val, Value::I32(42)));
594        assert!(matches!(str_val, Value::String(ref s) if s == "test"));
595        assert!(matches!(unit_val, Value::Unit));
596        assert!(matches!(option_val, Value::Option(Some(_))));
597
598        // Check discriminant values
599        assert_eq!(bool_val.discriminant(), 0);
600        assert_eq!(i32_val.discriminant(), 7);
601        assert_eq!(str_val.discriminant(), 12);
602    }
603
604    /// Test numeric boundary values and special floating points
605    #[test]
606    fn test_numeric_boundaries_and_special_values() {
607        // Integer boundaries
608        let min_i8 = Value::I8(i8::MIN);
609        let max_i8 = Value::I8(i8::MAX);
610        let min_i64 = Value::I64(i64::MIN);
611        let max_u64 = Value::U64(u64::MAX);
612
613        // Special floating points
614        let nan = Value::F64(f64::NAN);
615        let pos_inf = Value::F64(f64::INFINITY);
616        let neg_inf = Value::F64(f64::NEG_INFINITY);
617        let zero = Value::F64(0.0);
618        let neg_zero = Value::F64(-0.0);
619
620        // Make sure these encode and decode correctly
621        for val in [
622            min_i8,
623            max_i8,
624            min_i64,
625            max_u64,
626            nan.clone(),
627            pos_inf.clone(),
628            neg_inf.clone(),
629            zero.clone(),
630            neg_zero.clone(),
631        ] {
632            let encoded = encode_to_vec(&val, standard()).unwrap();
633            let (decoded, _): (Value, _) = decode_from_slice(&encoded, standard()).unwrap();
634
635            // Special case for NaN since NaN != NaN in normal floating point comparisons
636            if matches!(val, Value::F64(f) if f.is_nan()) {
637                assert!(matches!(decoded, Value::F64(f) if f.is_nan()));
638            } else {
639                assert_eq!(val, decoded);
640            }
641        }
642
643        // Test ordering behavior with special values
644        assert!(pos_inf > zero);
645        assert!(neg_inf < zero);
646
647        // NaN should be equal to itself when wrapped in Value (due to OrderedFloat)
648        let nan2 = Value::F64(f64::NAN);
649        assert_eq!(nan, nan2); // This works because Value uses OrderedFloat
650
651        // Verify zero and negative zero are treated as equal
652        assert_eq!(zero, neg_zero);
653    }
654
655    /// Test handling of containers (maps, sequences)
656    #[test]
657    fn test_container_types() {
658        // Empty containers
659        let empty_seq = Value::Seq(vec![]);
660        let empty_map = Value::Map(BTreeMap::new());
661
662        // Simple containers
663        let simple_seq = Value::Seq(vec![Value::I32(1), Value::I32(2), Value::I32(3)]);
664        let mut simple_map = BTreeMap::new();
665        simple_map.insert(Value::String("key".to_string()), Value::Bool(true));
666        let simple_map_val = Value::Map(simple_map);
667
668        // Deeply nested containers
669        let mut nested_map = BTreeMap::new();
670        nested_map.insert(
671            Value::String("outer".to_string()),
672            Value::Seq(vec![
673                Value::Option(Some(Box::new(Value::Map({
674                    let mut m = BTreeMap::new();
675                    m.insert(Value::I32(1), Value::String("nested".to_string()));
676                    m
677                })))),
678                Value::Bool(false),
679            ]),
680        );
681        let nested_val = Value::Map(nested_map);
682
683        // Encode and decode all container types
684        for val in [empty_seq, empty_map, simple_seq, simple_map_val, nested_val] {
685            let encoded = encode_to_vec(&val, standard()).unwrap();
686            let (decoded, _): (Value, _) = decode_from_slice(&encoded, standard()).unwrap();
687            assert_eq!(val, decoded);
688        }
689    }
690
691    /// Test handling of large values
692    #[test]
693    fn test_large_values() {
694        // Large sequence
695        let large_seq = Value::Seq((0..10000).map(Value::I32).collect());
696
697        // Large string
698        let large_string = Value::String("x".repeat(100000));
699
700        // Large bytes
701        let large_bytes = Value::Bytes((0..10000).map(|i| (i % 256) as u8).collect());
702
703        // Large nested structure
704        let mut large_map = BTreeMap::new();
705        for i in 0..1000 {
706            large_map.insert(
707                Value::I32(i),
708                Value::Seq((0..10).map(|j| Value::I32(i * j)).collect()),
709            );
710        }
711        let large_nested = Value::Map(large_map);
712
713        // Test round-trip for large values
714        for val in [large_seq, large_string, large_bytes, large_nested] {
715            let encoded = encode_to_vec(&val, standard()).unwrap();
716            let (decoded, _): (Value, _) = decode_from_slice(&encoded, standard()).unwrap();
717            assert_eq!(val, decoded);
718        }
719    }
720
721    /// Test value comparison across different types
722    #[test]
723    fn test_value_comparison() {
724        // Same type comparisons
725        assert!(Value::I32(1) < Value::I32(2));
726        assert!(Value::String("a".to_string()) < Value::String("b".to_string()));
727        assert!(Value::Bool(false) < Value::Bool(true));
728
729        // Different type comparisons (based on discriminant)
730        assert!(Value::Bool(true) < Value::I32(0)); // Bool(0) < I32(7) by discriminant
731        assert!(Value::I32(100) < Value::String("a".to_string())); // I32(7) < String(12)
732
733        // Container comparisons
734        assert!(
735            Value::Seq(vec![Value::I32(1), Value::I32(2)])
736                < Value::Seq(vec![Value::I32(1), Value::I32(3)])
737        );
738
739        let mut map1 = BTreeMap::new();
740        map1.insert(Value::String("key".to_string()), Value::I32(1));
741
742        let mut map2 = BTreeMap::new();
743        map2.insert(Value::String("key".to_string()), Value::I32(2));
744
745        assert!(Value::Map(map1) < Value::Map(map2));
746
747        // Test equality with NaN handling
748        let nan1 = Value::F64(f64::NAN);
749        let nan2 = Value::F64(f64::NAN);
750        assert_eq!(nan1, nan2); // OrderedFloat makes NaN == NaN
751    }
752
753    /// Test hash consistency for various value types
754    #[test]
755    #[cfg(feature = "std")]
756    fn test_value_hashing() {
757        use core::hash::Hasher;
758        use std::collections::hash_map::DefaultHasher;
759
760        let values = [
761            Value::Bool(true),
762            Value::I32(42),
763            Value::String("hash me".to_string()),
764            Value::F64(3.1),
765            Value::Char('🦀'),
766            Value::Option(Some(Box::new(Value::U8(5)))),
767            Value::Unit,
768        ];
769
770        for val in values {
771            // Hash the same value twice, should be consistent
772            let mut hasher1 = DefaultHasher::new();
773            let mut hasher2 = DefaultHasher::new();
774            val.hash(&mut hasher1);
775            val.hash(&mut hasher2);
776            assert_eq!(hasher1.finish(), hasher2.finish());
777
778            // Clone and hash, should be the same
779            let val_clone = val.clone();
780            let mut hasher3 = DefaultHasher::new();
781            val_clone.hash(&mut hasher3);
782            assert_eq!(hasher1.finish(), hasher3.finish());
783        }
784
785        // Special case: NaN should have consistent hash
786        let nan1 = Value::F64(f64::NAN);
787        let nan2 = Value::F64(f64::NAN);
788
789        let mut hasher1 = DefaultHasher::new();
790        let mut hasher2 = DefaultHasher::new();
791        nan1.hash(&mut hasher1);
792        nan2.hash(&mut hasher2);
793        assert_eq!(hasher1.finish(), hasher2.finish());
794    }
795
796    /// Test serialization/deserialization of custom data structures
797    #[test]
798    fn test_struct_serde() {
799        #[derive(Serialize, Deserialize, Debug, PartialEq)]
800        struct Person {
801            name: String,
802            age: u32,
803            addresses: Vec<Address>,
804        }
805
806        #[derive(Serialize, Deserialize, Debug, PartialEq)]
807        struct Address {
808            street: String,
809            city: String,
810            zip: u32,
811        }
812
813        let person = Person {
814            name: "Alice".to_string(),
815            age: 30,
816            addresses: vec![
817                Address {
818                    street: "123 Main St".to_string(),
819                    city: "Anytown".to_string(),
820                    zip: 12345,
821                },
822                Address {
823                    street: "456 Oak Ave".to_string(),
824                    city: "Somewhere".to_string(),
825                    zip: 67890,
826                },
827            ],
828        };
829
830        // Convert to Value
831        let value = to_value(&person).unwrap();
832
833        // Check structure
834        assert!(matches!(value, Value::Map(_)));
835
836        // Convert back to original type
837        let person2 = value.deserialize_into::<Person>().unwrap();
838        assert_eq!(person, person2);
839    }
840
841    /// Test enum serialization/deserialization
842    #[test]
843    fn test_enum_serde() {
844        #[derive(Serialize, Deserialize, Debug, PartialEq)]
845        enum MyEnum {
846            Unit,
847            NewType(i32),
848            Tuple(String, bool),
849            Struct { x: f64, y: f64 },
850        }
851
852        // Test all variants
853        let variants = vec![
854            MyEnum::Unit,
855            MyEnum::NewType(42),
856            MyEnum::Tuple("hello".to_string(), true),
857            MyEnum::Struct { x: 1.0, y: 2.0 },
858        ];
859
860        for variant in variants {
861            let value = to_value(&variant).unwrap();
862            let roundtrip = value.deserialize_into::<MyEnum>().unwrap();
863            assert_eq!(variant, roundtrip);
864        }
865    }
866
867    /// Test custom CuTime type handling
868    #[test]
869    fn test_cutime_handling() {
870        // Test round-trip for CuTime values
871        let times = vec![
872            CuTime::from(CuDuration(0)),
873            CuTime::from(CuDuration(1)),
874            CuTime::from(CuDuration(u64::MAX / 2)),
875            // Exclude MAX as it might be reserved for special use
876        ];
877
878        for time in times {
879            // Direct Value creation
880            let time_value = Value::CuTime(time);
881
882            // Serialize/deserialize as Value
883            let encoded = encode_to_vec(&time_value, standard()).unwrap();
884            let (decoded, _): (Value, _) = decode_from_slice(&encoded, standard()).unwrap();
885            assert_eq!(time_value, decoded);
886
887            // Convert through to_value
888            let via_to_value = to_value(time).unwrap();
889            assert_eq!(via_to_value, time_value);
890
891            // Deserialize back to CuTime
892            let time_roundtrip = via_to_value.deserialize_into::<CuTime>().unwrap();
893            assert_eq!(time, time_roundtrip);
894        }
895    }
896
897    /// Test error handling in deserialization
898    #[test]
899    fn test_error_handling() {
900        // Type mismatch
901        let bool_val = Value::Bool(true);
902        let result = bool_val.clone().deserialize_into::<i32>();
903        assert!(result.is_err());
904
905        // Missing fields
906        let empty_map = Value::Map(BTreeMap::new());
907
908        #[derive(Deserialize)]
909        struct RequiredFields {
910            _required: String,
911        }
912
913        let result = empty_map.deserialize_into::<RequiredFields>();
914        assert!(result.is_err());
915
916        // Invalid enum variant
917        let invalid_variant = Value::String("NonExistentVariant".to_string());
918
919        #[derive(Deserialize)]
920        enum TestEnum {
921            A,
922            B,
923            C,
924        }
925
926        let result = invalid_variant.deserialize_into::<TestEnum>();
927        assert!(result.is_err());
928
929        // Check we get appropriate error types
930        match bool_val.deserialize_into::<String>() {
931            Err(DeserializerError::InvalidType(..)) => (), // Expected
932            other => panic!("Expected InvalidType error, got: {other:?}"),
933        }
934    }
935
936    /// Test unicode handling in strings and chars
937    #[test]
938    fn test_unicode_handling() {
939        let strings = vec![
940            "".to_string(),             // Empty
941            "ASCII only".to_string(),   // ASCII
942            "Café 🍰".to_string(),      // Mixed ASCII and Unicode
943            "日本語".to_string(),       // CJK characters
944            "👨‍👩‍👧‍👦 Family".to_string(),    // Complex emoji with ZWJ sequences
945            "ᛁᚲ ᚲᚨᚾ ᚱᚢᚾᛖᛋ".to_string(), // Ancient runes
946        ];
947
948        for s in strings {
949            let string_val = Value::String(s.clone());
950
951            // Test round-trip
952            let encoded = encode_to_vec(&string_val, standard()).unwrap();
953            let (decoded, _): (Value, _) = decode_from_slice(&encoded, standard()).unwrap();
954
955            if let Value::String(decoded_s) = decoded {
956                assert_eq!(s, decoded_s);
957            } else {
958                panic!("Expected String value");
959            }
960        }
961
962        // Test various Unicode characters
963        let chars = vec!['a', 'é', '日', '🦀'];
964
965        for c in chars {
966            let char_val = Value::Char(c);
967
968            // Test round-trip
969            let encoded = encode_to_vec(&char_val, standard()).unwrap();
970            let (decoded, _): (Value, _) = decode_from_slice(&encoded, standard()).unwrap();
971
972            if let Value::Char(decoded_c) = decoded {
973                assert_eq!(c, decoded_c);
974            } else {
975                panic!("Expected Char value");
976            }
977        }
978    }
979
980    /// Test ValueDeserializer directly
981    #[test]
982    fn test_value_deserializer() {
983        let original = vec![1, 2, 3];
984        let value = to_value(&original).unwrap();
985
986        // Create a deserializer
987        let deserializer: de::ValueDeserializer<DeserializerError> = ValueDeserializer::new(value);
988
989        // Use it to deserialize
990        let result: Vec<i32> = serde::Deserialize::deserialize(deserializer).unwrap();
991
992        assert_eq!(original, result);
993    }
994
995    /// Test serialization/deserialization with custom types and Option
996    #[test]
997    fn test_option_handling() {
998        // Some values
999        let some_i32 = Some(42);
1000        let some_string = Some("test".to_string());
1001
1002        // None values of different types
1003        let none_i32: Option<i32> = None;
1004        let none_string: Option<String> = None;
1005
1006        // Convert to Value
1007        let some_i32_value = to_value(some_i32).unwrap();
1008        let some_string_value = to_value(&some_string).unwrap();
1009        let none_i32_value = to_value(none_i32).unwrap();
1010        let none_string_value = to_value(&none_string).unwrap();
1011
1012        // Check structure
1013        assert!(matches!(some_i32_value, Value::Option(Some(_))));
1014        assert!(matches!(some_string_value, Value::Option(Some(_))));
1015        assert!(matches!(none_i32_value, Value::Option(None)));
1016        assert!(matches!(none_string_value, Value::Option(None)));
1017
1018        // Round-trip
1019        let some_i32_rt: Option<i32> = some_i32_value.deserialize_into().unwrap();
1020        let some_string_rt: Option<String> = some_string_value.deserialize_into().unwrap();
1021        let none_i32_rt: Option<i32> = none_i32_value.deserialize_into().unwrap();
1022        let none_string_rt: Option<String> = none_string_value.deserialize_into().unwrap();
1023
1024        assert_eq!(some_i32, some_i32_rt);
1025        assert_eq!(some_string, some_string_rt);
1026        assert_eq!(none_i32, none_i32_rt);
1027        assert_eq!(none_string, none_string_rt);
1028    }
1029
1030    /// Test deeply nested option values
1031    #[test]
1032    fn test_nested_options() {
1033        // Create deeply nested Option structure
1034        let nested_option: Option<Option<Option<i32>>> = Some(Some(Some(42)));
1035
1036        // Convert to Value
1037        let value = to_value(nested_option).unwrap();
1038
1039        // Verify structure
1040        let mut current = &value;
1041        for _ in 0..3 {
1042            assert!(matches!(current, Value::Option(Some(_))));
1043            if let Value::Option(Some(inner)) = current {
1044                current = inner;
1045            } else {
1046                panic!("Expected Some");
1047            }
1048        }
1049        assert!(matches!(current, Value::I32(42)));
1050
1051        // Round-trip test
1052        let result: Option<Option<Option<i32>>> = value.deserialize_into().unwrap();
1053        assert_eq!(nested_option, result);
1054    }
1055
1056    /// Test conversion behaviors between numeric types
1057    #[test]
1058    fn test_numeric_conversions() {
1059        // Create values of different numeric types
1060        let i8_val = Value::I8(42);
1061        let i16_val = Value::I16(42);
1062        let i32_val = Value::I32(42);
1063        let i64_val = Value::I64(42);
1064        let u8_val = Value::U8(42);
1065        let u16_val = Value::U16(42);
1066        let u32_val = Value::U32(42);
1067        let u64_val = Value::U64(42);
1068        let u64_val_large = Value::U64(u64::MAX);
1069        let f32_val = Value::F32(42.0);
1070        let f64_val = Value::F64(42.0);
1071
1072        // Test valid conversions
1073        // Note: Some of these might depend on implementation details
1074        assert!(i8_val.deserialize_into::<i16>().is_ok());
1075        assert!(i16_val.deserialize_into::<i32>().is_ok());
1076        assert!(i32_val.clone().deserialize_into::<i64>().is_ok());
1077        assert!(u8_val.deserialize_into::<u16>().is_ok());
1078        assert!(u16_val.deserialize_into::<u32>().is_ok());
1079        assert!(u32_val.deserialize_into::<u64>().is_ok());
1080        assert!(u64_val.clone().deserialize_into::<f64>().is_ok());
1081        assert!(i32_val.deserialize_into::<f32>().is_ok());
1082        assert!(f32_val.deserialize_into::<f64>().is_ok());
1083        assert!(i64_val.clone().deserialize_into::<f64>().is_ok());
1084        assert!(u64_val.deserialize_into::<i8>().is_ok());
1085
1086        // Test conversions that shouldn't work
1087        assert!(u64_val_large.deserialize_into::<i8>().is_err());
1088        assert!(f64_val.deserialize_into::<u32>().is_err());
1089        assert!(i64_val.deserialize_into::<bool>().is_err());
1090    }
1091
1092    /// Test Display implementation
1093    #[test]
1094    fn test_display_implementation() {
1095        // Sample different value types and check their string representation
1096        let values = [
1097            (Value::Bool(true), "true"),
1098            (Value::I32(42), "42"),
1099            (Value::String("test".to_string()), "test"),
1100            (Value::Unit, "()"),
1101            (
1102                Value::CuTime(CuTime::from(CuDuration(1_000_000_000))),
1103                "1.000 s",
1104            ),
1105        ];
1106
1107        for (val, expected) in values {
1108            assert_eq!(val.to_string(), expected);
1109        }
1110
1111        // More complex values
1112        let seq = Value::Seq(vec![Value::I32(1), Value::I32(2), Value::I32(3)]);
1113        assert_eq!(seq.to_string(), "[1, 2, 3]");
1114
1115        let mut map = BTreeMap::new();
1116        map.insert(Value::String("key".to_string()), Value::Bool(true));
1117        let map_val = Value::Map(map);
1118        assert_eq!(map_val.to_string(), "{key: true}");
1119    }
1120    #[test]
1121    fn test_numeric_overflow_detection() {
1122        // Test overflow detection
1123        let large_i64 = Value::I64(i64::MAX);
1124        assert!(large_i64.deserialize_into::<i32>().is_err());
1125
1126        // Test underflow detection
1127        let negative = Value::I64(-1);
1128        assert!(negative.deserialize_into::<u64>().is_err());
1129
1130        // Edge case: exactly at boundary
1131        let max_i32 = Value::I64(i32::MAX as i64);
1132        assert!(max_i32.deserialize_into::<i32>().is_ok());
1133
1134        // Edge case: one beyond boundary
1135        let beyond_max_i32 = Value::I64((i32::MAX as i64) + 1);
1136        assert!(beyond_max_i32.deserialize_into::<i32>().is_err());
1137    }
1138
1139    #[test]
1140    fn test_float_precision_handling() {
1141        // Integer -> float -> integer round trip
1142        let original = i64::MAX;
1143        let as_value = Value::I64(original);
1144        let as_f64: f64 = as_value.deserialize_into().unwrap();
1145        let round_trip = Value::F64(as_f64).deserialize_into::<i64>();
1146
1147        // the round_trip should return Error since f64 cannot represent all i64 values
1148        assert!(round_trip.is_err());
1149
1150        // Fractional values to integers
1151        let half = Value::F64(0.5);
1152        let half_as_i32 = half.deserialize_into::<i32>();
1153        assert!(half_as_i32.is_err());
1154    }
1155
1156    #[test]
1157    fn test_float_special_values() {
1158        // NaN to integer
1159        let nan = Value::F64(f64::NAN);
1160        assert!(nan.deserialize_into::<i32>().is_err());
1161
1162        // Infinity to integer
1163        let infinity = Value::F64(f64::INFINITY);
1164        assert!(infinity.deserialize_into::<i64>().is_err());
1165
1166        // Huge values within float range but beyond integer range
1167        let huge = Value::F64(1e20);
1168        assert!(huge.deserialize_into::<i64>().is_err());
1169    }
1170}