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