Skip to main content

cbor_core/ext/
serde.rs

1//! Serde integration for CBOR [`Value`].
2//!
3//! This module provides [`Serialize`] and [`Deserialize`] implementations
4//! for [`Value`]. Conversion between arbitrary Rust types and [`Value`]
5//! is performed through the inherent methods [`Value::serialized`] and
6//! [`Value::deserialized`]. The module also defines the
7//! [`SerdeError`] type returned by these conversions.
8//!
9//! # Converting Rust types to `Value`
10//!
11//! Any type that implements [`Serialize`] can be converted into a
12//! [`Value`] with [`Value::serialized`]:
13//!
14//! ```
15//! use cbor_core::Value;
16//! use serde::Serialize;
17//!
18//! #[derive(Serialize)]
19//! struct Sensor {
20//!     id: u32,
21//!     label: String,
22//!     readings: Vec<f64>,
23//! }
24//!
25//! let s = Sensor {
26//!     id: 7,
27//!     label: "temperature".into(),
28//!     readings: vec![20.5, 21.0, 19.8],
29//! };
30//!
31//! let v = Value::serialized(&s).unwrap();
32//! assert_eq!(v["id"].to_u32().unwrap(), 7);
33//! assert_eq!(v["label"].as_str().unwrap(), "temperature");
34//! assert_eq!(v["readings"][0].to_f64().unwrap(), 20.5);
35//! ```
36//!
37//! # Converting `Value` to Rust types
38//!
39//! [`Value::deserialized`] goes the other direction, extracting a
40//! [`Deserialize`] type from a [`Value`]:
41//!
42//! ```
43//! use cbor_core::{Value, map, array};
44//! use serde::Deserialize;
45//!
46//! #[derive(Deserialize, Debug, PartialEq)]
47//! struct Sensor {
48//!     id: u32,
49//!     label: String,
50//!     readings: Vec<f64>,
51//! }
52//!
53//! let v = map! {
54//!     "id" => 7,
55//!     "label" => "temperature",
56//!     "readings" => array![20.5, 21.0, 19.8],
57//! };
58//!
59//! let s: Sensor = v.deserialized().unwrap();
60//! assert_eq!(s.id, 7);
61//! assert_eq!(s.label, "temperature");
62//! ```
63//!
64//! # Going directly between bytes and Rust types
65//!
66//! Combining [`Value::serialized`] / [`Value::deserialized`] with
67//! [`Value::encode`], [`Value::decode`], [`Value::encode_hex`], and
68//! [`Value::decode_hex`] gives concise round-trips through the wire
69//! format:
70//!
71//! ```
72//! use cbor_core::Value;
73//! use serde::{Deserialize, Serialize};
74//!
75//! #[derive(Serialize, Deserialize, Debug, PartialEq)]
76//! struct Point { x: i32, y: i32 }
77//!
78//! let p = Point { x: 1, y: 2 };
79//!
80//! let hex = Value::serialized(&p).unwrap().encode_hex();
81//! let back: Point = Value::decode_hex(&hex).unwrap().deserialized().unwrap();
82//! assert_eq!(back, p);
83//! ```
84//!
85//! # Serializing `Value` with other formats
86//!
87//! Because [`Value`] implements [`Serialize`] and [`Deserialize`], it
88//! works directly with any serde-based format such as JSON:
89//!
90//! ```
91//! use cbor_core::{Value, map};
92//!
93//! let v = map! { "x" => 1, "y" => 2 };
94//! let json = serde_json::to_string(&v).unwrap();
95//!
96//! let back: Value = serde_json::from_str(&json).unwrap();
97//! assert_eq!(back["x"].to_i32().unwrap(), 1);
98//! ```
99//!
100//! # Tags and CBOR-specific types
101//!
102//! The serde data model does not have a notion of CBOR tags or simple
103//! values. During deserialization, tags are stripped and their inner
104//! content is used directly, with the exception of big integers
105//! (tags 2 and 3), which are recognized and deserialized as integers.
106//! During serialization, tags are only emitted for big integers that
107//! exceed the `u64`/`i64` range; all other values are untagged.
108//!
109//! Tagged values and arbitrary simple values cannot be created through
110//! the serde interface. For full control over the encoded CBOR
111//! structure, build [`Value`]s directly using the constructors on
112//! [`Value`] (e.g. [`Value::tag`], [`Value::simple_value`]).
113
114use std::collections::BTreeMap;
115use std::fmt;
116
117use serde::de::{self, DeserializeSeed, Deserializer as _, MapAccess, SeqAccess, Visitor};
118use serde::ser::{self, SerializeMap, SerializeSeq};
119use serde::{Deserialize, Serialize};
120
121use crate::Value;
122
123// ---------------------------------------------------------------------------
124// Error
125// ---------------------------------------------------------------------------
126
127/// Error type returned by serde operations on [`Value`].
128///
129/// This is a string-based error type, separate from [`crate::Error`],
130/// because serde requires error types to support arbitrary messages
131/// via [`ser::Error::custom`] and [`de::Error::custom`]. The contained
132/// message is accessible directly through the public field.
133#[derive(Debug, Clone)]
134pub struct SerdeError(pub String);
135
136impl fmt::Display for SerdeError {
137    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
138        self.0.fmt(f)
139    }
140}
141
142impl std::error::Error for SerdeError {}
143
144impl ser::Error for SerdeError {
145    fn custom<T: fmt::Display>(msg: T) -> Self {
146        SerdeError(msg.to_string())
147    }
148}
149
150impl de::Error for SerdeError {
151    fn custom<T: fmt::Display>(msg: T) -> Self {
152        SerdeError(msg.to_string())
153    }
154}
155
156impl From<crate::Error> for SerdeError {
157    fn from(error: crate::Error) -> Self {
158        SerdeError(error.to_string())
159    }
160}
161
162// ---------------------------------------------------------------------------
163// Public API on Value
164// ---------------------------------------------------------------------------
165
166impl<'a> Value<'a> {
167    /// Serialize any [`Serialize`] value into a CBOR [`Value`].
168    ///
169    /// # Errors
170    ///
171    /// Returns any [`SerdeError`] raised by `value`'s
172    /// [`Serialize`] implementation.
173    ///
174    /// ```
175    /// use cbor_core::Value;
176    /// use serde::Serialize;
177    ///
178    /// #[derive(Serialize)]
179    /// struct Point { x: i32, y: i32 }
180    ///
181    /// let p = Point { x: 1, y: 2 };
182    /// let v = Value::serialized(&p).unwrap();
183    /// assert_eq!(v["x"].to_i32().unwrap(), 1);
184    /// assert_eq!(v["y"].to_i32().unwrap(), 2);
185    /// ```
186    pub fn serialized<T: ?Sized + Serialize>(value: &T) -> Result<Self, SerdeError> {
187        value.serialize(ValueSerializer(std::marker::PhantomData))
188    }
189
190    /// Deserialize this [`Value`] into any [`Deserialize`] type.
191    ///
192    /// # Errors
193    ///
194    /// Returns any [`SerdeError`] raised by `T`'s
195    /// [`Deserialize`] implementation, including type mismatches
196    /// between this `Value`'s shape and the target type.
197    ///
198    /// ```
199    /// use cbor_core::{Value, map};
200    /// use serde::Deserialize;
201    ///
202    /// #[derive(Deserialize, Debug, PartialEq)]
203    /// struct Point { x: i32, y: i32 }
204    ///
205    /// let v = map! { "x" => 1, "y" => 2 };
206    /// let p: Point = v.deserialized().unwrap();
207    /// assert_eq!(p, Point { x: 1, y: 2 });
208    /// ```
209    pub fn deserialized<'de, T: Deserialize<'de>>(&'de self) -> Result<T, SerdeError> {
210        T::deserialize(ValueDeserializer(self))
211    }
212}
213
214// ---------------------------------------------------------------------------
215// Serialize impl for Value
216// ---------------------------------------------------------------------------
217
218impl<'a> Serialize for Value<'a> {
219    fn serialize<S: ser::Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
220        match self {
221            Value::SimpleValue(sv) => match sv.data_type() {
222                crate::DataType::Null => serializer.serialize_unit(),
223                crate::DataType::Bool => serializer.serialize_bool(sv.to_bool().unwrap()),
224                _ => serializer.serialize_u8(sv.to_u8()),
225            },
226            Value::Unsigned(n) => serializer.serialize_u64(*n),
227            Value::Negative(n) => {
228                // actual value = -1 - n
229                if let Ok(v) = i64::try_from(*n).map(|v| !v) {
230                    serializer.serialize_i64(v)
231                } else {
232                    serializer.serialize_i128(!(*n as i128))
233                }
234            }
235            Value::Float(float) => serializer.serialize_f64(float.to_f64()),
236            Value::ByteString(b) => serializer.serialize_bytes(b),
237            Value::TextString(s) => serializer.serialize_str(s),
238            Value::Array(arr) => {
239                let mut seq = serializer.serialize_seq(Some(arr.len()))?;
240                for item in arr {
241                    seq.serialize_element(item)?;
242                }
243                seq.end()
244            }
245            Value::Map(map) => {
246                let mut m = serializer.serialize_map(Some(map.len()))?;
247                for (k, v) in map {
248                    m.serialize_entry(k, v)?;
249                }
250                m.end()
251            }
252            // Tags are transparent: serialize the inner content.
253            Value::Tag(_, content) => content.serialize(serializer),
254        }
255    }
256}
257
258// ---------------------------------------------------------------------------
259// Deserialize impl for Value
260// ---------------------------------------------------------------------------
261
262impl<'de, 'a> Deserialize<'de> for Value<'a> {
263    fn deserialize<D: de::Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
264        deserializer.deserialize_any(ValueVisitor(std::marker::PhantomData))
265    }
266}
267
268struct ValueVisitor<'a>(std::marker::PhantomData<&'a ()>);
269
270macro_rules! visit {
271    ($method:ident, $type:ty) => {
272        fn $method<E>(self, v: $type) -> Result<Value<'a>, E> {
273            Ok(Value::from(v))
274        }
275    };
276}
277
278impl<'de, 'a> Visitor<'de> for ValueVisitor<'a> {
279    type Value = Value<'a>;
280
281    fn expecting(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
282        f.write_str("any CBOR-compatible value")
283    }
284
285    visit!(visit_bool, bool);
286
287    visit!(visit_i8, i8);
288    visit!(visit_i16, i16);
289    visit!(visit_i32, i32);
290    visit!(visit_i64, i64);
291    visit!(visit_i128, i128);
292
293    visit!(visit_u8, u8);
294    visit!(visit_u16, u16);
295    visit!(visit_u32, u32);
296    visit!(visit_u64, u64);
297    visit!(visit_u128, u128);
298
299    visit!(visit_f32, f32);
300    visit!(visit_f64, f64);
301
302    fn visit_char<E>(self, v: char) -> Result<Value<'a>, E> {
303        Ok(Value::from(v.to_string()))
304    }
305
306    // visit!(visit_str, &str);
307    fn visit_str<E>(self, v: &str) -> Result<Value<'a>, E> {
308        Ok(Value::from(v.to_string()))
309    }
310
311    visit!(visit_string, String);
312
313    //visit!(visit_bytes, &[u8]);
314    fn visit_bytes<E>(self, v: &[u8]) -> Result<Value<'a>, E> {
315        Ok(Value::from(v.to_vec()))
316    }
317
318    visit!(visit_byte_buf, Vec<u8>);
319
320    fn visit_none<E>(self) -> Result<Value<'a>, E> {
321        Ok(Value::null())
322    }
323
324    fn visit_some<D: de::Deserializer<'de>>(self, deserializer: D) -> Result<Value<'a>, D::Error> {
325        Deserialize::deserialize(deserializer)
326    }
327
328    fn visit_unit<E>(self) -> Result<Value<'a>, E> {
329        Ok(Value::null())
330    }
331
332    fn visit_seq<A: SeqAccess<'de>>(self, mut access: A) -> Result<Value<'a>, A::Error> {
333        let mut elements = Vec::with_capacity(access.size_hint().unwrap_or(0));
334        while let Some(elem) = access.next_element()? {
335            elements.push(elem);
336        }
337        Ok(Value::Array(elements))
338    }
339
340    fn visit_map<A: MapAccess<'de>>(self, mut access: A) -> Result<Value<'a>, A::Error> {
341        let mut map = BTreeMap::new();
342        while let Some((k, v)) = access.next_entry()? {
343            map.insert(k, v);
344        }
345        Ok(Value::Map(map))
346    }
347}
348
349// ---------------------------------------------------------------------------
350// ValueSerializer: Rust → Value
351// ---------------------------------------------------------------------------
352
353/// Serde `Serializer` that produces a CBOR [`Value`].
354struct ValueSerializer<'a>(std::marker::PhantomData<&'a ()>);
355
356macro_rules! serialize {
357    ($method:ident, $type:ty) => {
358        fn $method(self, v: $type) -> Result<Value<'a>, SerdeError> {
359            Ok(Value::from(v))
360        }
361    };
362}
363
364impl<'a> ser::Serializer for ValueSerializer<'a> {
365    type Ok = Value<'a>;
366    type Error = SerdeError;
367
368    type SerializeSeq = SeqBuilder<'a>;
369    type SerializeTuple = SeqBuilder<'a>;
370    type SerializeTupleStruct = SeqBuilder<'a>;
371    type SerializeTupleVariant = TupleVariantBuilder<'a>;
372    type SerializeMap = MapBuilder<'a>;
373    type SerializeStruct = MapBuilder<'a>;
374    type SerializeStructVariant = StructVariantBuilder<'a>;
375
376    fn is_human_readable(&self) -> bool {
377        false
378    }
379
380    serialize!(serialize_bool, bool);
381
382    serialize!(serialize_i8, i8);
383    serialize!(serialize_i16, i16);
384    serialize!(serialize_i32, i32);
385    serialize!(serialize_i64, i64);
386    serialize!(serialize_i128, i128);
387
388    serialize!(serialize_u8, u8);
389    serialize!(serialize_u16, u16);
390    serialize!(serialize_u32, u32);
391    serialize!(serialize_u64, u64);
392    serialize!(serialize_u128, u128);
393
394    serialize!(serialize_f32, f32);
395    serialize!(serialize_f64, f64);
396
397    fn serialize_char(self, v: char) -> Result<Value<'a>, SerdeError> {
398        Ok(Value::from(v.to_string()))
399    }
400
401    fn serialize_str(self, v: &str) -> Result<Value<'a>, SerdeError> {
402        Ok(Value::from(v.to_string()))
403    }
404
405    fn serialize_bytes(self, v: &[u8]) -> Result<Value<'a>, SerdeError> {
406        Ok(Value::from(v.to_vec()))
407    }
408
409    fn serialize_none(self) -> Result<Value<'a>, SerdeError> {
410        Ok(Value::null())
411    }
412
413    fn serialize_some<T: ?Sized + Serialize>(self, value: &T) -> Result<Value<'a>, SerdeError> {
414        value.serialize(self)
415    }
416
417    fn serialize_unit(self) -> Result<Value<'a>, SerdeError> {
418        Ok(Value::null())
419    }
420
421    fn serialize_unit_struct(self, _name: &'static str) -> Result<Value<'a>, SerdeError> {
422        Ok(Value::null())
423    }
424
425    fn serialize_unit_variant(
426        self,
427        _name: &'static str,
428        _variant_index: u32,
429        variant: &'static str,
430    ) -> Result<Value<'a>, SerdeError> {
431        Ok(Value::from(variant))
432    }
433
434    fn serialize_newtype_struct<T: ?Sized + Serialize>(
435        self,
436        _name: &'static str,
437        value: &T,
438    ) -> Result<Value<'a>, SerdeError> {
439        value.serialize(self)
440    }
441
442    fn serialize_newtype_variant<T: ?Sized + Serialize>(
443        self,
444        _name: &'static str,
445        _variant_index: u32,
446        variant: &'static str,
447        value: &T,
448    ) -> Result<Value<'a>, SerdeError> {
449        Ok(Value::map([(variant, Value::serialized(value)?)]))
450    }
451
452    fn serialize_seq(self, len: Option<usize>) -> Result<SeqBuilder<'a>, SerdeError> {
453        Ok(SeqBuilder {
454            elements: Vec::with_capacity(len.unwrap_or(0)),
455        })
456    }
457
458    fn serialize_tuple(self, len: usize) -> Result<SeqBuilder<'a>, SerdeError> {
459        self.serialize_seq(Some(len))
460    }
461
462    fn serialize_tuple_struct(self, _name: &'static str, len: usize) -> Result<SeqBuilder<'a>, SerdeError> {
463        self.serialize_seq(Some(len))
464    }
465
466    fn serialize_tuple_variant(
467        self,
468        _name: &'static str,
469        _variant_index: u32,
470        variant: &'static str,
471        len: usize,
472    ) -> Result<TupleVariantBuilder<'a>, SerdeError> {
473        Ok(TupleVariantBuilder {
474            variant,
475            elements: Vec::with_capacity(len),
476        })
477    }
478
479    fn serialize_map(self, len: Option<usize>) -> Result<MapBuilder<'a>, SerdeError> {
480        let _ = len; // BTreeMap doesn't pre-allocate
481        Ok(MapBuilder {
482            entries: BTreeMap::new(),
483            next_key: None,
484        })
485    }
486
487    fn serialize_struct(self, _name: &'static str, len: usize) -> Result<MapBuilder<'a>, SerdeError> {
488        self.serialize_map(Some(len))
489    }
490
491    fn serialize_struct_variant(
492        self,
493        _name: &'static str,
494        _variant_index: u32,
495        variant: &'static str,
496        _len: usize,
497    ) -> Result<StructVariantBuilder<'a>, SerdeError> {
498        Ok(StructVariantBuilder {
499            variant,
500            entries: BTreeMap::new(),
501        })
502    }
503}
504
505// --- Serializer helpers ---
506
507struct SeqBuilder<'a> {
508    elements: Vec<Value<'a>>,
509}
510
511impl<'a> SerializeSeq for SeqBuilder<'a> {
512    type Ok = Value<'a>;
513    type Error = SerdeError;
514
515    fn serialize_element<T: ?Sized + Serialize>(&mut self, value: &T) -> Result<(), SerdeError> {
516        self.elements.push(Value::serialized(value)?);
517        Ok(())
518    }
519
520    fn end(self) -> Result<Value<'a>, SerdeError> {
521        Ok(Value::Array(self.elements))
522    }
523}
524
525impl<'a> ser::SerializeTuple for SeqBuilder<'a> {
526    type Ok = Value<'a>;
527    type Error = SerdeError;
528
529    fn serialize_element<T: ?Sized + Serialize>(&mut self, value: &T) -> Result<(), SerdeError> {
530        SerializeSeq::serialize_element(self, value)
531    }
532
533    fn end(self) -> Result<Value<'a>, SerdeError> {
534        SerializeSeq::end(self)
535    }
536}
537
538impl<'a> ser::SerializeTupleStruct for SeqBuilder<'a> {
539    type Ok = Value<'a>;
540    type Error = SerdeError;
541
542    fn serialize_field<T: ?Sized + Serialize>(&mut self, value: &T) -> Result<(), SerdeError> {
543        SerializeSeq::serialize_element(self, value)
544    }
545
546    fn end(self) -> Result<Value<'a>, SerdeError> {
547        SerializeSeq::end(self)
548    }
549}
550
551struct TupleVariantBuilder<'a> {
552    variant: &'static str,
553    elements: Vec<Value<'a>>,
554}
555
556impl<'a> ser::SerializeTupleVariant for TupleVariantBuilder<'a> {
557    type Ok = Value<'a>;
558    type Error = SerdeError;
559
560    fn serialize_field<T: ?Sized + Serialize>(&mut self, value: &T) -> Result<(), SerdeError> {
561        self.elements.push(Value::serialized(value)?);
562        Ok(())
563    }
564
565    fn end(self) -> Result<Value<'a>, SerdeError> {
566        Ok(Value::map([(self.variant, self.elements)]))
567    }
568}
569
570struct MapBuilder<'a> {
571    entries: BTreeMap<Value<'a>, Value<'a>>,
572    next_key: Option<Value<'a>>,
573}
574
575impl<'a> SerializeMap for MapBuilder<'a> {
576    type Ok = Value<'a>;
577    type Error = SerdeError;
578
579    fn serialize_key<T: ?Sized + Serialize>(&mut self, key: &T) -> Result<(), SerdeError> {
580        self.next_key = Some(Value::serialized(key)?);
581        Ok(())
582    }
583
584    fn serialize_value<T: ?Sized + Serialize>(&mut self, value: &T) -> Result<(), SerdeError> {
585        let key = self
586            .next_key
587            .take()
588            .ok_or_else(|| SerdeError("serialize_value called before serialize_key".into()))?;
589        self.entries.insert(key, Value::serialized(value)?);
590        Ok(())
591    }
592
593    fn end(self) -> Result<Value<'a>, SerdeError> {
594        Ok(Value::Map(self.entries))
595    }
596}
597
598impl<'a> ser::SerializeStruct for MapBuilder<'a> {
599    type Ok = Value<'a>;
600    type Error = SerdeError;
601
602    fn serialize_field<T: ?Sized + Serialize>(&mut self, key: &'static str, value: &T) -> Result<(), SerdeError> {
603        self.entries.insert(Value::from(key), Value::serialized(value)?);
604        Ok(())
605    }
606
607    fn end(self) -> Result<Value<'a>, SerdeError> {
608        Ok(Value::Map(self.entries))
609    }
610}
611
612struct StructVariantBuilder<'a> {
613    variant: &'static str,
614    entries: BTreeMap<Value<'a>, Value<'a>>,
615}
616
617impl<'a> ser::SerializeStructVariant for StructVariantBuilder<'a> {
618    type Ok = Value<'a>;
619    type Error = SerdeError;
620
621    fn serialize_field<T: ?Sized + Serialize>(&mut self, key: &'static str, value: &T) -> Result<(), SerdeError> {
622        self.entries.insert(Value::from(key), Value::serialized(value)?);
623        Ok(())
624    }
625
626    fn end(self) -> Result<Value<'a>, SerdeError> {
627        Ok(Value::map([(self.variant, self.entries)]))
628    }
629}
630
631// ---------------------------------------------------------------------------
632// ValueDeserializer: &Value → Rust
633// ---------------------------------------------------------------------------
634
635/// Serde `Deserializer` that reads from a CBOR [`Value`] reference.
636struct ValueDeserializer<'de, 'a>(&'de Value<'a>);
637
638macro_rules! deserialize {
639    ($method:ident, $visit:ident) => {
640        fn $method<V: Visitor<'de>>(self, visitor: V) -> Result<V::Value, SerdeError> {
641            visitor.$visit(self.0.try_into()?)
642        }
643    };
644}
645
646impl<'de, 'a> de::Deserializer<'de> for ValueDeserializer<'de, 'a> {
647    type Error = SerdeError;
648
649    fn is_human_readable(&self) -> bool {
650        false
651    }
652
653    fn deserialize_any<V: Visitor<'de>>(self, visitor: V) -> Result<V::Value, SerdeError> {
654        let this = self.0.peeled();
655        if let Value::SimpleValue(sv) = this {
656            if sv.data_type().is_null() {
657                visitor.visit_unit()
658            } else if let Ok(v) = sv.to_bool() {
659                visitor.visit_bool(v)
660            } else {
661                visitor.visit_u8(sv.to_u8())
662            }
663        } else if let Ok(v) = this.to_u64() {
664            visitor.visit_u64(v)
665        } else if let Ok(v) = this.to_i64() {
666            visitor.visit_i64(v)
667        } else if let Ok(v) = this.to_u128() {
668            visitor.visit_u128(v)
669        } else if let Ok(v) = this.to_i128() {
670            visitor.visit_i128(v)
671        } else if let Ok(v) = this.to_f32() {
672            visitor.visit_f32(v)
673        } else if let Ok(v) = this.to_f64() {
674            visitor.visit_f64(v)
675        } else if let Ok(v) = this.as_bytes() {
676            visitor.visit_borrowed_bytes(v)
677        } else if let Ok(v) = this.as_str() {
678            visitor.visit_borrowed_str(v)
679        } else {
680            match this.untagged() {
681                Value::Array(arr) => visitor.visit_seq(SeqAccessImpl(arr.iter())),
682                Value::Map(map) => visitor.visit_map(MapAccessImpl {
683                    iter: map.iter(),
684                    pending_value: None,
685                }),
686                _other => unreachable!(),
687            }
688        }
689    }
690
691    deserialize!(deserialize_bool, visit_bool);
692
693    deserialize!(deserialize_i8, visit_i8);
694    deserialize!(deserialize_i16, visit_i16);
695    deserialize!(deserialize_i32, visit_i32);
696    deserialize!(deserialize_i64, visit_i64);
697    deserialize!(deserialize_i128, visit_i128);
698
699    deserialize!(deserialize_u8, visit_u8);
700    deserialize!(deserialize_u16, visit_u16);
701    deserialize!(deserialize_u32, visit_u32);
702    deserialize!(deserialize_u64, visit_u64);
703    deserialize!(deserialize_u128, visit_u128);
704
705    fn deserialize_f32<V: Visitor<'de>>(self, visitor: V) -> Result<V::Value, SerdeError> {
706        visitor.visit_f32(self.0.to_f64()? as f32)
707    }
708
709    deserialize!(deserialize_f64, visit_f64);
710
711    fn deserialize_char<V: Visitor<'de>>(self, visitor: V) -> Result<V::Value, SerdeError> {
712        let s = self.0.as_str()?;
713        let mut chars = s.chars();
714        let ch = chars.next().ok_or_else(|| SerdeError("empty string for char".into()))?;
715        if chars.next().is_some() {
716            return Err(SerdeError("string contains more than one char".into()));
717        }
718        visitor.visit_char(ch)
719    }
720
721    deserialize!(deserialize_str, visit_borrowed_str);
722    deserialize!(deserialize_string, visit_borrowed_str);
723
724    deserialize!(deserialize_bytes, visit_borrowed_bytes);
725    deserialize!(deserialize_byte_buf, visit_borrowed_bytes);
726
727    fn deserialize_option<V: Visitor<'de>>(self, visitor: V) -> Result<V::Value, SerdeError> {
728        if self.0.untagged().data_type().is_null() {
729            visitor.visit_none()
730        } else {
731            visitor.visit_some(self)
732        }
733    }
734
735    fn deserialize_unit<V: Visitor<'de>>(self, visitor: V) -> Result<V::Value, SerdeError> {
736        if self.0.untagged().data_type().is_null() {
737            visitor.visit_unit()
738        } else {
739            Err(de::Error::custom(format!(
740                "expected null, got {}",
741                self.0.data_type().name()
742            )))
743        }
744    }
745
746    fn deserialize_unit_struct<V: Visitor<'de>>(self, _name: &'static str, visitor: V) -> Result<V::Value, SerdeError> {
747        self.deserialize_unit(visitor)
748    }
749
750    fn deserialize_newtype_struct<V: Visitor<'de>>(
751        self,
752        _name: &'static str,
753        visitor: V,
754    ) -> Result<V::Value, SerdeError> {
755        visitor.visit_newtype_struct(self)
756    }
757
758    fn deserialize_seq<V: Visitor<'de>>(self, visitor: V) -> Result<V::Value, SerdeError> {
759        match self.0.untagged() {
760            Value::Array(arr) => visitor.visit_seq(SeqAccessImpl(arr.iter())),
761            other => Err(de::Error::custom(format!(
762                "expected array, got {}",
763                other.data_type().name()
764            ))),
765        }
766    }
767
768    fn deserialize_tuple<V: Visitor<'de>>(self, _len: usize, visitor: V) -> Result<V::Value, SerdeError> {
769        self.deserialize_seq(visitor)
770    }
771
772    fn deserialize_tuple_struct<V: Visitor<'de>>(
773        self,
774        _name: &'static str,
775        _len: usize,
776        visitor: V,
777    ) -> Result<V::Value, SerdeError> {
778        self.deserialize_seq(visitor)
779    }
780
781    fn deserialize_map<V: Visitor<'de>>(self, visitor: V) -> Result<V::Value, SerdeError> {
782        match self.0.untagged() {
783            Value::Map(map) => visitor.visit_map(MapAccessImpl {
784                iter: map.iter(),
785                pending_value: None,
786            }),
787            other => Err(de::Error::custom(format!(
788                "expected map, got {}",
789                other.data_type().name()
790            ))),
791        }
792    }
793
794    fn deserialize_struct<V: Visitor<'de>>(
795        self,
796        _name: &'static str,
797        _fields: &'static [&'static str],
798        visitor: V,
799    ) -> Result<V::Value, SerdeError> {
800        self.deserialize_map(visitor)
801    }
802
803    fn deserialize_identifier<V: Visitor<'de>>(self, visitor: V) -> Result<V::Value, SerdeError> {
804        match self.0.untagged() {
805            Value::TextString(s) => visitor.visit_borrowed_str(s),
806            other => Err(de::Error::custom(format!(
807                "expected string identifier, got {}",
808                other.data_type().name()
809            ))),
810        }
811    }
812
813    fn deserialize_ignored_any<V: Visitor<'de>>(self, visitor: V) -> Result<V::Value, SerdeError> {
814        visitor.visit_unit()
815    }
816
817    fn deserialize_enum<V: Visitor<'de>>(
818        self,
819        _name: &'static str,
820        _variants: &'static [&'static str],
821        visitor: V,
822    ) -> Result<V::Value, SerdeError> {
823        match self.0.untagged() {
824            // Unit variant: "VariantName"
825            Value::TextString(variant) => visitor.visit_enum(de::value::StrDeserializer::new(variant)),
826
827            // Newtype / tuple / struct variant: { "VariantName": payload }
828            Value::Map(map) if map.len() == 1 => {
829                let (k, v) = map.iter().next().unwrap();
830                let variant = k.as_str()?;
831                visitor.visit_enum(EnumAccessImpl { variant, value: v })
832            }
833
834            other => Err(de::Error::custom(format!(
835                "expected string or single-entry map for enum, got {}",
836                other.data_type().name()
837            ))),
838        }
839    }
840}
841
842// ---------------------------------------------------------------------------
843// SeqAccess / MapAccess
844// ---------------------------------------------------------------------------
845
846struct SeqAccessImpl<'de, 'a>(std::slice::Iter<'de, Value<'a>>);
847
848impl<'de, 'a> SeqAccess<'de> for SeqAccessImpl<'de, 'a> {
849    type Error = SerdeError;
850
851    fn next_element_seed<T: DeserializeSeed<'de>>(&mut self, seed: T) -> Result<Option<T::Value>, SerdeError> {
852        match self.0.next() {
853            Some(v) => seed.deserialize(ValueDeserializer(v)).map(Some),
854            None => Ok(None),
855        }
856    }
857
858    fn size_hint(&self) -> Option<usize> {
859        Some(self.0.len())
860    }
861}
862
863struct MapAccessImpl<'de, 'a> {
864    iter: std::collections::btree_map::Iter<'de, Value<'a>, Value<'a>>,
865    pending_value: Option<&'de Value<'a>>,
866}
867
868impl<'de, 'a> MapAccess<'de> for MapAccessImpl<'de, 'a> {
869    type Error = SerdeError;
870
871    fn next_key_seed<K: DeserializeSeed<'de>>(&mut self, seed: K) -> Result<Option<K::Value>, SerdeError> {
872        match self.iter.next() {
873            Some((k, v)) => {
874                self.pending_value = Some(v);
875                seed.deserialize(ValueDeserializer(k)).map(Some)
876            }
877            None => Ok(None),
878        }
879    }
880
881    fn next_value_seed<V: DeserializeSeed<'de>>(&mut self, seed: V) -> Result<V::Value, SerdeError> {
882        let v = self
883            .pending_value
884            .take()
885            .ok_or_else(|| SerdeError("next_value_seed called before next_key_seed".into()))?;
886        seed.deserialize(ValueDeserializer(v))
887    }
888
889    fn size_hint(&self) -> Option<usize> {
890        Some(self.iter.len())
891    }
892}
893
894// ---------------------------------------------------------------------------
895// EnumAccess / VariantAccess
896// ---------------------------------------------------------------------------
897
898struct EnumAccessImpl<'de, 'a> {
899    variant: &'de str,
900    value: &'de Value<'a>,
901}
902
903impl<'de, 'a> de::EnumAccess<'de> for EnumAccessImpl<'de, 'a> {
904    type Error = SerdeError;
905    type Variant = VariantAccessImpl<'de, 'a>;
906
907    fn variant_seed<V: DeserializeSeed<'de>>(self, seed: V) -> Result<(V::Value, Self::Variant), SerdeError> {
908        let variant = seed.deserialize(de::value::StrDeserializer::<SerdeError>::new(self.variant))?;
909        Ok((variant, VariantAccessImpl(self.value)))
910    }
911}
912
913struct VariantAccessImpl<'de, 'a>(&'de Value<'a>);
914
915impl<'de, 'a> de::VariantAccess<'de> for VariantAccessImpl<'de, 'a> {
916    type Error = SerdeError;
917
918    fn unit_variant(self) -> Result<(), SerdeError> {
919        if self.0.untagged().data_type().is_null() {
920            Ok(())
921        } else {
922            Err(SerdeError(format!(
923                "expected null for unit variant, got {}",
924                self.0.data_type().name()
925            )))
926        }
927    }
928
929    fn newtype_variant_seed<T: DeserializeSeed<'de>>(self, seed: T) -> Result<T::Value, SerdeError> {
930        seed.deserialize(ValueDeserializer(self.0))
931    }
932
933    fn tuple_variant<V: Visitor<'de>>(self, _len: usize, visitor: V) -> Result<V::Value, SerdeError> {
934        ValueDeserializer(self.0).deserialize_seq(visitor)
935    }
936
937    fn struct_variant<V: Visitor<'de>>(
938        self,
939        _fields: &'static [&'static str],
940        visitor: V,
941    ) -> Result<V::Value, SerdeError> {
942        ValueDeserializer(self.0).deserialize_map(visitor)
943    }
944}
945
946// ---------------------------------------------------------------------------
947// Tests
948// ---------------------------------------------------------------------------
949
950#[cfg(test)]
951mod tests {
952    use super::*;
953    use crate::{array, map};
954
955    // --- Round-trip: primitives ---
956
957    #[test]
958    fn round_trip_bool() {
959        let v = Value::serialized(&true).unwrap();
960        assert!(v.to_bool().unwrap());
961        assert!(v.deserialized::<bool>().unwrap());
962
963        let v = Value::serialized(&false).unwrap();
964        assert!(!v.deserialized::<bool>().unwrap());
965    }
966
967    #[test]
968    fn round_trip_unsigned() {
969        let v = Value::serialized(&42_u32).unwrap();
970        assert_eq!(v.to_u64().unwrap(), 42);
971        assert_eq!(v.deserialized::<u32>().unwrap(), 42);
972    }
973
974    #[test]
975    fn round_trip_signed_positive() {
976        let v = Value::serialized(&100_i64).unwrap();
977        assert_eq!(v.deserialized::<i64>().unwrap(), 100);
978    }
979
980    #[test]
981    fn round_trip_signed_negative() {
982        let v = Value::serialized(&-42_i32).unwrap();
983        assert_eq!(v.deserialized::<i32>().unwrap(), -42);
984    }
985
986    #[test]
987    fn round_trip_float() {
988        let v = Value::serialized(&3.42_f64).unwrap();
989        assert_eq!(v.deserialized::<f64>().unwrap(), 3.42);
990    }
991
992    #[test]
993    fn round_trip_string() {
994        let v = Value::serialized("hello").unwrap();
995        assert_eq!(v.as_str().unwrap(), "hello");
996        assert_eq!(v.deserialized::<String>().unwrap(), "hello");
997    }
998
999    #[test]
1000    fn round_trip_bytes() {
1001        let data = vec![1_u8, 2, 3];
1002        let v = Value::serialized(&serde_bytes::Bytes::new(&data)).unwrap();
1003        assert_eq!(v.as_bytes().unwrap(), &[1, 2, 3]);
1004        let back: serde_bytes::ByteBuf = v.deserialized().unwrap();
1005        assert_eq!(back.as_ref(), &[1, 2, 3]);
1006    }
1007
1008    #[test]
1009    fn round_trip_none() {
1010        let v = Value::serialized(&Option::<i32>::None).unwrap();
1011        assert!(v.data_type().is_null());
1012        assert_eq!(v.deserialized::<Option<i32>>().unwrap(), None);
1013    }
1014
1015    #[test]
1016    fn round_trip_some() {
1017        let v = Value::serialized(&Some(42_u32)).unwrap();
1018        assert_eq!(v.deserialized::<Option<u32>>().unwrap(), Some(42));
1019    }
1020
1021    // --- Round-trip: collections ---
1022
1023    #[test]
1024    fn round_trip_vec() {
1025        let v = Value::serialized(&vec![1_u32, 2, 3]).unwrap();
1026        assert_eq!(v.deserialized::<Vec<u32>>().unwrap(), vec![1, 2, 3]);
1027    }
1028
1029    #[test]
1030    fn round_trip_map() {
1031        let mut m = std::collections::BTreeMap::new();
1032        m.insert("a".to_string(), 1_u32);
1033        m.insert("b".to_string(), 2);
1034        let v = Value::serialized(&m).unwrap();
1035        let back: std::collections::BTreeMap<String, u32> = v.deserialized().unwrap();
1036        assert_eq!(back, m);
1037    }
1038
1039    // --- Round-trip: structs ---
1040
1041    #[test]
1042    fn round_trip_struct() {
1043        #[derive(Serialize, Deserialize, Debug, PartialEq)]
1044        struct Point {
1045            x: i32,
1046            y: i32,
1047        }
1048
1049        let p = Point { x: 10, y: -20 };
1050        let v = Value::serialized(&p).unwrap();
1051        assert_eq!(v["x"].to_i32().unwrap(), 10);
1052        assert_eq!(v["y"].to_i32().unwrap(), -20);
1053        let back: Point = v.deserialized().unwrap();
1054        assert_eq!(back, p);
1055    }
1056
1057    #[test]
1058    fn round_trip_nested_struct() {
1059        #[derive(Serialize, Deserialize, Debug, PartialEq)]
1060        struct Inner {
1061            value: String,
1062        }
1063        #[derive(Serialize, Deserialize, Debug, PartialEq)]
1064        struct Outer {
1065            name: String,
1066            inner: Inner,
1067        }
1068
1069        let o = Outer {
1070            name: "test".into(),
1071            inner: Inner { value: "nested".into() },
1072        };
1073        let v = Value::serialized(&o).unwrap();
1074        let back: Outer = v.deserialized().unwrap();
1075        assert_eq!(back, o);
1076    }
1077
1078    // --- Round-trip: enums ---
1079
1080    #[test]
1081    fn round_trip_unit_variant() {
1082        #[derive(Serialize, Deserialize, Debug, PartialEq)]
1083        enum Color {
1084            Red,
1085            Green,
1086            Blue,
1087        }
1088
1089        let v = Value::serialized(&Color::Green).unwrap();
1090        assert_eq!(v.as_str().unwrap(), "Green");
1091        let back: Color = v.deserialized().unwrap();
1092        assert_eq!(back, Color::Green);
1093    }
1094
1095    #[test]
1096    fn round_trip_newtype_variant() {
1097        #[derive(Serialize, Deserialize, Debug, PartialEq)]
1098        enum Shape {
1099            Circle(f64),
1100            Square(f64),
1101        }
1102
1103        let v = Value::serialized(&Shape::Circle(2.5)).unwrap();
1104        let back: Shape = v.deserialized().unwrap();
1105        assert_eq!(back, Shape::Circle(2.5));
1106    }
1107
1108    #[test]
1109    fn round_trip_struct_variant() {
1110        #[derive(Serialize, Deserialize, Debug, PartialEq)]
1111        enum Message {
1112            Quit,
1113            Move { x: i32, y: i32 },
1114        }
1115
1116        let v = Value::serialized(&Message::Move { x: 1, y: 2 }).unwrap();
1117        let back: Message = v.deserialized().unwrap();
1118        assert_eq!(back, Message::Move { x: 1, y: 2 });
1119    }
1120
1121    #[test]
1122    fn round_trip_tuple_variant() {
1123        #[derive(Serialize, Deserialize, Debug, PartialEq)]
1124        enum Pair {
1125            Two(i32, i32),
1126        }
1127
1128        let v = Value::serialized(&Pair::Two(3, 4)).unwrap();
1129        let back: Pair = v.deserialized().unwrap();
1130        assert_eq!(back, Pair::Two(3, 4));
1131    }
1132
1133    // --- Deserialize from hand-built Value ---
1134
1135    #[test]
1136    fn deserialize_hand_built() {
1137        #[derive(Deserialize, Debug, PartialEq)]
1138        struct Record {
1139            id: u64,
1140            name: String,
1141            active: bool,
1142        }
1143
1144        let v = map! {
1145            "id" => 42,
1146            "name" => "alice",
1147            "active" => true,
1148        };
1149
1150        let r: Record = v.deserialized().unwrap();
1151        assert_eq!(
1152            r,
1153            Record {
1154                id: 42,
1155                name: "alice".into(),
1156                active: true,
1157            }
1158        );
1159    }
1160
1161    // --- Serialize Value itself ---
1162
1163    #[test]
1164    fn serialize_value_null() {
1165        let v = Value::null();
1166        let json = serde_json::to_string(&v).unwrap();
1167        assert_eq!(json, "null");
1168    }
1169
1170    #[test]
1171    fn serialize_value_integer() {
1172        let v = Value::from(42_u64);
1173        let json = serde_json::to_string(&v).unwrap();
1174        assert_eq!(json, "42");
1175    }
1176
1177    #[test]
1178    fn serialize_value_negative() {
1179        let v = Value::from(-10_i64);
1180        let json = serde_json::to_string(&v).unwrap();
1181        assert_eq!(json, "-10");
1182    }
1183
1184    #[test]
1185    fn serialize_value_array() {
1186        let v = array![1, 2, 3];
1187        let json = serde_json::to_string(&v).unwrap();
1188        assert_eq!(json, "[1,2,3]");
1189    }
1190
1191    #[test]
1192    fn serialize_value_map() {
1193        let v = map! { "a" => 1 };
1194        let json = serde_json::to_string(&v).unwrap();
1195        assert_eq!(json, "{\"a\":1}");
1196    }
1197
1198    // --- Tags are transparent ---
1199
1200    #[test]
1201    fn tagged_value_transparent_deserialize() {
1202        // Tag wrapping an integer should deserialize as if untagged.
1203        let v = Value::tag(42, 100_u64);
1204        let n: u64 = v.deserialized().unwrap();
1205        assert_eq!(n, 100);
1206    }
1207
1208    #[test]
1209    fn tagged_value_transparent_serialize() {
1210        let v = Value::tag(42, 100_u64);
1211        let json = serde_json::to_string(&v).unwrap();
1212        assert_eq!(json, "100");
1213    }
1214
1215    // --- Edge cases ---
1216
1217    #[test]
1218    fn large_negative_i128() {
1219        let big = i64::MIN as i128 - 1;
1220        let v = Value::serialized(&big).unwrap();
1221        let back: i128 = v.deserialized().unwrap();
1222        assert_eq!(back, big);
1223    }
1224
1225    #[test]
1226    fn unit_type() {
1227        let v = Value::serialized(&()).unwrap();
1228        assert!(v.data_type().is_null());
1229        v.deserialized::<()>().unwrap();
1230    }
1231
1232    #[test]
1233    fn char_round_trip() {
1234        let v = Value::serialized(&'Z').unwrap();
1235        assert_eq!(v.deserialized::<char>().unwrap(), 'Z');
1236    }
1237
1238    #[test]
1239    fn empty_vec() {
1240        let v = Value::serialized(&Vec::<i32>::new()).unwrap();
1241        assert_eq!(v.deserialized::<Vec<i32>>().unwrap(), Vec::<i32>::new());
1242    }
1243
1244    #[test]
1245    fn empty_map() {
1246        let v = Value::serialized(&std::collections::BTreeMap::<String, i32>::new()).unwrap();
1247        let back: std::collections::BTreeMap<String, i32> = v.deserialized().unwrap();
1248        assert!(back.is_empty());
1249    }
1250
1251    #[test]
1252    fn deserialize_error_type_mismatch() {
1253        let v = Value::from("not a number");
1254        let result = v.deserialized::<u32>();
1255        assert!(result.is_err());
1256    }
1257
1258    #[test]
1259    fn deserialize_error_overflow() {
1260        let v = Value::from(1000_u64);
1261        let result = v.deserialized::<u8>();
1262        assert!(result.is_err());
1263    }
1264
1265    #[test]
1266    fn optional_field() {
1267        #[derive(Serialize, Deserialize, Debug, PartialEq)]
1268        struct Config {
1269            name: String,
1270            port: Option<u16>,
1271        }
1272
1273        let with = Value::serialized(&Config {
1274            name: "srv".into(),
1275            port: Some(8080),
1276        })
1277        .unwrap();
1278        let back: Config = with.deserialized().unwrap();
1279        assert_eq!(back.port, Some(8080));
1280
1281        let without = Value::serialized(&Config {
1282            name: "srv".into(),
1283            port: None,
1284        })
1285        .unwrap();
1286        let back: Config = without.deserialized().unwrap();
1287        assert_eq!(back.port, None);
1288    }
1289
1290    #[test]
1291    fn tuple() {
1292        let v = Value::serialized(&(1_u32, "hello", true)).unwrap();
1293        let back: (u32, String, bool) = v.deserialized().unwrap();
1294        assert_eq!(back, (1, "hello".into(), true));
1295    }
1296
1297    /// --- Borrowed values ---
1298
1299    #[test]
1300    fn deserialize_borrowed() {
1301        let v = map! { "text" => "Rust", "bytes" => b"CBOR" };
1302
1303        #[derive(Deserialize)]
1304        struct Example<'a> {
1305            text: &'a str,
1306            bytes: &'a [u8],
1307        }
1308
1309        let s: Example = v.deserialized().unwrap();
1310
1311        assert_eq!(s.text, "Rust");
1312        assert_eq!(s.bytes, b"CBOR");
1313    }
1314
1315    // --- SerdeError public field ---
1316
1317    #[test]
1318    fn serde_error_message_accessible() {
1319        let v = Value::from("not a number");
1320        let err = v.deserialized::<u32>().unwrap_err();
1321        // The public String field is directly readable.
1322        assert!(!err.0.is_empty());
1323        assert_eq!(err.to_string(), err.0);
1324    }
1325
1326    // --- is_human_readable is false ---
1327
1328    #[test]
1329    fn serializer_is_not_human_readable() {
1330        // A type that reports back the serializer's human-readable flag.
1331        struct ProbeFlag;
1332        impl Serialize for ProbeFlag {
1333            fn serialize<S: ser::Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
1334                let human_readable = serializer.is_human_readable();
1335                serializer.serialize_bool(human_readable)
1336            }
1337        }
1338
1339        let v = Value::serialized(&ProbeFlag).unwrap();
1340        assert!(!v.to_bool().unwrap());
1341    }
1342
1343    #[test]
1344    fn deserializer_is_not_human_readable() {
1345        // A type that captures the deserializer's human-readable flag.
1346        #[derive(Debug)]
1347        struct ProbeFlag(bool);
1348        impl<'de> Deserialize<'de> for ProbeFlag {
1349            fn deserialize<D: de::Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
1350                Ok(ProbeFlag(deserializer.is_human_readable()))
1351            }
1352        }
1353
1354        let probe: ProbeFlag = Value::null().deserialized().unwrap();
1355        assert!(!probe.0);
1356    }
1357
1358    // --- Deserialize Value from JSON (proves Deserialize impl works) ---
1359
1360    #[test]
1361    fn deserialize_value_from_json() {
1362        let v: Value = serde_json::from_str(r#"{"key": [1, 2, 3]}"#).unwrap();
1363        let arr = v["key"].as_array().unwrap();
1364        assert_eq!(arr.len(), 3);
1365        assert_eq!(arr[0].to_u32().unwrap(), 1);
1366    }
1367}