1 //! Definition of a TOML value
2 
3 use std::collections::{BTreeMap, HashMap};
4 use std::fmt;
5 use std::hash::Hash;
6 use std::mem::discriminant;
7 use std::ops;
8 use std::str::FromStr;
9 use std::vec;
10 
11 use serde::de;
12 use serde::de::IntoDeserializer;
13 use serde::ser;
14 
15 use crate::datetime::{self, DatetimeFromString};
16 pub use crate::datetime::{Datetime, DatetimeParseError};
17 
18 pub use crate::map::Map;
19 
20 /// Representation of a TOML value.
21 #[derive(PartialEq, Clone, Debug)]
22 pub enum Value {
23     /// Represents a TOML string
24     String(String),
25     /// Represents a TOML integer
26     Integer(i64),
27     /// Represents a TOML float
28     Float(f64),
29     /// Represents a TOML boolean
30     Boolean(bool),
31     /// Represents a TOML datetime
32     Datetime(Datetime),
33     /// Represents a TOML array
34     Array(Array),
35     /// Represents a TOML table
36     Table(Table),
37 }
38 
39 /// Type representing a TOML array, payload of the `Value::Array` variant
40 pub type Array = Vec<Value>;
41 
42 /// Type representing a TOML table, payload of the `Value::Table` variant.
43 /// By default it is backed by a BTreeMap, enable the `preserve_order` feature
44 /// to use a LinkedHashMap instead.
45 pub type Table = Map<String, Value>;
46 
47 impl Value {
48     /// Convert a `T` into `toml::Value` which is an enum that can represent
49     /// any valid TOML data.
50     ///
51     /// This conversion can fail if `T`'s implementation of `Serialize` decides to
52     /// fail, or if `T` contains a map with non-string keys.
try_from<T>(value: T) -> Result<Value, crate::ser::Error> where T: ser::Serialize,53     pub fn try_from<T>(value: T) -> Result<Value, crate::ser::Error>
54     where
55         T: ser::Serialize,
56     {
57         value.serialize(Serializer)
58     }
59 
60     /// Interpret a `toml::Value` as an instance of type `T`.
61     ///
62     /// This conversion can fail if the structure of the `Value` does not match the
63     /// structure expected by `T`, for example if `T` is a struct type but the
64     /// `Value` contains something other than a TOML table. It can also fail if the
65     /// structure is correct but `T`'s implementation of `Deserialize` decides that
66     /// something is wrong with the data, for example required struct fields are
67     /// missing from the TOML map or some number is too big to fit in the expected
68     /// primitive type.
try_into<'de, T>(self) -> Result<T, crate::de::Error> where T: de::Deserialize<'de>,69     pub fn try_into<'de, T>(self) -> Result<T, crate::de::Error>
70     where
71         T: de::Deserialize<'de>,
72     {
73         de::Deserialize::deserialize(self)
74     }
75 
76     /// Index into a TOML array or map. A string index can be used to access a
77     /// value in a map, and a usize index can be used to access an element of an
78     /// array.
79     ///
80     /// Returns `None` if the type of `self` does not match the type of the
81     /// index, for example if the index is a string and `self` is an array or a
82     /// number. Also returns `None` if the given key does not exist in the map
83     /// or the given index is not within the bounds of the array.
get<I: Index>(&self, index: I) -> Option<&Value>84     pub fn get<I: Index>(&self, index: I) -> Option<&Value> {
85         index.index(self)
86     }
87 
88     /// Mutably index into a TOML array or map. A string index can be used to
89     /// access a value in a map, and a usize index can be used to access an
90     /// element of an array.
91     ///
92     /// Returns `None` if the type of `self` does not match the type of the
93     /// index, for example if the index is a string and `self` is an array or a
94     /// number. Also returns `None` if the given key does not exist in the map
95     /// or the given index is not within the bounds of the array.
get_mut<I: Index>(&mut self, index: I) -> Option<&mut Value>96     pub fn get_mut<I: Index>(&mut self, index: I) -> Option<&mut Value> {
97         index.index_mut(self)
98     }
99 
100     /// Extracts the integer value if it is an integer.
as_integer(&self) -> Option<i64>101     pub fn as_integer(&self) -> Option<i64> {
102         match *self {
103             Value::Integer(i) => Some(i),
104             _ => None,
105         }
106     }
107 
108     /// Tests whether this value is an integer.
is_integer(&self) -> bool109     pub fn is_integer(&self) -> bool {
110         self.as_integer().is_some()
111     }
112 
113     /// Extracts the float value if it is a float.
as_float(&self) -> Option<f64>114     pub fn as_float(&self) -> Option<f64> {
115         match *self {
116             Value::Float(f) => Some(f),
117             _ => None,
118         }
119     }
120 
121     /// Tests whether this value is a float.
is_float(&self) -> bool122     pub fn is_float(&self) -> bool {
123         self.as_float().is_some()
124     }
125 
126     /// Extracts the boolean value if it is a boolean.
as_bool(&self) -> Option<bool>127     pub fn as_bool(&self) -> Option<bool> {
128         match *self {
129             Value::Boolean(b) => Some(b),
130             _ => None,
131         }
132     }
133 
134     /// Tests whether this value is a boolean.
is_bool(&self) -> bool135     pub fn is_bool(&self) -> bool {
136         self.as_bool().is_some()
137     }
138 
139     /// Extracts the string of this value if it is a string.
as_str(&self) -> Option<&str>140     pub fn as_str(&self) -> Option<&str> {
141         match *self {
142             Value::String(ref s) => Some(&**s),
143             _ => None,
144         }
145     }
146 
147     /// Tests if this value is a string.
is_str(&self) -> bool148     pub fn is_str(&self) -> bool {
149         self.as_str().is_some()
150     }
151 
152     /// Extracts the datetime value if it is a datetime.
153     ///
154     /// Note that a parsed TOML value will only contain ISO 8601 dates. An
155     /// example date is:
156     ///
157     /// ```notrust
158     /// 1979-05-27T07:32:00Z
159     /// ```
as_datetime(&self) -> Option<&Datetime>160     pub fn as_datetime(&self) -> Option<&Datetime> {
161         match *self {
162             Value::Datetime(ref s) => Some(s),
163             _ => None,
164         }
165     }
166 
167     /// Tests whether this value is a datetime.
is_datetime(&self) -> bool168     pub fn is_datetime(&self) -> bool {
169         self.as_datetime().is_some()
170     }
171 
172     /// Extracts the array value if it is an array.
as_array(&self) -> Option<&Vec<Value>>173     pub fn as_array(&self) -> Option<&Vec<Value>> {
174         match *self {
175             Value::Array(ref s) => Some(s),
176             _ => None,
177         }
178     }
179 
180     /// Extracts the array value if it is an array.
as_array_mut(&mut self) -> Option<&mut Vec<Value>>181     pub fn as_array_mut(&mut self) -> Option<&mut Vec<Value>> {
182         match *self {
183             Value::Array(ref mut s) => Some(s),
184             _ => None,
185         }
186     }
187 
188     /// Tests whether this value is an array.
is_array(&self) -> bool189     pub fn is_array(&self) -> bool {
190         self.as_array().is_some()
191     }
192 
193     /// Extracts the table value if it is a table.
as_table(&self) -> Option<&Table>194     pub fn as_table(&self) -> Option<&Table> {
195         match *self {
196             Value::Table(ref s) => Some(s),
197             _ => None,
198         }
199     }
200 
201     /// Extracts the table value if it is a table.
as_table_mut(&mut self) -> Option<&mut Table>202     pub fn as_table_mut(&mut self) -> Option<&mut Table> {
203         match *self {
204             Value::Table(ref mut s) => Some(s),
205             _ => None,
206         }
207     }
208 
209     /// Tests whether this value is a table.
is_table(&self) -> bool210     pub fn is_table(&self) -> bool {
211         self.as_table().is_some()
212     }
213 
214     /// Tests whether this and another value have the same type.
same_type(&self, other: &Value) -> bool215     pub fn same_type(&self, other: &Value) -> bool {
216         discriminant(self) == discriminant(other)
217     }
218 
219     /// Returns a human-readable representation of the type of this value.
type_str(&self) -> &'static str220     pub fn type_str(&self) -> &'static str {
221         match *self {
222             Value::String(..) => "string",
223             Value::Integer(..) => "integer",
224             Value::Float(..) => "float",
225             Value::Boolean(..) => "boolean",
226             Value::Datetime(..) => "datetime",
227             Value::Array(..) => "array",
228             Value::Table(..) => "table",
229         }
230     }
231 }
232 
233 impl<I> ops::Index<I> for Value
234 where
235     I: Index,
236 {
237     type Output = Value;
238 
index(&self, index: I) -> &Value239     fn index(&self, index: I) -> &Value {
240         self.get(index).expect("index not found")
241     }
242 }
243 
244 impl<I> ops::IndexMut<I> for Value
245 where
246     I: Index,
247 {
index_mut(&mut self, index: I) -> &mut Value248     fn index_mut(&mut self, index: I) -> &mut Value {
249         self.get_mut(index).expect("index not found")
250     }
251 }
252 
253 impl<'a> From<&'a str> for Value {
254     #[inline]
from(val: &'a str) -> Value255     fn from(val: &'a str) -> Value {
256         Value::String(val.to_string())
257     }
258 }
259 
260 impl<V: Into<Value>> From<Vec<V>> for Value {
from(val: Vec<V>) -> Value261     fn from(val: Vec<V>) -> Value {
262         Value::Array(val.into_iter().map(|v| v.into()).collect())
263     }
264 }
265 
266 impl<S: Into<String>, V: Into<Value>> From<BTreeMap<S, V>> for Value {
from(val: BTreeMap<S, V>) -> Value267     fn from(val: BTreeMap<S, V>) -> Value {
268         let table = val.into_iter().map(|(s, v)| (s.into(), v.into())).collect();
269 
270         Value::Table(table)
271     }
272 }
273 
274 impl<S: Into<String> + Hash + Eq, V: Into<Value>> From<HashMap<S, V>> for Value {
from(val: HashMap<S, V>) -> Value275     fn from(val: HashMap<S, V>) -> Value {
276         let table = val.into_iter().map(|(s, v)| (s.into(), v.into())).collect();
277 
278         Value::Table(table)
279     }
280 }
281 
282 macro_rules! impl_into_value {
283     ($variant:ident : $T:ty) => {
284         impl From<$T> for Value {
285             #[inline]
286             fn from(val: $T) -> Value {
287                 Value::$variant(val.into())
288             }
289         }
290     };
291 }
292 
293 impl_into_value!(String: String);
294 impl_into_value!(Integer: i64);
295 impl_into_value!(Integer: i32);
296 impl_into_value!(Integer: i8);
297 impl_into_value!(Integer: u8);
298 impl_into_value!(Integer: u32);
299 impl_into_value!(Float: f64);
300 impl_into_value!(Float: f32);
301 impl_into_value!(Boolean: bool);
302 impl_into_value!(Datetime: Datetime);
303 impl_into_value!(Table: Table);
304 
305 /// Types that can be used to index a `toml::Value`
306 ///
307 /// Currently this is implemented for `usize` to index arrays and `str` to index
308 /// tables.
309 ///
310 /// This trait is sealed and not intended for implementation outside of the
311 /// `toml` crate.
312 pub trait Index: Sealed {
313     #[doc(hidden)]
index<'a>(&self, val: &'a Value) -> Option<&'a Value>314     fn index<'a>(&self, val: &'a Value) -> Option<&'a Value>;
315     #[doc(hidden)]
index_mut<'a>(&self, val: &'a mut Value) -> Option<&'a mut Value>316     fn index_mut<'a>(&self, val: &'a mut Value) -> Option<&'a mut Value>;
317 }
318 
319 /// An implementation detail that should not be implemented, this will change in
320 /// the future and break code otherwise.
321 #[doc(hidden)]
322 pub trait Sealed {}
323 impl Sealed for usize {}
324 impl Sealed for str {}
325 impl Sealed for String {}
326 impl<'a, T: Sealed + ?Sized> Sealed for &'a T {}
327 
328 impl Index for usize {
index<'a>(&self, val: &'a Value) -> Option<&'a Value>329     fn index<'a>(&self, val: &'a Value) -> Option<&'a Value> {
330         match *val {
331             Value::Array(ref a) => a.get(*self),
332             _ => None,
333         }
334     }
335 
index_mut<'a>(&self, val: &'a mut Value) -> Option<&'a mut Value>336     fn index_mut<'a>(&self, val: &'a mut Value) -> Option<&'a mut Value> {
337         match *val {
338             Value::Array(ref mut a) => a.get_mut(*self),
339             _ => None,
340         }
341     }
342 }
343 
344 impl Index for str {
index<'a>(&self, val: &'a Value) -> Option<&'a Value>345     fn index<'a>(&self, val: &'a Value) -> Option<&'a Value> {
346         match *val {
347             Value::Table(ref a) => a.get(self),
348             _ => None,
349         }
350     }
351 
index_mut<'a>(&self, val: &'a mut Value) -> Option<&'a mut Value>352     fn index_mut<'a>(&self, val: &'a mut Value) -> Option<&'a mut Value> {
353         match *val {
354             Value::Table(ref mut a) => a.get_mut(self),
355             _ => None,
356         }
357     }
358 }
359 
360 impl Index for String {
index<'a>(&self, val: &'a Value) -> Option<&'a Value>361     fn index<'a>(&self, val: &'a Value) -> Option<&'a Value> {
362         self[..].index(val)
363     }
364 
index_mut<'a>(&self, val: &'a mut Value) -> Option<&'a mut Value>365     fn index_mut<'a>(&self, val: &'a mut Value) -> Option<&'a mut Value> {
366         self[..].index_mut(val)
367     }
368 }
369 
370 impl<'s, T: ?Sized> Index for &'s T
371 where
372     T: Index,
373 {
index<'a>(&self, val: &'a Value) -> Option<&'a Value>374     fn index<'a>(&self, val: &'a Value) -> Option<&'a Value> {
375         (**self).index(val)
376     }
377 
index_mut<'a>(&self, val: &'a mut Value) -> Option<&'a mut Value>378     fn index_mut<'a>(&self, val: &'a mut Value) -> Option<&'a mut Value> {
379         (**self).index_mut(val)
380     }
381 }
382 
383 impl fmt::Display for Value {
fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result384     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
385         crate::ser::to_string(self)
386             .expect("Unable to represent value as string")
387             .fmt(f)
388     }
389 }
390 
391 impl FromStr for Value {
392     type Err = crate::de::Error;
from_str(s: &str) -> Result<Value, Self::Err>393     fn from_str(s: &str) -> Result<Value, Self::Err> {
394         crate::from_str(s)
395     }
396 }
397 
398 impl ser::Serialize for Value {
serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error> where S: ser::Serializer,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 
445 impl<'de> de::Deserialize<'de> for Value {
deserialize<D>(deserializer: D) -> Result<Value, D::Error> where D: de::Deserializer<'de>,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: DatetimeFromString = visitor.next_value()?;
522                         return Ok(Value::Datetime(date.value));
523                     }
524                     None => return Ok(Value::Table(Map::new())),
525                     Some(false) => {}
526                 }
527                 let mut map = Map::new();
528                 map.insert(key, visitor.next_value()?);
529                 while let Some(key) = visitor.next_key()? {
530                     if map.contains_key(&key) {
531                         let msg = format!("duplicate key: `{}`", key);
532                         return Err(de::Error::custom(msg));
533                     }
534                     map.insert(key, visitor.next_value()?);
535                 }
536                 Ok(Value::Table(map))
537             }
538         }
539 
540         deserializer.deserialize_any(ValueVisitor)
541     }
542 }
543 
544 impl<'de> de::Deserializer<'de> for Value {
545     type Error = crate::de::Error;
546 
deserialize_any<V>(self, visitor: V) -> Result<V::Value, crate::de::Error> where V: de::Visitor<'de>,547     fn deserialize_any<V>(self, visitor: V) -> Result<V::Value, crate::de::Error>
548     where
549         V: de::Visitor<'de>,
550     {
551         match self {
552             Value::Boolean(v) => visitor.visit_bool(v),
553             Value::Integer(n) => visitor.visit_i64(n),
554             Value::Float(n) => visitor.visit_f64(n),
555             Value::String(v) => visitor.visit_string(v),
556             Value::Datetime(v) => visitor.visit_string(v.to_string()),
557             Value::Array(v) => {
558                 let len = v.len();
559                 let mut deserializer = SeqDeserializer::new(v);
560                 let seq = visitor.visit_seq(&mut deserializer)?;
561                 let remaining = deserializer.iter.len();
562                 if remaining == 0 {
563                     Ok(seq)
564                 } else {
565                     Err(de::Error::invalid_length(len, &"fewer elements in array"))
566                 }
567             }
568             Value::Table(v) => {
569                 let len = v.len();
570                 let mut deserializer = MapDeserializer::new(v);
571                 let map = visitor.visit_map(&mut deserializer)?;
572                 let remaining = deserializer.iter.len();
573                 if remaining == 0 {
574                     Ok(map)
575                 } else {
576                     Err(de::Error::invalid_length(len, &"fewer elements in map"))
577                 }
578             }
579         }
580     }
581 
582     #[inline]
deserialize_enum<V>( self, _name: &str, _variants: &'static [&'static str], visitor: V, ) -> Result<V::Value, crate::de::Error> where V: de::Visitor<'de>,583     fn deserialize_enum<V>(
584         self,
585         _name: &str,
586         _variants: &'static [&'static str],
587         visitor: V,
588     ) -> Result<V::Value, crate::de::Error>
589     where
590         V: de::Visitor<'de>,
591     {
592         match self {
593             Value::String(variant) => visitor.visit_enum(variant.into_deserializer()),
594             _ => Err(de::Error::invalid_type(
595                 de::Unexpected::UnitVariant,
596                 &"string only",
597             )),
598         }
599     }
600 
601     // `None` is interpreted as a missing field so be sure to implement `Some`
602     // as a present field.
deserialize_option<V>(self, visitor: V) -> Result<V::Value, crate::de::Error> where V: de::Visitor<'de>,603     fn deserialize_option<V>(self, visitor: V) -> Result<V::Value, crate::de::Error>
604     where
605         V: de::Visitor<'de>,
606     {
607         visitor.visit_some(self)
608     }
609 
deserialize_newtype_struct<V>( self, _name: &'static str, visitor: V, ) -> Result<V::Value, crate::de::Error> where V: de::Visitor<'de>,610     fn deserialize_newtype_struct<V>(
611         self,
612         _name: &'static str,
613         visitor: V,
614     ) -> Result<V::Value, crate::de::Error>
615     where
616         V: de::Visitor<'de>,
617     {
618         visitor.visit_newtype_struct(self)
619     }
620 
621     serde::forward_to_deserialize_any! {
622         bool u8 u16 u32 u64 i8 i16 i32 i64 f32 f64 char str string unit seq
623         bytes byte_buf map unit_struct tuple_struct struct
624         tuple ignored_any identifier
625     }
626 }
627 
628 struct SeqDeserializer {
629     iter: vec::IntoIter<Value>,
630 }
631 
632 impl SeqDeserializer {
new(vec: Vec<Value>) -> Self633     fn new(vec: Vec<Value>) -> Self {
634         SeqDeserializer {
635             iter: vec.into_iter(),
636         }
637     }
638 }
639 
640 impl<'de> de::SeqAccess<'de> for SeqDeserializer {
641     type Error = crate::de::Error;
642 
next_element_seed<T>(&mut self, seed: T) -> Result<Option<T::Value>, crate::de::Error> where T: de::DeserializeSeed<'de>,643     fn next_element_seed<T>(&mut self, seed: T) -> Result<Option<T::Value>, crate::de::Error>
644     where
645         T: de::DeserializeSeed<'de>,
646     {
647         match self.iter.next() {
648             Some(value) => seed.deserialize(value).map(Some),
649             None => Ok(None),
650         }
651     }
652 
size_hint(&self) -> Option<usize>653     fn size_hint(&self) -> Option<usize> {
654         match self.iter.size_hint() {
655             (lower, Some(upper)) if lower == upper => Some(upper),
656             _ => None,
657         }
658     }
659 }
660 
661 struct MapDeserializer {
662     iter: <Map<String, Value> as IntoIterator>::IntoIter,
663     value: Option<(String, Value)>,
664 }
665 
666 impl MapDeserializer {
new(map: Map<String, Value>) -> Self667     fn new(map: Map<String, Value>) -> Self {
668         MapDeserializer {
669             iter: map.into_iter(),
670             value: None,
671         }
672     }
673 }
674 
675 impl<'de> de::MapAccess<'de> for MapDeserializer {
676     type Error = crate::de::Error;
677 
next_key_seed<T>(&mut self, seed: T) -> Result<Option<T::Value>, crate::de::Error> where T: de::DeserializeSeed<'de>,678     fn next_key_seed<T>(&mut self, seed: T) -> Result<Option<T::Value>, crate::de::Error>
679     where
680         T: de::DeserializeSeed<'de>,
681     {
682         match self.iter.next() {
683             Some((key, value)) => {
684                 self.value = Some((key.clone(), value));
685                 seed.deserialize(Value::String(key)).map(Some)
686             }
687             None => Ok(None),
688         }
689     }
690 
next_value_seed<T>(&mut self, seed: T) -> Result<T::Value, crate::de::Error> where T: de::DeserializeSeed<'de>,691     fn next_value_seed<T>(&mut self, seed: T) -> Result<T::Value, crate::de::Error>
692     where
693         T: de::DeserializeSeed<'de>,
694     {
695         let (key, res) = match self.value.take() {
696             Some((key, value)) => (key, seed.deserialize(value)),
697             None => return Err(de::Error::custom("value is missing")),
698         };
699         res.map_err(|mut error| {
700             error.add_key_context(&key);
701             error
702         })
703     }
704 
size_hint(&self) -> Option<usize>705     fn size_hint(&self) -> Option<usize> {
706         match self.iter.size_hint() {
707             (lower, Some(upper)) if lower == upper => Some(upper),
708             _ => None,
709         }
710     }
711 }
712 
713 impl<'de> de::IntoDeserializer<'de, crate::de::Error> for Value {
714     type Deserializer = Self;
715 
into_deserializer(self) -> Self716     fn into_deserializer(self) -> Self {
717         self
718     }
719 }
720 
721 struct Serializer;
722 
723 impl ser::Serializer for Serializer {
724     type Ok = Value;
725     type Error = crate::ser::Error;
726 
727     type SerializeSeq = SerializeVec;
728     type SerializeTuple = SerializeVec;
729     type SerializeTupleStruct = SerializeVec;
730     type SerializeTupleVariant = SerializeVec;
731     type SerializeMap = SerializeMap;
732     type SerializeStruct = SerializeMap;
733     type SerializeStructVariant = ser::Impossible<Value, crate::ser::Error>;
734 
serialize_bool(self, value: bool) -> Result<Value, crate::ser::Error>735     fn serialize_bool(self, value: bool) -> Result<Value, crate::ser::Error> {
736         Ok(Value::Boolean(value))
737     }
738 
serialize_i8(self, value: i8) -> Result<Value, crate::ser::Error>739     fn serialize_i8(self, value: i8) -> Result<Value, crate::ser::Error> {
740         self.serialize_i64(value.into())
741     }
742 
serialize_i16(self, value: i16) -> Result<Value, crate::ser::Error>743     fn serialize_i16(self, value: i16) -> Result<Value, crate::ser::Error> {
744         self.serialize_i64(value.into())
745     }
746 
serialize_i32(self, value: i32) -> Result<Value, crate::ser::Error>747     fn serialize_i32(self, value: i32) -> Result<Value, crate::ser::Error> {
748         self.serialize_i64(value.into())
749     }
750 
serialize_i64(self, value: i64) -> Result<Value, crate::ser::Error>751     fn serialize_i64(self, value: i64) -> Result<Value, crate::ser::Error> {
752         Ok(Value::Integer(value))
753     }
754 
serialize_u8(self, value: u8) -> Result<Value, crate::ser::Error>755     fn serialize_u8(self, value: u8) -> Result<Value, crate::ser::Error> {
756         self.serialize_i64(value.into())
757     }
758 
serialize_u16(self, value: u16) -> Result<Value, crate::ser::Error>759     fn serialize_u16(self, value: u16) -> Result<Value, crate::ser::Error> {
760         self.serialize_i64(value.into())
761     }
762 
serialize_u32(self, value: u32) -> Result<Value, crate::ser::Error>763     fn serialize_u32(self, value: u32) -> Result<Value, crate::ser::Error> {
764         self.serialize_i64(value.into())
765     }
766 
serialize_u64(self, value: u64) -> Result<Value, crate::ser::Error>767     fn serialize_u64(self, value: u64) -> Result<Value, crate::ser::Error> {
768         if value <= i64::max_value() as u64 {
769             self.serialize_i64(value as i64)
770         } else {
771             Err(ser::Error::custom("u64 value was too large"))
772         }
773     }
774 
serialize_f32(self, value: f32) -> Result<Value, crate::ser::Error>775     fn serialize_f32(self, value: f32) -> Result<Value, crate::ser::Error> {
776         self.serialize_f64(value.into())
777     }
778 
serialize_f64(self, value: f64) -> Result<Value, crate::ser::Error>779     fn serialize_f64(self, value: f64) -> Result<Value, crate::ser::Error> {
780         Ok(Value::Float(value))
781     }
782 
serialize_char(self, value: char) -> Result<Value, crate::ser::Error>783     fn serialize_char(self, value: char) -> Result<Value, crate::ser::Error> {
784         let mut s = String::new();
785         s.push(value);
786         self.serialize_str(&s)
787     }
788 
serialize_str(self, value: &str) -> Result<Value, crate::ser::Error>789     fn serialize_str(self, value: &str) -> Result<Value, crate::ser::Error> {
790         Ok(Value::String(value.to_owned()))
791     }
792 
serialize_bytes(self, value: &[u8]) -> Result<Value, crate::ser::Error>793     fn serialize_bytes(self, value: &[u8]) -> Result<Value, crate::ser::Error> {
794         let vec = value.iter().map(|&b| Value::Integer(b.into())).collect();
795         Ok(Value::Array(vec))
796     }
797 
serialize_unit(self) -> Result<Value, crate::ser::Error>798     fn serialize_unit(self) -> Result<Value, crate::ser::Error> {
799         Err(crate::ser::Error::UnsupportedType)
800     }
801 
serialize_unit_struct(self, _name: &'static str) -> Result<Value, crate::ser::Error>802     fn serialize_unit_struct(self, _name: &'static str) -> Result<Value, crate::ser::Error> {
803         Err(crate::ser::Error::UnsupportedType)
804     }
805 
serialize_unit_variant( self, _name: &'static str, _variant_index: u32, _variant: &'static str, ) -> Result<Value, crate::ser::Error>806     fn serialize_unit_variant(
807         self,
808         _name: &'static str,
809         _variant_index: u32,
810         _variant: &'static str,
811     ) -> Result<Value, crate::ser::Error> {
812         self.serialize_str(_variant)
813     }
814 
serialize_newtype_struct<T: ?Sized>( self, _name: &'static str, value: &T, ) -> Result<Value, crate::ser::Error> where T: ser::Serialize,815     fn serialize_newtype_struct<T: ?Sized>(
816         self,
817         _name: &'static str,
818         value: &T,
819     ) -> Result<Value, crate::ser::Error>
820     where
821         T: ser::Serialize,
822     {
823         value.serialize(self)
824     }
825 
serialize_newtype_variant<T: ?Sized>( self, _name: &'static str, _variant_index: u32, _variant: &'static str, _value: &T, ) -> Result<Value, crate::ser::Error> where T: ser::Serialize,826     fn serialize_newtype_variant<T: ?Sized>(
827         self,
828         _name: &'static str,
829         _variant_index: u32,
830         _variant: &'static str,
831         _value: &T,
832     ) -> Result<Value, crate::ser::Error>
833     where
834         T: ser::Serialize,
835     {
836         Err(crate::ser::Error::UnsupportedType)
837     }
838 
serialize_none(self) -> Result<Value, crate::ser::Error>839     fn serialize_none(self) -> Result<Value, crate::ser::Error> {
840         Err(crate::ser::Error::UnsupportedNone)
841     }
842 
serialize_some<T: ?Sized>(self, value: &T) -> Result<Value, crate::ser::Error> where T: ser::Serialize,843     fn serialize_some<T: ?Sized>(self, value: &T) -> Result<Value, crate::ser::Error>
844     where
845         T: ser::Serialize,
846     {
847         value.serialize(self)
848     }
849 
serialize_seq(self, len: Option<usize>) -> Result<Self::SerializeSeq, crate::ser::Error>850     fn serialize_seq(self, len: Option<usize>) -> Result<Self::SerializeSeq, crate::ser::Error> {
851         Ok(SerializeVec {
852             vec: Vec::with_capacity(len.unwrap_or(0)),
853         })
854     }
855 
serialize_tuple(self, len: usize) -> Result<Self::SerializeTuple, crate::ser::Error>856     fn serialize_tuple(self, len: usize) -> Result<Self::SerializeTuple, crate::ser::Error> {
857         self.serialize_seq(Some(len))
858     }
859 
serialize_tuple_struct( self, _name: &'static str, len: usize, ) -> Result<Self::SerializeTupleStruct, crate::ser::Error>860     fn serialize_tuple_struct(
861         self,
862         _name: &'static str,
863         len: usize,
864     ) -> Result<Self::SerializeTupleStruct, crate::ser::Error> {
865         self.serialize_seq(Some(len))
866     }
867 
serialize_tuple_variant( self, _name: &'static str, _variant_index: u32, _variant: &'static str, len: usize, ) -> Result<Self::SerializeTupleVariant, crate::ser::Error>868     fn serialize_tuple_variant(
869         self,
870         _name: &'static str,
871         _variant_index: u32,
872         _variant: &'static str,
873         len: usize,
874     ) -> Result<Self::SerializeTupleVariant, crate::ser::Error> {
875         self.serialize_seq(Some(len))
876     }
877 
serialize_map(self, _len: Option<usize>) -> Result<Self::SerializeMap, crate::ser::Error>878     fn serialize_map(self, _len: Option<usize>) -> Result<Self::SerializeMap, crate::ser::Error> {
879         Ok(SerializeMap {
880             map: Map::new(),
881             next_key: None,
882         })
883     }
884 
serialize_struct( self, _name: &'static str, len: usize, ) -> Result<Self::SerializeStruct, crate::ser::Error>885     fn serialize_struct(
886         self,
887         _name: &'static str,
888         len: usize,
889     ) -> Result<Self::SerializeStruct, crate::ser::Error> {
890         self.serialize_map(Some(len))
891     }
892 
serialize_struct_variant( self, _name: &'static str, _variant_index: u32, _variant: &'static str, _len: usize, ) -> Result<Self::SerializeStructVariant, crate::ser::Error>893     fn serialize_struct_variant(
894         self,
895         _name: &'static str,
896         _variant_index: u32,
897         _variant: &'static str,
898         _len: usize,
899     ) -> Result<Self::SerializeStructVariant, crate::ser::Error> {
900         Err(crate::ser::Error::UnsupportedType)
901     }
902 }
903 
904 struct SerializeVec {
905     vec: Vec<Value>,
906 }
907 
908 struct SerializeMap {
909     map: Map<String, Value>,
910     next_key: Option<String>,
911 }
912 
913 impl ser::SerializeSeq for SerializeVec {
914     type Ok = Value;
915     type Error = crate::ser::Error;
916 
serialize_element<T: ?Sized>(&mut self, value: &T) -> Result<(), crate::ser::Error> where T: ser::Serialize,917     fn serialize_element<T: ?Sized>(&mut self, value: &T) -> Result<(), crate::ser::Error>
918     where
919         T: ser::Serialize,
920     {
921         self.vec.push(Value::try_from(value)?);
922         Ok(())
923     }
924 
end(self) -> Result<Value, crate::ser::Error>925     fn end(self) -> Result<Value, crate::ser::Error> {
926         Ok(Value::Array(self.vec))
927     }
928 }
929 
930 impl ser::SerializeTuple for SerializeVec {
931     type Ok = Value;
932     type Error = crate::ser::Error;
933 
serialize_element<T: ?Sized>(&mut self, value: &T) -> Result<(), crate::ser::Error> where T: ser::Serialize,934     fn serialize_element<T: ?Sized>(&mut self, value: &T) -> Result<(), crate::ser::Error>
935     where
936         T: ser::Serialize,
937     {
938         ser::SerializeSeq::serialize_element(self, value)
939     }
940 
end(self) -> Result<Value, crate::ser::Error>941     fn end(self) -> Result<Value, crate::ser::Error> {
942         ser::SerializeSeq::end(self)
943     }
944 }
945 
946 impl ser::SerializeTupleStruct for SerializeVec {
947     type Ok = Value;
948     type Error = crate::ser::Error;
949 
serialize_field<T: ?Sized>(&mut self, value: &T) -> Result<(), crate::ser::Error> where T: ser::Serialize,950     fn serialize_field<T: ?Sized>(&mut self, value: &T) -> Result<(), crate::ser::Error>
951     where
952         T: ser::Serialize,
953     {
954         ser::SerializeSeq::serialize_element(self, value)
955     }
956 
end(self) -> Result<Value, crate::ser::Error>957     fn end(self) -> Result<Value, crate::ser::Error> {
958         ser::SerializeSeq::end(self)
959     }
960 }
961 
962 impl ser::SerializeTupleVariant for SerializeVec {
963     type Ok = Value;
964     type Error = crate::ser::Error;
965 
serialize_field<T: ?Sized>(&mut self, value: &T) -> Result<(), crate::ser::Error> where T: ser::Serialize,966     fn serialize_field<T: ?Sized>(&mut self, value: &T) -> Result<(), crate::ser::Error>
967     where
968         T: ser::Serialize,
969     {
970         ser::SerializeSeq::serialize_element(self, value)
971     }
972 
end(self) -> Result<Value, crate::ser::Error>973     fn end(self) -> Result<Value, crate::ser::Error> {
974         ser::SerializeSeq::end(self)
975     }
976 }
977 
978 impl ser::SerializeMap for SerializeMap {
979     type Ok = Value;
980     type Error = crate::ser::Error;
981 
serialize_key<T: ?Sized>(&mut self, key: &T) -> Result<(), crate::ser::Error> where T: ser::Serialize,982     fn serialize_key<T: ?Sized>(&mut self, key: &T) -> Result<(), crate::ser::Error>
983     where
984         T: ser::Serialize,
985     {
986         match Value::try_from(key)? {
987             Value::String(s) => self.next_key = Some(s),
988             _ => return Err(crate::ser::Error::KeyNotString),
989         };
990         Ok(())
991     }
992 
serialize_value<T: ?Sized>(&mut self, value: &T) -> Result<(), crate::ser::Error> where T: ser::Serialize,993     fn serialize_value<T: ?Sized>(&mut self, value: &T) -> Result<(), crate::ser::Error>
994     where
995         T: ser::Serialize,
996     {
997         let key = self.next_key.take();
998         let key = key.expect("serialize_value called before serialize_key");
999         match Value::try_from(value) {
1000             Ok(value) => {
1001                 self.map.insert(key, value);
1002             }
1003             Err(crate::ser::Error::UnsupportedNone) => {}
1004             Err(e) => return Err(e),
1005         }
1006         Ok(())
1007     }
1008 
end(self) -> Result<Value, crate::ser::Error>1009     fn end(self) -> Result<Value, crate::ser::Error> {
1010         Ok(Value::Table(self.map))
1011     }
1012 }
1013 
1014 impl ser::SerializeStruct for SerializeMap {
1015     type Ok = Value;
1016     type Error = crate::ser::Error;
1017 
serialize_field<T: ?Sized>( &mut self, key: &'static str, value: &T, ) -> Result<(), crate::ser::Error> where T: ser::Serialize,1018     fn serialize_field<T: ?Sized>(
1019         &mut self,
1020         key: &'static str,
1021         value: &T,
1022     ) -> Result<(), crate::ser::Error>
1023     where
1024         T: ser::Serialize,
1025     {
1026         ser::SerializeMap::serialize_key(self, key)?;
1027         ser::SerializeMap::serialize_value(self, value)
1028     }
1029 
end(self) -> Result<Value, crate::ser::Error>1030     fn end(self) -> Result<Value, crate::ser::Error> {
1031         ser::SerializeMap::end(self)
1032     }
1033 }
1034 
1035 struct DatetimeOrTable<'a> {
1036     key: &'a mut String,
1037 }
1038 
1039 impl<'a, 'de> de::DeserializeSeed<'de> for DatetimeOrTable<'a> {
1040     type Value = bool;
1041 
deserialize<D>(self, deserializer: D) -> Result<Self::Value, D::Error> where D: de::Deserializer<'de>,1042     fn deserialize<D>(self, deserializer: D) -> Result<Self::Value, D::Error>
1043     where
1044         D: de::Deserializer<'de>,
1045     {
1046         deserializer.deserialize_any(self)
1047     }
1048 }
1049 
1050 impl<'a, 'de> de::Visitor<'de> for DatetimeOrTable<'a> {
1051     type Value = bool;
1052 
expecting(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result1053     fn expecting(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
1054         formatter.write_str("a string key")
1055     }
1056 
visit_str<E>(self, s: &str) -> Result<bool, E> where E: de::Error,1057     fn visit_str<E>(self, s: &str) -> Result<bool, E>
1058     where
1059         E: de::Error,
1060     {
1061         if s == datetime::FIELD {
1062             Ok(true)
1063         } else {
1064             self.key.push_str(s);
1065             Ok(false)
1066         }
1067     }
1068 
visit_string<E>(self, s: String) -> Result<bool, E> where E: de::Error,1069     fn visit_string<E>(self, s: String) -> Result<bool, E>
1070     where
1071         E: de::Error,
1072     {
1073         if s == datetime::FIELD {
1074             Ok(true)
1075         } else {
1076             *self.key = s;
1077             Ok(false)
1078         }
1079     }
1080 }
1081