Skip to main content

toml/
value.rs

1//! Definition of a TOML [value][Value]
2
3use alloc::collections::BTreeMap;
4use alloc::vec;
5use core::fmt;
6use core::hash::Hash;
7use core::mem::discriminant;
8use core::ops;
9#[cfg(feature = "std")]
10use std::collections::HashMap;
11
12use serde_core::de;
13use serde_core::de::IntoDeserializer;
14use serde_core::ser;
15
16use crate::alloc_prelude::*;
17
18pub use toml_datetime::{Date, Datetime, DatetimeParseError, Offset, Time};
19
20/// Type representing a TOML array, payload of the `Value::Array` variant
21pub type Array = Vec<Value>;
22
23#[doc(no_inline)]
24pub use crate::Table;
25
26/// Representation of a TOML value.
27#[derive(PartialEq, Clone, Debug)]
28pub enum Value {
29    /// Represents a TOML string
30    String(String),
31    /// Represents a TOML integer
32    Integer(i64),
33    /// Represents a TOML float
34    Float(f64),
35    /// Represents a TOML boolean
36    Boolean(bool),
37    /// Represents a TOML datetime
38    Datetime(Datetime),
39    /// Represents a TOML array
40    Array(Array),
41    /// Represents a TOML table
42    Table(Table),
43}
44
45impl Value {
46    /// Convert a `T` into `toml::Value` which is an enum that can represent
47    /// any valid TOML data.
48    ///
49    /// This conversion can fail if `T`'s implementation of `Serialize` decides to
50    /// fail, or if `T` contains a map with non-string keys.
51    pub fn try_from<T>(value: T) -> Result<Self, crate::ser::Error>
52    where
53        T: ser::Serialize,
54    {
55        value.serialize(ValueSerializer)
56    }
57
58    /// Interpret a `toml::Value` as an instance of type `T`.
59    ///
60    /// This conversion can fail if the structure of the `Value` does not match the
61    /// structure expected by `T`, for example if `T` is a struct type but the
62    /// `Value` contains something other than a TOML table. It can also fail if the
63    /// structure is correct but `T`'s implementation of `Deserialize` decides that
64    /// something is wrong with the data, for example required struct fields are
65    /// missing from the TOML map or some number is too big to fit in the expected
66    /// primitive type.
67    pub fn try_into<'de, T>(self) -> Result<T, crate::de::Error>
68    where
69        T: de::Deserialize<'de>,
70    {
71        de::Deserialize::deserialize(self)
72    }
73
74    /// Index into a TOML array or map. A string index can be used to access a
75    /// value in a map, and a usize index can be used to access an element of an
76    /// array.
77    ///
78    /// Returns `None` if the type of `self` does not match the type of the
79    /// index, for example if the index is a string and `self` is an array or a
80    /// number. Also returns `None` if the given key does not exist in the map
81    /// or the given index is not within the bounds of the array.
82    pub fn get<I: Index>(&self, index: I) -> Option<&Self> {
83        index.index(self)
84    }
85
86    /// Mutably index into a TOML array or map. A string index can be used to
87    /// access a value in a map, and a usize index can be used to access an
88    /// element of an array.
89    ///
90    /// Returns `None` if the type of `self` does not match the type of the
91    /// index, for example if the index is a string and `self` is an array or a
92    /// number. Also returns `None` if the given key does not exist in the map
93    /// or the given index is not within the bounds of the array.
94    pub fn get_mut<I: Index>(&mut self, index: I) -> Option<&mut Self> {
95        index.index_mut(self)
96    }
97
98    /// Extracts the integer value if it is an integer.
99    pub fn as_integer(&self) -> Option<i64> {
100        match *self {
101            Self::Integer(i) => Some(i),
102            _ => None,
103        }
104    }
105
106    /// Tests whether this value is an integer.
107    pub fn is_integer(&self) -> bool {
108        self.as_integer().is_some()
109    }
110
111    /// Extracts the float value if it is a float.
112    pub fn as_float(&self) -> Option<f64> {
113        match *self {
114            Self::Float(f) => Some(f),
115            _ => None,
116        }
117    }
118
119    /// Tests whether this value is a float.
120    pub fn is_float(&self) -> bool {
121        self.as_float().is_some()
122    }
123
124    /// Extracts the boolean value if it is a boolean.
125    pub fn as_bool(&self) -> Option<bool> {
126        match *self {
127            Self::Boolean(b) => Some(b),
128            _ => None,
129        }
130    }
131
132    /// Tests whether this value is a boolean.
133    pub fn is_bool(&self) -> bool {
134        self.as_bool().is_some()
135    }
136
137    /// Extracts the string of this value if it is a string.
138    pub fn as_str(&self) -> Option<&str> {
139        match *self {
140            Self::String(ref s) => Some(&**s),
141            _ => None,
142        }
143    }
144
145    /// Tests if this value is a string.
146    pub fn is_str(&self) -> bool {
147        self.as_str().is_some()
148    }
149
150    /// Extracts the datetime value if it is a datetime.
151    ///
152    /// Note that a parsed TOML value will only contain ISO 8601 dates. An
153    /// example date is:
154    ///
155    /// ```notrust
156    /// 1979-05-27T07:32:00Z
157    /// ```
158    pub fn as_datetime(&self) -> Option<&Datetime> {
159        match *self {
160            Self::Datetime(ref s) => Some(s),
161            _ => None,
162        }
163    }
164
165    /// Tests whether this value is a datetime.
166    pub fn is_datetime(&self) -> bool {
167        self.as_datetime().is_some()
168    }
169
170    /// Extracts the array value if it is an array.
171    pub fn as_array(&self) -> Option<&Vec<Self>> {
172        match *self {
173            Self::Array(ref s) => Some(s),
174            _ => None,
175        }
176    }
177
178    /// Extracts the array value if it is an array.
179    pub fn as_array_mut(&mut self) -> Option<&mut Vec<Self>> {
180        match *self {
181            Self::Array(ref mut s) => Some(s),
182            _ => None,
183        }
184    }
185
186    /// Tests whether this value is an array.
187    pub fn is_array(&self) -> bool {
188        self.as_array().is_some()
189    }
190
191    /// Extracts the table value if it is a table.
192    pub fn as_table(&self) -> Option<&Table> {
193        match *self {
194            Self::Table(ref s) => Some(s),
195            _ => None,
196        }
197    }
198
199    /// Extracts the table value if it is a table.
200    pub fn as_table_mut(&mut self) -> Option<&mut Table> {
201        match *self {
202            Self::Table(ref mut s) => Some(s),
203            _ => None,
204        }
205    }
206
207    /// Tests whether this value is a table.
208    pub fn is_table(&self) -> bool {
209        self.as_table().is_some()
210    }
211
212    /// Tests whether this and another value have the same type.
213    pub fn same_type(&self, other: &Self) -> bool {
214        discriminant(self) == discriminant(other)
215    }
216
217    /// Returns a human-readable representation of the type of this value.
218    pub fn type_str(&self) -> &'static str {
219        match *self {
220            Self::String(..) => "string",
221            Self::Integer(..) => "integer",
222            Self::Float(..) => "float",
223            Self::Boolean(..) => "boolean",
224            Self::Datetime(..) => "datetime",
225            Self::Array(..) => "array",
226            Self::Table(..) => "table",
227        }
228    }
229}
230
231impl<I> ops::Index<I> for Value
232where
233    I: Index,
234{
235    type Output = Self;
236
237    fn index(&self, index: I) -> &Self {
238        self.get(index).expect("index not found")
239    }
240}
241
242impl<I> ops::IndexMut<I> for Value
243where
244    I: Index,
245{
246    fn index_mut(&mut self, index: I) -> &mut Self {
247        self.get_mut(index).expect("index not found")
248    }
249}
250
251impl<'a> From<&'a str> for Value {
252    #[inline]
253    fn from(val: &'a str) -> Self {
254        Self::String(val.to_owned())
255    }
256}
257
258impl<V: Into<Self>> From<Vec<V>> for Value {
259    fn from(val: Vec<V>) -> Self {
260        Self::Array(val.into_iter().map(|v| v.into()).collect())
261    }
262}
263
264impl<S: Into<String>, V: Into<Self>> From<BTreeMap<S, V>> for Value {
265    fn from(val: BTreeMap<S, V>) -> Self {
266        let table = val.into_iter().map(|(s, v)| (s.into(), v.into())).collect();
267
268        Self::Table(table)
269    }
270}
271
272#[cfg(feature = "std")]
273impl<S: Into<String> + Hash + Eq, V: Into<Self>> From<HashMap<S, V>> for Value {
274    fn from(val: HashMap<S, V>) -> Self {
275        let table = val.into_iter().map(|(s, v)| (s.into(), v.into())).collect();
276
277        Self::Table(table)
278    }
279}
280
281macro_rules! impl_into_value {
282    ($variant:ident : $T:ty) => {
283        impl From<$T> for Value {
284            #[inline]
285            fn from(val: $T) -> Value {
286                Value::$variant(val.into())
287            }
288        }
289    };
290}
291
292impl_into_value!(String: String);
293impl_into_value!(Integer: i64);
294impl_into_value!(Integer: i32);
295impl_into_value!(Integer: i8);
296impl_into_value!(Integer: u8);
297impl_into_value!(Integer: u32);
298impl_into_value!(Float: f64);
299impl_into_value!(Float: f32);
300impl_into_value!(Boolean: bool);
301impl_into_value!(Datetime: Datetime);
302impl_into_value!(Table: Table);
303
304/// Types that can be used to index a `toml::Value`
305///
306/// Currently this is implemented for `usize` to index arrays and `str` to index
307/// tables.
308///
309/// This trait is sealed and not intended for implementation outside of the
310/// `toml` crate.
311pub trait Index: Sealed {
312    #[doc(hidden)]
313    fn index<'a>(&self, val: &'a Value) -> Option<&'a Value>;
314    #[doc(hidden)]
315    fn index_mut<'a>(&self, val: &'a mut Value) -> Option<&'a mut Value>;
316}
317
318/// An implementation detail that should not be implemented, this will change in
319/// the future and break code otherwise.
320#[doc(hidden)]
321pub trait Sealed {}
322impl Sealed for usize {}
323impl Sealed for str {}
324impl Sealed for String {}
325impl<T: Sealed + ?Sized> Sealed for &T {}
326
327impl Index for usize {
328    fn index<'a>(&self, val: &'a Value) -> Option<&'a Value> {
329        match *val {
330            Value::Array(ref a) => a.get(*self),
331            _ => None,
332        }
333    }
334
335    fn index_mut<'a>(&self, val: &'a mut Value) -> Option<&'a mut Value> {
336        match *val {
337            Value::Array(ref mut a) => a.get_mut(*self),
338            _ => None,
339        }
340    }
341}
342
343impl Index for str {
344    fn index<'a>(&self, val: &'a Value) -> Option<&'a Value> {
345        match *val {
346            Value::Table(ref a) => a.get(self),
347            _ => None,
348        }
349    }
350
351    fn index_mut<'a>(&self, val: &'a mut Value) -> Option<&'a mut Value> {
352        match *val {
353            Value::Table(ref mut a) => a.get_mut(self),
354            _ => None,
355        }
356    }
357}
358
359impl Index for String {
360    fn index<'a>(&self, val: &'a Value) -> Option<&'a Value> {
361        self[..].index(val)
362    }
363
364    fn index_mut<'a>(&self, val: &'a mut Value) -> Option<&'a mut Value> {
365        self[..].index_mut(val)
366    }
367}
368
369impl<T> Index for &T
370where
371    T: Index + ?Sized,
372{
373    fn index<'a>(&self, val: &'a Value) -> Option<&'a Value> {
374        (**self).index(val)
375    }
376
377    fn index_mut<'a>(&self, val: &'a mut Value) -> Option<&'a mut Value> {
378        (**self).index_mut(val)
379    }
380}
381
382#[cfg(feature = "display")]
383impl fmt::Display for Value {
384    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
385        use serde_core::Serialize as _;
386
387        let mut output = String::new();
388        let serializer = crate::ser::ValueSerializer::new(&mut output);
389        self.serialize(serializer).unwrap();
390        output.fmt(f)
391    }
392}
393
394#[cfg(feature = "parse")]
395impl core::str::FromStr for Value {
396    type Err = crate::de::Error;
397    fn from_str(s: &str) -> Result<Self, Self::Err> {
398        use serde_core::Deserialize as _;
399        Self::deserialize(crate::de::ValueDeserializer::parse(s)?)
400    }
401}
402
403impl ser::Serialize for Value {
404    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
405    where
406        S: ser::Serializer,
407    {
408        match *self {
409            Self::String(ref s) => serializer.serialize_str(s),
410            Self::Integer(i) => serializer.serialize_i64(i),
411            Self::Float(f) => serializer.serialize_f64(f),
412            Self::Boolean(b) => serializer.serialize_bool(b),
413            Self::Datetime(ref s) => s.serialize(serializer),
414            Self::Array(ref a) => a.serialize(serializer),
415            Self::Table(ref t) => t.serialize(serializer),
416        }
417    }
418}
419
420impl<'de> de::Deserialize<'de> for Value {
421    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
422    where
423        D: de::Deserializer<'de>,
424    {
425        struct ValueVisitor;
426
427        impl<'de> de::Visitor<'de> for ValueVisitor {
428            type Value = Value;
429
430            fn expecting(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
431                formatter.write_str("any valid TOML value")
432            }
433
434            fn visit_bool<E>(self, value: bool) -> Result<Value, E> {
435                Ok(Value::Boolean(value))
436            }
437
438            fn visit_i64<E>(self, value: i64) -> Result<Value, E> {
439                Ok(Value::Integer(value))
440            }
441
442            fn visit_u64<E: de::Error>(self, value: u64) -> Result<Value, E> {
443                if i64::try_from(value).is_ok() {
444                    Ok(Value::Integer(value as i64))
445                } else {
446                    Err(de::Error::custom("u64 value was too large"))
447                }
448            }
449
450            fn visit_u32<E>(self, value: u32) -> Result<Value, E> {
451                Ok(Value::Integer(value.into()))
452            }
453
454            fn visit_i32<E>(self, value: i32) -> Result<Value, E> {
455                Ok(Value::Integer(value.into()))
456            }
457
458            fn visit_f64<E>(self, value: f64) -> Result<Value, E> {
459                Ok(Value::Float(value))
460            }
461
462            fn visit_str<E>(self, value: &str) -> Result<Value, E> {
463                Ok(Value::String(value.into()))
464            }
465
466            fn visit_string<E>(self, value: String) -> Result<Value, E> {
467                Ok(Value::String(value))
468            }
469
470            fn visit_some<D>(self, deserializer: D) -> Result<Value, D::Error>
471            where
472                D: de::Deserializer<'de>,
473            {
474                de::Deserialize::deserialize(deserializer)
475            }
476
477            fn visit_seq<V>(self, mut visitor: V) -> Result<Value, V::Error>
478            where
479                V: de::SeqAccess<'de>,
480            {
481                let mut vec = Vec::new();
482                while let Some(elem) = visitor.next_element()? {
483                    vec.push(elem);
484                }
485                Ok(Value::Array(vec))
486            }
487
488            fn visit_map<V>(self, mut visitor: V) -> Result<Value, V::Error>
489            where
490                V: de::MapAccess<'de>,
491            {
492                let key = match toml_datetime::de::VisitMap::next_key_seed(&mut visitor)? {
493                    Some(toml_datetime::de::VisitMap::Datetime(datetime)) => {
494                        return Ok(Value::Datetime(datetime));
495                    }
496                    None => return Ok(Value::Table(Table::new())),
497                    Some(toml_datetime::de::VisitMap::Key(key)) => key,
498                };
499                let mut map = Table::new();
500                map.insert(key.into_owned(), visitor.next_value()?);
501                while let Some(key) = visitor.next_key::<String>()? {
502                    match map.entry(key) {
503                        crate::map::Entry::Vacant(vacant) => {
504                            vacant.insert(visitor.next_value()?);
505                        }
506                        crate::map::Entry::Occupied(occupied) => {
507                            let key = occupied.key();
508                            let msg = format!("duplicate key: `{key}`");
509                            return Err(de::Error::custom(msg));
510                        }
511                    }
512                }
513                Ok(Value::Table(map))
514            }
515        }
516
517        deserializer.deserialize_any(ValueVisitor)
518    }
519}
520
521// This is wrapped by `Table` and any trait methods implemented here need to be wrapped there.
522impl<'de> de::Deserializer<'de> for Value {
523    type Error = crate::de::Error;
524
525    fn deserialize_any<V>(self, visitor: V) -> Result<V::Value, crate::de::Error>
526    where
527        V: de::Visitor<'de>,
528    {
529        match self {
530            Self::Boolean(v) => visitor.visit_bool(v),
531            Self::Integer(n) => visitor.visit_i64(n),
532            Self::Float(n) => visitor.visit_f64(n),
533            Self::String(v) => visitor.visit_string(v),
534            Self::Datetime(v) => visitor.visit_string(v.to_string()),
535            Self::Array(v) => {
536                let len = v.len();
537                let mut deserializer = SeqDeserializer::new(v);
538                let seq = visitor.visit_seq(&mut deserializer)?;
539                let remaining = deserializer.iter.len();
540                if remaining == 0 {
541                    Ok(seq)
542                } else {
543                    Err(de::Error::invalid_length(len, &"fewer elements in array"))
544                }
545            }
546            Self::Table(v) => {
547                let len = v.len();
548                let mut deserializer = MapDeserializer::new(v);
549                let map = visitor.visit_map(&mut deserializer)?;
550                let remaining = deserializer.iter.len();
551                if remaining == 0 {
552                    Ok(map)
553                } else {
554                    Err(de::Error::invalid_length(len, &"fewer elements in map"))
555                }
556            }
557        }
558    }
559
560    #[inline]
561    fn deserialize_enum<V>(
562        self,
563        _name: &'static str,
564        _variants: &'static [&'static str],
565        visitor: V,
566    ) -> Result<V::Value, crate::de::Error>
567    where
568        V: de::Visitor<'de>,
569    {
570        match self {
571            Self::String(variant) => visitor.visit_enum(variant.into_deserializer()),
572            Self::Table(variant) => {
573                if variant.is_empty() {
574                    Err(crate::de::Error::custom(
575                        "wanted exactly 1 element, found 0 elements",
576                        None,
577                    ))
578                } else if variant.len() != 1 {
579                    Err(crate::de::Error::custom(
580                        "wanted exactly 1 element, more than 1 element",
581                        None,
582                    ))
583                } else {
584                    let deserializer = MapDeserializer::new(variant);
585                    visitor.visit_enum(deserializer)
586                }
587            }
588            _ => Err(de::Error::invalid_type(
589                de::Unexpected::UnitVariant,
590                &"string only",
591            )),
592        }
593    }
594
595    // `None` is interpreted as a missing field so be sure to implement `Some`
596    // as a present field.
597    fn deserialize_option<V>(self, visitor: V) -> Result<V::Value, crate::de::Error>
598    where
599        V: de::Visitor<'de>,
600    {
601        visitor.visit_some(self)
602    }
603
604    fn deserialize_newtype_struct<V>(
605        self,
606        _name: &'static str,
607        visitor: V,
608    ) -> Result<V::Value, crate::de::Error>
609    where
610        V: de::Visitor<'de>,
611    {
612        visitor.visit_newtype_struct(self)
613    }
614
615    fn deserialize_struct<V>(
616        self,
617        name: &'static str,
618        _fields: &'static [&'static str],
619        visitor: V,
620    ) -> Result<V::Value, crate::de::Error>
621    where
622        V: de::Visitor<'de>,
623    {
624        match (toml_datetime::de::is_datetime(name), self) {
625            (true, Self::Datetime(v)) => {
626                visitor.visit_map(toml_datetime::de::DatetimeDeserializer::new(v))
627            }
628            (_, value) => value.deserialize_any(visitor),
629        }
630    }
631
632    serde_core::forward_to_deserialize_any! {
633        bool u8 u16 u32 u64 i8 i16 i32 i64 f32 f64 char str string unit seq
634        bytes byte_buf map unit_struct tuple_struct
635        tuple ignored_any identifier
636    }
637}
638
639pub(crate) struct SeqDeserializer {
640    iter: vec::IntoIter<Value>,
641}
642
643impl SeqDeserializer {
644    fn new(vec: Vec<Value>) -> Self {
645        Self {
646            iter: vec.into_iter(),
647        }
648    }
649}
650
651impl<'de> de::SeqAccess<'de> for SeqDeserializer {
652    type Error = crate::de::Error;
653
654    fn next_element_seed<T>(&mut self, seed: T) -> Result<Option<T::Value>, crate::de::Error>
655    where
656        T: de::DeserializeSeed<'de>,
657    {
658        match self.iter.next() {
659            Some(value) => seed.deserialize(value).map(Some),
660            None => Ok(None),
661        }
662    }
663
664    fn size_hint(&self) -> Option<usize> {
665        match self.iter.size_hint() {
666            (lower, Some(upper)) if lower == upper => Some(upper),
667            _ => None,
668        }
669    }
670}
671
672pub(crate) struct MapDeserializer {
673    iter: <Table as IntoIterator>::IntoIter,
674    value: Option<(String, Value)>,
675}
676
677impl MapDeserializer {
678    fn new(map: Table) -> Self {
679        Self {
680            iter: map.into_iter(),
681            value: None,
682        }
683    }
684}
685
686impl<'de> de::MapAccess<'de> for MapDeserializer {
687    type Error = crate::de::Error;
688
689    fn next_key_seed<T>(&mut self, seed: T) -> Result<Option<T::Value>, crate::de::Error>
690    where
691        T: de::DeserializeSeed<'de>,
692    {
693        match self.iter.next() {
694            Some((key, value)) => {
695                self.value = Some((key.clone(), value));
696                seed.deserialize(Value::String(key)).map(Some)
697            }
698            None => Ok(None),
699        }
700    }
701
702    fn next_value_seed<T>(&mut self, seed: T) -> Result<T::Value, crate::de::Error>
703    where
704        T: de::DeserializeSeed<'de>,
705    {
706        let (key, res) = match self.value.take() {
707            Some((key, value)) => (key, seed.deserialize(value)),
708            None => return Err(de::Error::custom("value is missing")),
709        };
710        res.map_err(|mut error| {
711            error.add_key(key);
712            error
713        })
714    }
715
716    fn size_hint(&self) -> Option<usize> {
717        match self.iter.size_hint() {
718            (lower, Some(upper)) if lower == upper => Some(upper),
719            _ => None,
720        }
721    }
722}
723
724impl<'de> de::EnumAccess<'de> for MapDeserializer {
725    type Error = crate::de::Error;
726    type Variant = MapEnumDeserializer;
727
728    fn variant_seed<V>(mut self, seed: V) -> Result<(V::Value, Self::Variant), Self::Error>
729    where
730        V: de::DeserializeSeed<'de>,
731    {
732        use de::Error;
733        let (key, value) = match self.iter.next() {
734            Some(pair) => pair,
735            None => {
736                return Err(Error::custom(
737                    "expected table with exactly 1 entry, found empty table",
738                ));
739            }
740        };
741
742        let val = seed.deserialize(key.into_deserializer())?;
743
744        let variant = MapEnumDeserializer::new(value);
745
746        Ok((val, variant))
747    }
748}
749
750/// Deserializes table values into enum variants.
751pub(crate) struct MapEnumDeserializer {
752    value: Value,
753}
754
755impl MapEnumDeserializer {
756    pub(crate) fn new(value: Value) -> Self {
757        Self { value }
758    }
759}
760
761impl<'de> de::VariantAccess<'de> for MapEnumDeserializer {
762    type Error = crate::de::Error;
763
764    fn unit_variant(self) -> Result<(), Self::Error> {
765        use de::Error;
766        match self.value {
767            Value::Array(values) => {
768                if values.is_empty() {
769                    Ok(())
770                } else {
771                    Err(Error::custom("expected empty array"))
772                }
773            }
774            Value::Table(values) => {
775                if values.is_empty() {
776                    Ok(())
777                } else {
778                    Err(Error::custom("expected empty table"))
779                }
780            }
781            e => Err(Error::custom(format!(
782                "expected table, found {}",
783                e.type_str()
784            ))),
785        }
786    }
787
788    fn newtype_variant_seed<T>(self, seed: T) -> Result<T::Value, Self::Error>
789    where
790        T: de::DeserializeSeed<'de>,
791    {
792        seed.deserialize(self.value.into_deserializer())
793    }
794
795    fn tuple_variant<V>(self, len: usize, visitor: V) -> Result<V::Value, Self::Error>
796    where
797        V: de::Visitor<'de>,
798    {
799        use de::Error;
800        match self.value {
801            Value::Array(values) => {
802                if values.len() == len {
803                    de::Deserializer::deserialize_seq(values.into_deserializer(), visitor)
804                } else {
805                    Err(Error::custom(format!("expected tuple with length {len}")))
806                }
807            }
808            Value::Table(values) => {
809                let tuple_values: Result<Vec<_>, _> = values
810                    .into_iter()
811                    .enumerate()
812                    .map(|(index, (key, value))| match key.parse::<usize>() {
813                        Ok(key_index) if key_index == index => Ok(value),
814                        Ok(_) | Err(_) => Err(Error::custom(format!(
815                            "expected table key `{index}`, but was `{key}`"
816                        ))),
817                    })
818                    .collect();
819                let tuple_values = tuple_values?;
820
821                if tuple_values.len() == len {
822                    de::Deserializer::deserialize_seq(tuple_values.into_deserializer(), visitor)
823                } else {
824                    Err(Error::custom(format!("expected tuple with length {len}")))
825                }
826            }
827            e => Err(Error::custom(format!(
828                "expected table, found {}",
829                e.type_str()
830            ))),
831        }
832    }
833
834    fn struct_variant<V>(
835        self,
836        fields: &'static [&'static str],
837        visitor: V,
838    ) -> Result<V::Value, Self::Error>
839    where
840        V: de::Visitor<'de>,
841    {
842        de::Deserializer::deserialize_struct(
843            self.value.into_deserializer(),
844            "", // TODO: this should be the variant name
845            fields,
846            visitor,
847        )
848    }
849}
850
851impl IntoDeserializer<'_, crate::de::Error> for Value {
852    type Deserializer = Self;
853
854    fn into_deserializer(self) -> Self {
855        self
856    }
857}
858
859pub(crate) struct ValueSerializer;
860
861impl ser::Serializer for ValueSerializer {
862    type Ok = Value;
863    type Error = crate::ser::Error;
864
865    type SerializeSeq = ValueSerializeVec;
866    type SerializeTuple = ValueSerializeVec;
867    type SerializeTupleStruct = ValueSerializeVec;
868    type SerializeTupleVariant = ValueSerializeTupleVariant;
869    type SerializeMap = ValueSerializeMap;
870    type SerializeStruct = ValueSerializeMap;
871    type SerializeStructVariant = ValueSerializeStructVariant;
872
873    fn serialize_bool(self, value: bool) -> Result<Value, crate::ser::Error> {
874        Ok(Value::Boolean(value))
875    }
876
877    fn serialize_i8(self, value: i8) -> Result<Value, crate::ser::Error> {
878        self.serialize_i64(value.into())
879    }
880
881    fn serialize_i16(self, value: i16) -> Result<Value, crate::ser::Error> {
882        self.serialize_i64(value.into())
883    }
884
885    fn serialize_i32(self, value: i32) -> Result<Value, crate::ser::Error> {
886        self.serialize_i64(value.into())
887    }
888
889    fn serialize_i64(self, value: i64) -> Result<Value, crate::ser::Error> {
890        Ok(Value::Integer(value))
891    }
892
893    fn serialize_u8(self, value: u8) -> Result<Value, crate::ser::Error> {
894        self.serialize_i64(value.into())
895    }
896
897    fn serialize_u16(self, value: u16) -> Result<Value, crate::ser::Error> {
898        self.serialize_i64(value.into())
899    }
900
901    fn serialize_u32(self, value: u32) -> Result<Value, crate::ser::Error> {
902        self.serialize_i64(value.into())
903    }
904
905    fn serialize_u64(self, value: u64) -> Result<Value, crate::ser::Error> {
906        if i64::try_from(value).is_ok() {
907            self.serialize_i64(value as i64)
908        } else {
909            Err(ser::Error::custom("u64 value was too large"))
910        }
911    }
912
913    fn serialize_f32(self, value: f32) -> Result<Value, crate::ser::Error> {
914        self.serialize_f64(value as f64)
915    }
916
917    fn serialize_f64(self, mut value: f64) -> Result<Value, crate::ser::Error> {
918        // Discard sign of NaN. See ValueSerializer::serialize_f64.
919        if value.is_nan() {
920            value = value.copysign(1.0);
921        }
922        Ok(Value::Float(value))
923    }
924
925    fn serialize_char(self, value: char) -> Result<Value, crate::ser::Error> {
926        let mut s = String::new();
927        s.push(value);
928        self.serialize_str(&s)
929    }
930
931    fn serialize_str(self, value: &str) -> Result<Value, crate::ser::Error> {
932        Ok(Value::String(value.to_owned()))
933    }
934
935    fn serialize_bytes(self, value: &[u8]) -> Result<Value, crate::ser::Error> {
936        let vec = value.iter().map(|&b| Value::Integer(b.into())).collect();
937        Ok(Value::Array(vec))
938    }
939
940    fn serialize_unit(self) -> Result<Value, crate::ser::Error> {
941        Err(crate::ser::Error::unsupported_type(Some("unit")))
942    }
943
944    fn serialize_unit_struct(self, name: &'static str) -> Result<Value, crate::ser::Error> {
945        Err(crate::ser::Error::unsupported_type(Some(name)))
946    }
947
948    fn serialize_unit_variant(
949        self,
950        _name: &'static str,
951        _variant_index: u32,
952        _variant: &'static str,
953    ) -> Result<Value, crate::ser::Error> {
954        self.serialize_str(_variant)
955    }
956
957    fn serialize_newtype_struct<T>(
958        self,
959        _name: &'static str,
960        value: &T,
961    ) -> Result<Value, crate::ser::Error>
962    where
963        T: ser::Serialize + ?Sized,
964    {
965        value.serialize(self)
966    }
967
968    fn serialize_newtype_variant<T>(
969        self,
970        _name: &'static str,
971        _variant_index: u32,
972        variant: &'static str,
973        value: &T,
974    ) -> Result<Value, crate::ser::Error>
975    where
976        T: ser::Serialize + ?Sized,
977    {
978        let value = value.serialize(Self)?;
979        let mut table = Table::new();
980        table.insert(variant.to_owned(), value);
981        Ok(table.into())
982    }
983
984    fn serialize_none(self) -> Result<Value, crate::ser::Error> {
985        Err(crate::ser::Error::unsupported_none())
986    }
987
988    fn serialize_some<T>(self, value: &T) -> Result<Value, crate::ser::Error>
989    where
990        T: ser::Serialize + ?Sized,
991    {
992        value.serialize(self)
993    }
994
995    fn serialize_seq(self, len: Option<usize>) -> Result<Self::SerializeSeq, crate::ser::Error> {
996        Ok(ValueSerializeVec {
997            vec: Vec::with_capacity(len.unwrap_or(0)),
998        })
999    }
1000
1001    fn serialize_tuple(self, len: usize) -> Result<Self::SerializeTuple, crate::ser::Error> {
1002        self.serialize_seq(Some(len))
1003    }
1004
1005    fn serialize_tuple_struct(
1006        self,
1007        _name: &'static str,
1008        len: usize,
1009    ) -> Result<Self::SerializeTupleStruct, crate::ser::Error> {
1010        self.serialize_seq(Some(len))
1011    }
1012
1013    fn serialize_tuple_variant(
1014        self,
1015        _name: &'static str,
1016        _variant_index: u32,
1017        variant: &'static str,
1018        len: usize,
1019    ) -> Result<Self::SerializeTupleVariant, crate::ser::Error> {
1020        Ok(ValueSerializeTupleVariant::tuple(variant, len))
1021    }
1022
1023    fn serialize_map(self, _len: Option<usize>) -> Result<Self::SerializeMap, crate::ser::Error> {
1024        Ok(ValueSerializeMap {
1025            ser: crate::table::SerializeMap::new(),
1026        })
1027    }
1028
1029    fn serialize_struct(
1030        self,
1031        _name: &'static str,
1032        len: usize,
1033    ) -> Result<Self::SerializeStruct, crate::ser::Error> {
1034        self.serialize_map(Some(len))
1035    }
1036
1037    fn serialize_struct_variant(
1038        self,
1039        _name: &'static str,
1040        _variant_index: u32,
1041        variant: &'static str,
1042        len: usize,
1043    ) -> Result<Self::SerializeStructVariant, crate::ser::Error> {
1044        Ok(ValueSerializeStructVariant::struct_(variant, len))
1045    }
1046}
1047
1048pub(crate) struct ValueSerializeVec {
1049    vec: Vec<Value>,
1050}
1051
1052impl ser::SerializeSeq for ValueSerializeVec {
1053    type Ok = Value;
1054    type Error = crate::ser::Error;
1055
1056    fn serialize_element<T>(&mut self, value: &T) -> Result<(), crate::ser::Error>
1057    where
1058        T: ser::Serialize + ?Sized,
1059    {
1060        self.vec.push(Value::try_from(value)?);
1061        Ok(())
1062    }
1063
1064    fn end(self) -> Result<Value, crate::ser::Error> {
1065        Ok(Value::Array(self.vec))
1066    }
1067}
1068
1069impl ser::SerializeTuple for ValueSerializeVec {
1070    type Ok = Value;
1071    type Error = crate::ser::Error;
1072
1073    fn serialize_element<T>(&mut self, value: &T) -> Result<(), crate::ser::Error>
1074    where
1075        T: ser::Serialize + ?Sized,
1076    {
1077        ser::SerializeSeq::serialize_element(self, value)
1078    }
1079
1080    fn end(self) -> Result<Value, crate::ser::Error> {
1081        ser::SerializeSeq::end(self)
1082    }
1083}
1084
1085impl ser::SerializeTupleStruct for ValueSerializeVec {
1086    type Ok = Value;
1087    type Error = crate::ser::Error;
1088
1089    fn serialize_field<T>(&mut self, value: &T) -> Result<(), crate::ser::Error>
1090    where
1091        T: ser::Serialize + ?Sized,
1092    {
1093        ser::SerializeSeq::serialize_element(self, value)
1094    }
1095
1096    fn end(self) -> Result<Value, crate::ser::Error> {
1097        ser::SerializeSeq::end(self)
1098    }
1099}
1100
1101impl ser::SerializeTupleVariant for ValueSerializeVec {
1102    type Ok = Value;
1103    type Error = crate::ser::Error;
1104
1105    fn serialize_field<T>(&mut self, value: &T) -> Result<(), crate::ser::Error>
1106    where
1107        T: ser::Serialize + ?Sized,
1108    {
1109        ser::SerializeSeq::serialize_element(self, value)
1110    }
1111
1112    fn end(self) -> Result<Value, crate::ser::Error> {
1113        ser::SerializeSeq::end(self)
1114    }
1115}
1116
1117pub(crate) struct ValueSerializeMap {
1118    ser: crate::table::SerializeMap,
1119}
1120
1121impl ser::SerializeMap for ValueSerializeMap {
1122    type Ok = Value;
1123    type Error = crate::ser::Error;
1124
1125    fn serialize_key<T>(&mut self, key: &T) -> Result<(), crate::ser::Error>
1126    where
1127        T: ser::Serialize + ?Sized,
1128    {
1129        self.ser.serialize_key(key)
1130    }
1131
1132    fn serialize_value<T>(&mut self, value: &T) -> Result<(), crate::ser::Error>
1133    where
1134        T: ser::Serialize + ?Sized,
1135    {
1136        self.ser.serialize_value(value)
1137    }
1138
1139    fn end(self) -> Result<Value, crate::ser::Error> {
1140        self.ser.end().map(Value::Table)
1141    }
1142}
1143
1144impl ser::SerializeStruct for ValueSerializeMap {
1145    type Ok = Value;
1146    type Error = crate::ser::Error;
1147
1148    fn serialize_field<T>(&mut self, key: &'static str, value: &T) -> Result<(), crate::ser::Error>
1149    where
1150        T: ser::Serialize + ?Sized,
1151    {
1152        ser::SerializeMap::serialize_key(self, key)?;
1153        ser::SerializeMap::serialize_value(self, value)
1154    }
1155
1156    fn end(self) -> Result<Value, crate::ser::Error> {
1157        ser::SerializeMap::end(self)
1158    }
1159}
1160
1161type ValueSerializeTupleVariant = ValueSerializeVariant<ValueSerializeVec>;
1162type ValueSerializeStructVariant = ValueSerializeVariant<ValueSerializeMap>;
1163
1164pub(crate) struct ValueSerializeVariant<T> {
1165    variant: &'static str,
1166    inner: T,
1167}
1168
1169impl ValueSerializeVariant<ValueSerializeVec> {
1170    pub(crate) fn tuple(variant: &'static str, len: usize) -> Self {
1171        Self {
1172            variant,
1173            inner: ValueSerializeVec {
1174                vec: Vec::with_capacity(len),
1175            },
1176        }
1177    }
1178}
1179
1180impl ValueSerializeVariant<ValueSerializeMap> {
1181    pub(crate) fn struct_(variant: &'static str, len: usize) -> Self {
1182        Self {
1183            variant,
1184            inner: ValueSerializeMap {
1185                ser: crate::table::SerializeMap::with_capacity(len),
1186            },
1187        }
1188    }
1189}
1190
1191impl ser::SerializeTupleVariant for ValueSerializeVariant<ValueSerializeVec> {
1192    type Ok = Value;
1193    type Error = crate::ser::Error;
1194
1195    fn serialize_field<T>(&mut self, value: &T) -> Result<(), Self::Error>
1196    where
1197        T: ser::Serialize + ?Sized,
1198    {
1199        ser::SerializeSeq::serialize_element(&mut self.inner, value)
1200    }
1201
1202    fn end(self) -> Result<Self::Ok, Self::Error> {
1203        let inner = ser::SerializeSeq::end(self.inner)?;
1204        let mut table = Table::new();
1205        table.insert(self.variant.to_owned(), inner);
1206        Ok(Value::Table(table))
1207    }
1208}
1209
1210impl ser::SerializeStructVariant for ValueSerializeVariant<ValueSerializeMap> {
1211    type Ok = Value;
1212    type Error = crate::ser::Error;
1213
1214    #[inline]
1215    fn serialize_field<T>(&mut self, key: &'static str, value: &T) -> Result<(), Self::Error>
1216    where
1217        T: ser::Serialize + ?Sized,
1218    {
1219        ser::SerializeStruct::serialize_field(&mut self.inner, key, value)
1220    }
1221
1222    #[inline]
1223    fn end(self) -> Result<Self::Ok, Self::Error> {
1224        let inner = ser::SerializeStruct::end(self.inner)?;
1225        let mut table = Table::new();
1226        table.insert(self.variant.to_owned(), inner);
1227        Ok(Value::Table(table))
1228    }
1229}