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