toml/
value.rs

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