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