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                    if let crate::map::Entry::Vacant(vacant) = map.entry(&key) {
503                        vacant.insert(visitor.next_value()?);
504                    } else {
505                        let msg = format!("duplicate key: `{key}`");
506                        return Err(de::Error::custom(msg));
507                    }
508                }
509                Ok(Value::Table(map))
510            }
511        }
512
513        deserializer.deserialize_any(ValueVisitor)
514    }
515}
516
517// This is wrapped by `Table` and any trait methods implemented here need to be wrapped there.
518impl<'de> de::Deserializer<'de> for Value {
519    type Error = crate::de::Error;
520
521    fn deserialize_any<V>(self, visitor: V) -> Result<V::Value, crate::de::Error>
522    where
523        V: de::Visitor<'de>,
524    {
525        match self {
526            Self::Boolean(v) => visitor.visit_bool(v),
527            Self::Integer(n) => visitor.visit_i64(n),
528            Self::Float(n) => visitor.visit_f64(n),
529            Self::String(v) => visitor.visit_string(v),
530            Self::Datetime(v) => visitor.visit_string(v.to_string()),
531            Self::Array(v) => {
532                let len = v.len();
533                let mut deserializer = SeqDeserializer::new(v);
534                let seq = visitor.visit_seq(&mut deserializer)?;
535                let remaining = deserializer.iter.len();
536                if remaining == 0 {
537                    Ok(seq)
538                } else {
539                    Err(de::Error::invalid_length(len, &"fewer elements in array"))
540                }
541            }
542            Self::Table(v) => {
543                let len = v.len();
544                let mut deserializer = MapDeserializer::new(v);
545                let map = visitor.visit_map(&mut deserializer)?;
546                let remaining = deserializer.iter.len();
547                if remaining == 0 {
548                    Ok(map)
549                } else {
550                    Err(de::Error::invalid_length(len, &"fewer elements in map"))
551                }
552            }
553        }
554    }
555
556    #[inline]
557    fn deserialize_enum<V>(
558        self,
559        _name: &'static str,
560        _variants: &'static [&'static str],
561        visitor: V,
562    ) -> Result<V::Value, crate::de::Error>
563    where
564        V: de::Visitor<'de>,
565    {
566        match self {
567            Self::String(variant) => visitor.visit_enum(variant.into_deserializer()),
568            Self::Table(variant) => {
569                if variant.is_empty() {
570                    Err(crate::de::Error::custom(
571                        "wanted exactly 1 element, found 0 elements",
572                        None,
573                    ))
574                } else if variant.len() != 1 {
575                    Err(crate::de::Error::custom(
576                        "wanted exactly 1 element, more than 1 element",
577                        None,
578                    ))
579                } else {
580                    let deserializer = MapDeserializer::new(variant);
581                    visitor.visit_enum(deserializer)
582                }
583            }
584            _ => Err(de::Error::invalid_type(
585                de::Unexpected::UnitVariant,
586                &"string only",
587            )),
588        }
589    }
590
591    // `None` is interpreted as a missing field so be sure to implement `Some`
592    // as a present field.
593    fn deserialize_option<V>(self, visitor: V) -> Result<V::Value, crate::de::Error>
594    where
595        V: de::Visitor<'de>,
596    {
597        visitor.visit_some(self)
598    }
599
600    fn deserialize_newtype_struct<V>(
601        self,
602        _name: &'static str,
603        visitor: V,
604    ) -> Result<V::Value, crate::de::Error>
605    where
606        V: de::Visitor<'de>,
607    {
608        visitor.visit_newtype_struct(self)
609    }
610
611    fn deserialize_struct<V>(
612        self,
613        name: &'static str,
614        _fields: &'static [&'static str],
615        visitor: V,
616    ) -> Result<V::Value, crate::de::Error>
617    where
618        V: de::Visitor<'de>,
619    {
620        match (toml_datetime::de::is_datetime(name), self) {
621            (true, Self::Datetime(v)) => {
622                visitor.visit_map(toml_datetime::de::DatetimeDeserializer::new(v))
623            }
624            (_, value) => value.deserialize_any(visitor),
625        }
626    }
627
628    serde_core::forward_to_deserialize_any! {
629        bool u8 u16 u32 u64 i8 i16 i32 i64 f32 f64 char str string unit seq
630        bytes byte_buf map unit_struct tuple_struct
631        tuple ignored_any identifier
632    }
633}
634
635pub(crate) struct SeqDeserializer {
636    iter: vec::IntoIter<Value>,
637}
638
639impl SeqDeserializer {
640    fn new(vec: Vec<Value>) -> Self {
641        Self {
642            iter: vec.into_iter(),
643        }
644    }
645}
646
647impl<'de> de::SeqAccess<'de> for SeqDeserializer {
648    type Error = crate::de::Error;
649
650    fn next_element_seed<T>(&mut self, seed: T) -> Result<Option<T::Value>, crate::de::Error>
651    where
652        T: de::DeserializeSeed<'de>,
653    {
654        match self.iter.next() {
655            Some(value) => seed.deserialize(value).map(Some),
656            None => Ok(None),
657        }
658    }
659
660    fn size_hint(&self) -> Option<usize> {
661        match self.iter.size_hint() {
662            (lower, Some(upper)) if lower == upper => Some(upper),
663            _ => None,
664        }
665    }
666}
667
668pub(crate) struct MapDeserializer {
669    iter: <Table as IntoIterator>::IntoIter,
670    value: Option<(String, Value)>,
671}
672
673impl MapDeserializer {
674    fn new(map: Table) -> Self {
675        Self {
676            iter: map.into_iter(),
677            value: None,
678        }
679    }
680}
681
682impl<'de> de::MapAccess<'de> for MapDeserializer {
683    type Error = crate::de::Error;
684
685    fn next_key_seed<T>(&mut self, seed: T) -> Result<Option<T::Value>, crate::de::Error>
686    where
687        T: de::DeserializeSeed<'de>,
688    {
689        match self.iter.next() {
690            Some((key, value)) => {
691                self.value = Some((key.clone(), value));
692                seed.deserialize(Value::String(key)).map(Some)
693            }
694            None => Ok(None),
695        }
696    }
697
698    fn next_value_seed<T>(&mut self, seed: T) -> Result<T::Value, crate::de::Error>
699    where
700        T: de::DeserializeSeed<'de>,
701    {
702        let (key, res) = match self.value.take() {
703            Some((key, value)) => (key, seed.deserialize(value)),
704            None => return Err(de::Error::custom("value is missing")),
705        };
706        res.map_err(|mut error| {
707            error.add_key(key);
708            error
709        })
710    }
711
712    fn size_hint(&self) -> Option<usize> {
713        match self.iter.size_hint() {
714            (lower, Some(upper)) if lower == upper => Some(upper),
715            _ => None,
716        }
717    }
718}
719
720impl<'de> de::EnumAccess<'de> for MapDeserializer {
721    type Error = crate::de::Error;
722    type Variant = MapEnumDeserializer;
723
724    fn variant_seed<V>(mut self, seed: V) -> Result<(V::Value, Self::Variant), Self::Error>
725    where
726        V: de::DeserializeSeed<'de>,
727    {
728        use de::Error;
729        let (key, value) = match self.iter.next() {
730            Some(pair) => pair,
731            None => {
732                return Err(Error::custom(
733                    "expected table with exactly 1 entry, found empty table",
734                ));
735            }
736        };
737
738        let val = seed.deserialize(key.into_deserializer())?;
739
740        let variant = MapEnumDeserializer::new(value);
741
742        Ok((val, variant))
743    }
744}
745
746/// Deserializes table values into enum variants.
747pub(crate) struct MapEnumDeserializer {
748    value: Value,
749}
750
751impl MapEnumDeserializer {
752    pub(crate) fn new(value: Value) -> Self {
753        Self { value }
754    }
755}
756
757impl<'de> de::VariantAccess<'de> for MapEnumDeserializer {
758    type Error = crate::de::Error;
759
760    fn unit_variant(self) -> Result<(), Self::Error> {
761        use de::Error;
762        match self.value {
763            Value::Array(values) => {
764                if values.is_empty() {
765                    Ok(())
766                } else {
767                    Err(Error::custom("expected empty array"))
768                }
769            }
770            Value::Table(values) => {
771                if values.is_empty() {
772                    Ok(())
773                } else {
774                    Err(Error::custom("expected empty table"))
775                }
776            }
777            e => Err(Error::custom(format!(
778                "expected table, found {}",
779                e.type_str()
780            ))),
781        }
782    }
783
784    fn newtype_variant_seed<T>(self, seed: T) -> Result<T::Value, Self::Error>
785    where
786        T: de::DeserializeSeed<'de>,
787    {
788        seed.deserialize(self.value.into_deserializer())
789    }
790
791    fn tuple_variant<V>(self, len: usize, visitor: V) -> Result<V::Value, Self::Error>
792    where
793        V: de::Visitor<'de>,
794    {
795        use de::Error;
796        match self.value {
797            Value::Array(values) => {
798                if values.len() == len {
799                    de::Deserializer::deserialize_seq(values.into_deserializer(), visitor)
800                } else {
801                    Err(Error::custom(format!("expected tuple with length {len}")))
802                }
803            }
804            Value::Table(values) => {
805                let tuple_values: Result<Vec<_>, _> = values
806                    .into_iter()
807                    .enumerate()
808                    .map(|(index, (key, value))| match key.parse::<usize>() {
809                        Ok(key_index) if key_index == index => Ok(value),
810                        Ok(_) | Err(_) => Err(Error::custom(format!(
811                            "expected table key `{index}`, but was `{key}`"
812                        ))),
813                    })
814                    .collect();
815                let tuple_values = tuple_values?;
816
817                if tuple_values.len() == len {
818                    de::Deserializer::deserialize_seq(tuple_values.into_deserializer(), visitor)
819                } else {
820                    Err(Error::custom(format!("expected tuple with length {len}")))
821                }
822            }
823            e => Err(Error::custom(format!(
824                "expected table, found {}",
825                e.type_str()
826            ))),
827        }
828    }
829
830    fn struct_variant<V>(
831        self,
832        fields: &'static [&'static str],
833        visitor: V,
834    ) -> Result<V::Value, Self::Error>
835    where
836        V: de::Visitor<'de>,
837    {
838        de::Deserializer::deserialize_struct(
839            self.value.into_deserializer(),
840            "", // TODO: this should be the variant name
841            fields,
842            visitor,
843        )
844    }
845}
846
847impl IntoDeserializer<'_, crate::de::Error> for Value {
848    type Deserializer = Self;
849
850    fn into_deserializer(self) -> Self {
851        self
852    }
853}
854
855pub(crate) struct ValueSerializer;
856
857impl ser::Serializer for ValueSerializer {
858    type Ok = Value;
859    type Error = crate::ser::Error;
860
861    type SerializeSeq = ValueSerializeVec;
862    type SerializeTuple = ValueSerializeVec;
863    type SerializeTupleStruct = ValueSerializeVec;
864    type SerializeTupleVariant = ValueSerializeTupleVariant;
865    type SerializeMap = ValueSerializeMap;
866    type SerializeStruct = ValueSerializeMap;
867    type SerializeStructVariant = ValueSerializeStructVariant;
868
869    fn serialize_bool(self, value: bool) -> Result<Value, crate::ser::Error> {
870        Ok(Value::Boolean(value))
871    }
872
873    fn serialize_i8(self, value: i8) -> Result<Value, crate::ser::Error> {
874        self.serialize_i64(value.into())
875    }
876
877    fn serialize_i16(self, value: i16) -> Result<Value, crate::ser::Error> {
878        self.serialize_i64(value.into())
879    }
880
881    fn serialize_i32(self, value: i32) -> Result<Value, crate::ser::Error> {
882        self.serialize_i64(value.into())
883    }
884
885    fn serialize_i64(self, value: i64) -> Result<Value, crate::ser::Error> {
886        Ok(Value::Integer(value))
887    }
888
889    fn serialize_u8(self, value: u8) -> Result<Value, crate::ser::Error> {
890        self.serialize_i64(value.into())
891    }
892
893    fn serialize_u16(self, value: u16) -> Result<Value, crate::ser::Error> {
894        self.serialize_i64(value.into())
895    }
896
897    fn serialize_u32(self, value: u32) -> Result<Value, crate::ser::Error> {
898        self.serialize_i64(value.into())
899    }
900
901    fn serialize_u64(self, value: u64) -> Result<Value, crate::ser::Error> {
902        if i64::try_from(value).is_ok() {
903            self.serialize_i64(value as i64)
904        } else {
905            Err(ser::Error::custom("u64 value was too large"))
906        }
907    }
908
909    fn serialize_f32(self, value: f32) -> Result<Value, crate::ser::Error> {
910        self.serialize_f64(value as f64)
911    }
912
913    fn serialize_f64(self, mut value: f64) -> Result<Value, crate::ser::Error> {
914        // Discard sign of NaN. See ValueSerializer::serialize_f64.
915        if value.is_nan() {
916            value = value.copysign(1.0);
917        }
918        Ok(Value::Float(value))
919    }
920
921    fn serialize_char(self, value: char) -> Result<Value, crate::ser::Error> {
922        let mut s = String::new();
923        s.push(value);
924        self.serialize_str(&s)
925    }
926
927    fn serialize_str(self, value: &str) -> Result<Value, crate::ser::Error> {
928        Ok(Value::String(value.to_owned()))
929    }
930
931    fn serialize_bytes(self, value: &[u8]) -> Result<Value, crate::ser::Error> {
932        let vec = value.iter().map(|&b| Value::Integer(b.into())).collect();
933        Ok(Value::Array(vec))
934    }
935
936    fn serialize_unit(self) -> Result<Value, crate::ser::Error> {
937        Err(crate::ser::Error::unsupported_type(Some("unit")))
938    }
939
940    fn serialize_unit_struct(self, name: &'static str) -> Result<Value, crate::ser::Error> {
941        Err(crate::ser::Error::unsupported_type(Some(name)))
942    }
943
944    fn serialize_unit_variant(
945        self,
946        _name: &'static str,
947        _variant_index: u32,
948        _variant: &'static str,
949    ) -> Result<Value, crate::ser::Error> {
950        self.serialize_str(_variant)
951    }
952
953    fn serialize_newtype_struct<T>(
954        self,
955        _name: &'static str,
956        value: &T,
957    ) -> Result<Value, crate::ser::Error>
958    where
959        T: ser::Serialize + ?Sized,
960    {
961        value.serialize(self)
962    }
963
964    fn serialize_newtype_variant<T>(
965        self,
966        _name: &'static str,
967        _variant_index: u32,
968        variant: &'static str,
969        value: &T,
970    ) -> Result<Value, crate::ser::Error>
971    where
972        T: ser::Serialize + ?Sized,
973    {
974        let value = value.serialize(Self)?;
975        let mut table = Table::new();
976        table.insert(variant.to_owned(), value);
977        Ok(table.into())
978    }
979
980    fn serialize_none(self) -> Result<Value, crate::ser::Error> {
981        Err(crate::ser::Error::unsupported_none())
982    }
983
984    fn serialize_some<T>(self, value: &T) -> Result<Value, crate::ser::Error>
985    where
986        T: ser::Serialize + ?Sized,
987    {
988        value.serialize(self)
989    }
990
991    fn serialize_seq(self, len: Option<usize>) -> Result<Self::SerializeSeq, crate::ser::Error> {
992        Ok(ValueSerializeVec {
993            vec: Vec::with_capacity(len.unwrap_or(0)),
994        })
995    }
996
997    fn serialize_tuple(self, len: usize) -> Result<Self::SerializeTuple, crate::ser::Error> {
998        self.serialize_seq(Some(len))
999    }
1000
1001    fn serialize_tuple_struct(
1002        self,
1003        _name: &'static str,
1004        len: usize,
1005    ) -> Result<Self::SerializeTupleStruct, crate::ser::Error> {
1006        self.serialize_seq(Some(len))
1007    }
1008
1009    fn serialize_tuple_variant(
1010        self,
1011        _name: &'static str,
1012        _variant_index: u32,
1013        variant: &'static str,
1014        len: usize,
1015    ) -> Result<Self::SerializeTupleVariant, crate::ser::Error> {
1016        Ok(ValueSerializeTupleVariant::tuple(variant, len))
1017    }
1018
1019    fn serialize_map(self, _len: Option<usize>) -> Result<Self::SerializeMap, crate::ser::Error> {
1020        Ok(ValueSerializeMap {
1021            ser: crate::table::SerializeMap::new(),
1022        })
1023    }
1024
1025    fn serialize_struct(
1026        self,
1027        _name: &'static str,
1028        len: usize,
1029    ) -> Result<Self::SerializeStruct, crate::ser::Error> {
1030        self.serialize_map(Some(len))
1031    }
1032
1033    fn serialize_struct_variant(
1034        self,
1035        _name: &'static str,
1036        _variant_index: u32,
1037        variant: &'static str,
1038        len: usize,
1039    ) -> Result<Self::SerializeStructVariant, crate::ser::Error> {
1040        Ok(ValueSerializeStructVariant::struct_(variant, len))
1041    }
1042}
1043
1044pub(crate) struct ValueSerializeVec {
1045    vec: Vec<Value>,
1046}
1047
1048impl ser::SerializeSeq for ValueSerializeVec {
1049    type Ok = Value;
1050    type Error = crate::ser::Error;
1051
1052    fn serialize_element<T>(&mut self, value: &T) -> Result<(), crate::ser::Error>
1053    where
1054        T: ser::Serialize + ?Sized,
1055    {
1056        self.vec.push(Value::try_from(value)?);
1057        Ok(())
1058    }
1059
1060    fn end(self) -> Result<Value, crate::ser::Error> {
1061        Ok(Value::Array(self.vec))
1062    }
1063}
1064
1065impl ser::SerializeTuple for ValueSerializeVec {
1066    type Ok = Value;
1067    type Error = crate::ser::Error;
1068
1069    fn serialize_element<T>(&mut self, value: &T) -> Result<(), crate::ser::Error>
1070    where
1071        T: ser::Serialize + ?Sized,
1072    {
1073        ser::SerializeSeq::serialize_element(self, value)
1074    }
1075
1076    fn end(self) -> Result<Value, crate::ser::Error> {
1077        ser::SerializeSeq::end(self)
1078    }
1079}
1080
1081impl ser::SerializeTupleStruct for ValueSerializeVec {
1082    type Ok = Value;
1083    type Error = crate::ser::Error;
1084
1085    fn serialize_field<T>(&mut self, value: &T) -> Result<(), crate::ser::Error>
1086    where
1087        T: ser::Serialize + ?Sized,
1088    {
1089        ser::SerializeSeq::serialize_element(self, value)
1090    }
1091
1092    fn end(self) -> Result<Value, crate::ser::Error> {
1093        ser::SerializeSeq::end(self)
1094    }
1095}
1096
1097impl ser::SerializeTupleVariant for ValueSerializeVec {
1098    type Ok = Value;
1099    type Error = crate::ser::Error;
1100
1101    fn serialize_field<T>(&mut self, value: &T) -> Result<(), crate::ser::Error>
1102    where
1103        T: ser::Serialize + ?Sized,
1104    {
1105        ser::SerializeSeq::serialize_element(self, value)
1106    }
1107
1108    fn end(self) -> Result<Value, crate::ser::Error> {
1109        ser::SerializeSeq::end(self)
1110    }
1111}
1112
1113pub(crate) struct ValueSerializeMap {
1114    ser: crate::table::SerializeMap,
1115}
1116
1117impl ser::SerializeMap for ValueSerializeMap {
1118    type Ok = Value;
1119    type Error = crate::ser::Error;
1120
1121    fn serialize_key<T>(&mut self, key: &T) -> Result<(), crate::ser::Error>
1122    where
1123        T: ser::Serialize + ?Sized,
1124    {
1125        self.ser.serialize_key(key)
1126    }
1127
1128    fn serialize_value<T>(&mut self, value: &T) -> Result<(), crate::ser::Error>
1129    where
1130        T: ser::Serialize + ?Sized,
1131    {
1132        self.ser.serialize_value(value)
1133    }
1134
1135    fn end(self) -> Result<Value, crate::ser::Error> {
1136        self.ser.end().map(Value::Table)
1137    }
1138}
1139
1140impl ser::SerializeStruct for ValueSerializeMap {
1141    type Ok = Value;
1142    type Error = crate::ser::Error;
1143
1144    fn serialize_field<T>(&mut self, key: &'static str, value: &T) -> Result<(), crate::ser::Error>
1145    where
1146        T: ser::Serialize + ?Sized,
1147    {
1148        ser::SerializeMap::serialize_key(self, key)?;
1149        ser::SerializeMap::serialize_value(self, value)
1150    }
1151
1152    fn end(self) -> Result<Value, crate::ser::Error> {
1153        ser::SerializeMap::end(self)
1154    }
1155}
1156
1157type ValueSerializeTupleVariant = ValueSerializeVariant<ValueSerializeVec>;
1158type ValueSerializeStructVariant = ValueSerializeVariant<ValueSerializeMap>;
1159
1160pub(crate) struct ValueSerializeVariant<T> {
1161    variant: &'static str,
1162    inner: T,
1163}
1164
1165impl ValueSerializeVariant<ValueSerializeVec> {
1166    pub(crate) fn tuple(variant: &'static str, len: usize) -> Self {
1167        Self {
1168            variant,
1169            inner: ValueSerializeVec {
1170                vec: Vec::with_capacity(len),
1171            },
1172        }
1173    }
1174}
1175
1176impl ValueSerializeVariant<ValueSerializeMap> {
1177    pub(crate) fn struct_(variant: &'static str, len: usize) -> Self {
1178        Self {
1179            variant,
1180            inner: ValueSerializeMap {
1181                ser: crate::table::SerializeMap::with_capacity(len),
1182            },
1183        }
1184    }
1185}
1186
1187impl ser::SerializeTupleVariant for ValueSerializeVariant<ValueSerializeVec> {
1188    type Ok = Value;
1189    type Error = crate::ser::Error;
1190
1191    fn serialize_field<T>(&mut self, value: &T) -> Result<(), Self::Error>
1192    where
1193        T: ser::Serialize + ?Sized,
1194    {
1195        ser::SerializeSeq::serialize_element(&mut self.inner, value)
1196    }
1197
1198    fn end(self) -> Result<Self::Ok, Self::Error> {
1199        let inner = ser::SerializeSeq::end(self.inner)?;
1200        let mut table = Table::new();
1201        table.insert(self.variant.to_owned(), inner);
1202        Ok(Value::Table(table))
1203    }
1204}
1205
1206impl ser::SerializeStructVariant for ValueSerializeVariant<ValueSerializeMap> {
1207    type Ok = Value;
1208    type Error = crate::ser::Error;
1209
1210    #[inline]
1211    fn serialize_field<T>(&mut self, key: &'static str, value: &T) -> Result<(), Self::Error>
1212    where
1213        T: ser::Serialize + ?Sized,
1214    {
1215        ser::SerializeStruct::serialize_field(&mut self.inner, key, value)
1216    }
1217
1218    #[inline]
1219    fn end(self) -> Result<Self::Ok, Self::Error> {
1220        let inner = ser::SerializeStruct::end(self.inner)?;
1221        let mut table = Table::new();
1222        table.insert(self.variant.to_owned(), inner);
1223        Ok(Value::Table(table))
1224    }
1225}