1//! Definition of a TOML value
2
3use std::collections::{BTreeMap, HashMap};
4use std::fmt;
5use std::hash::Hash;
6use std::mem::discriminant;
7use std::ops;
8use std::str::FromStr;
9use std::vec;
10
11use serde::de;
12use serde::de::IntoDeserializer;
13use serde::ser;
14
15use crate::datetime::{self, DatetimeFromString};
16pub use crate::datetime::{Date, Datetime, DatetimeParseError, Offset, Time};
17
18pub use crate::map::{Entry, Map};
19
20/// Representation of a TOML value.
21#[derive(PartialEq, Clone, Debug)]
22pub 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
40pub 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.
45pub type Table = Map<String, Value>;
46
47impl 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.
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.
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.
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.
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.
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.
109 pub fn is_integer(&self) -> bool {
110 self.as_integer().is_some()
111 }
112
113 /// Extracts the float value if it is a float.
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.
122 pub fn is_float(&self) -> bool {
123 self.as_float().is_some()
124 }
125
126 /// Extracts the boolean value if it is a boolean.
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.
135 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.
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.
148 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 /// ```
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.
168 pub fn is_datetime(&self) -> bool {
169 self.as_datetime().is_some()
170 }
171
172 /// Extracts the array value if it is an array.
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.
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.
189 pub fn is_array(&self) -> bool {
190 self.as_array().is_some()
191 }
192
193 /// Extracts the table value if it is a 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.
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.
210 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.
215 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.
220 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
233impl<I> ops::Index<I> for Value
234where
235 I: Index,
236{
237 type Output = Value;
238
239 fn index(&self, index: I) -> &Value {
240 self.get(index).expect(msg:"index not found")
241 }
242}
243
244impl<I> ops::IndexMut<I> for Value
245where
246 I: Index,
247{
248 fn index_mut(&mut self, index: I) -> &mut Value {
249 self.get_mut(index).expect(msg:"index not found")
250 }
251}
252
253impl<'a> From<&'a str> for Value {
254 #[inline]
255 fn from(val: &'a str) -> Value {
256 Value::String(val.to_string())
257 }
258}
259
260impl<V: Into<Value>> From<Vec<V>> for Value {
261 fn from(val: Vec<V>) -> Value {
262 Value::Array(val.into_iter().map(|v: V| v.into()).collect())
263 }
264}
265
266impl<S: Into<String>, V: Into<Value>> From<BTreeMap<S, V>> for Value {
267 fn from(val: BTreeMap<S, V>) -> Value {
268 let table: Map = val.into_iter().map(|(s: S, v: V)| (s.into(), v.into())).collect();
269
270 Value::Table(table)
271 }
272}
273
274impl<S: Into<String> + Hash + Eq, V: Into<Value>> From<HashMap<S, V>> for Value {
275 fn from(val: HashMap<S, V>) -> Value {
276 let table: Map = val.into_iter().map(|(s: S, v: V)| (s.into(), v.into())).collect();
277
278 Value::Table(table)
279 }
280}
281
282macro_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
293impl_into_value!(String: String);
294impl_into_value!(Integer: i64);
295impl_into_value!(Integer: i32);
296impl_into_value!(Integer: i8);
297impl_into_value!(Integer: u8);
298impl_into_value!(Integer: u32);
299impl_into_value!(Float: f64);
300impl_into_value!(Float: f32);
301impl_into_value!(Boolean: bool);
302impl_into_value!(Datetime: Datetime);
303impl_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.
312pub trait Index: Sealed {
313 #[doc(hidden)]
314 fn index<'a>(&self, val: &'a Value) -> Option<&'a Value>;
315 #[doc(hidden)]
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)]
322pub trait Sealed {}
323impl Sealed for usize {}
324impl Sealed for str {}
325impl Sealed for String {}
326impl<'a, T: Sealed + ?Sized> Sealed for &'a T {}
327
328impl Index for usize {
329 fn index<'a>(&self, val: &'a Value) -> Option<&'a Value> {
330 match *val {
331 Value::Array(ref a: &Vec) => a.get(*self),
332 _ => None,
333 }
334 }
335
336 fn index_mut<'a>(&self, val: &'a mut Value) -> Option<&'a mut Value> {
337 match *val {
338 Value::Array(ref mut a: &mut Vec) => a.get_mut(*self),
339 _ => None,
340 }
341 }
342}
343
344impl Index for str {
345 fn index<'a>(&self, val: &'a Value) -> Option<&'a Value> {
346 match *val {
347 Value::Table(ref a: &Map) => a.get(self),
348 _ => None,
349 }
350 }
351
352 fn index_mut<'a>(&self, val: &'a mut Value) -> Option<&'a mut Value> {
353 match *val {
354 Value::Table(ref mut a: &mut Map) => a.get_mut(self),
355 _ => None,
356 }
357 }
358}
359
360impl Index for String {
361 fn index<'a>(&self, val: &'a Value) -> Option<&'a Value> {
362 self[..].index(val)
363 }
364
365 fn index_mut<'a>(&self, val: &'a mut Value) -> Option<&'a mut Value> {
366 self[..].index_mut(val)
367 }
368}
369
370impl<'s, T: ?Sized> Index for &'s T
371where
372 T: Index,
373{
374 fn index<'a>(&self, val: &'a Value) -> Option<&'a Value> {
375 (**self).index(val)
376 }
377
378 fn index_mut<'a>(&self, val: &'a mut Value) -> Option<&'a mut Value> {
379 (**self).index_mut(val)
380 }
381}
382
383impl fmt::Display for Value {
384 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
385 crateString::ser::to_string(self)
386 .expect(msg:"Unable to represent value as string")
387 .fmt(f)
388 }
389}
390
391impl 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: 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::<String>()? {
530 if let 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
545impl<'de> de::Deserializer<'de> for Value {
546 type Error = crate::de::Error;
547
548 fn deserialize_any<V>(self, visitor: V) -> Result<V::Value, crate::de::Error>
549 where
550 V: de::Visitor<'de>,
551 {
552 match self {
553 Value::Boolean(v) => visitor.visit_bool(v),
554 Value::Integer(n) => visitor.visit_i64(n),
555 Value::Float(n) => visitor.visit_f64(n),
556 Value::String(v) => visitor.visit_string(v),
557 Value::Datetime(v) => visitor.visit_string(v.to_string()),
558 Value::Array(v) => {
559 let len = v.len();
560 let mut deserializer = SeqDeserializer::new(v);
561 let seq = visitor.visit_seq(&mut deserializer)?;
562 let remaining = deserializer.iter.len();
563 if remaining == 0 {
564 Ok(seq)
565 } else {
566 Err(de::Error::invalid_length(len, &"fewer elements in array"))
567 }
568 }
569 Value::Table(v) => {
570 let len = v.len();
571 let mut deserializer = MapDeserializer::new(v);
572 let map = visitor.visit_map(&mut deserializer)?;
573 let remaining = deserializer.iter.len();
574 if remaining == 0 {
575 Ok(map)
576 } else {
577 Err(de::Error::invalid_length(len, &"fewer elements in map"))
578 }
579 }
580 }
581 }
582
583 #[inline]
584 fn deserialize_enum<V>(
585 self,
586 _name: &str,
587 _variants: &'static [&'static str],
588 visitor: V,
589 ) -> Result<V::Value, crate::de::Error>
590 where
591 V: de::Visitor<'de>,
592 {
593 match self {
594 Value::String(variant) => visitor.visit_enum(variant.into_deserializer()),
595 _ => Err(de::Error::invalid_type(
596 de::Unexpected::UnitVariant,
597 &"string only",
598 )),
599 }
600 }
601
602 // `None` is interpreted as a missing field so be sure to implement `Some`
603 // as a present field.
604 fn deserialize_option<V>(self, visitor: V) -> Result<V::Value, crate::de::Error>
605 where
606 V: de::Visitor<'de>,
607 {
608 visitor.visit_some(self)
609 }
610
611 fn deserialize_newtype_struct<V>(
612 self,
613 _name: &'static str,
614 visitor: V,
615 ) -> Result<V::Value, crate::de::Error>
616 where
617 V: de::Visitor<'de>,
618 {
619 visitor.visit_newtype_struct(self)
620 }
621
622 serde::forward_to_deserialize_any! {
623 bool u8 u16 u32 u64 i8 i16 i32 i64 f32 f64 char str string unit seq
624 bytes byte_buf map unit_struct tuple_struct struct
625 tuple ignored_any identifier
626 }
627}
628
629struct SeqDeserializer {
630 iter: vec::IntoIter<Value>,
631}
632
633impl SeqDeserializer {
634 fn new(vec: Vec<Value>) -> Self {
635 SeqDeserializer {
636 iter: vec.into_iter(),
637 }
638 }
639}
640
641impl<'de> de::SeqAccess<'de> for SeqDeserializer {
642 type Error = crate::de::Error;
643
644 fn next_element_seed<T>(&mut self, seed: T) -> Result<Option<T::Value>, crate::de::Error>
645 where
646 T: de::DeserializeSeed<'de>,
647 {
648 match self.iter.next() {
649 Some(value: Value) => seed.deserialize(value).map(op:Some),
650 None => Ok(None),
651 }
652 }
653
654 fn size_hint(&self) -> Option<usize> {
655 match self.iter.size_hint() {
656 (lower: usize, Some(upper: usize)) if lower == upper => Some(upper),
657 _ => None,
658 }
659 }
660}
661
662struct MapDeserializer {
663 iter: <Map<String, Value> as IntoIterator>::IntoIter,
664 value: Option<(String, Value)>,
665}
666
667impl MapDeserializer {
668 fn new(map: Map<String, Value>) -> Self {
669 MapDeserializer {
670 iter: map.into_iter(),
671 value: None,
672 }
673 }
674}
675
676impl<'de> de::MapAccess<'de> for MapDeserializer {
677 type Error = crate::de::Error;
678
679 fn next_key_seed<T>(&mut self, seed: T) -> Result<Option<T::Value>, crate::de::Error>
680 where
681 T: de::DeserializeSeed<'de>,
682 {
683 match self.iter.next() {
684 Some((key, value)) => {
685 self.value = Some((key.clone(), value));
686 seed.deserialize(Value::String(key)).map(Some)
687 }
688 None => Ok(None),
689 }
690 }
691
692 fn next_value_seed<T>(&mut self, seed: T) -> Result<T::Value, crate::de::Error>
693 where
694 T: de::DeserializeSeed<'de>,
695 {
696 let (key, res) = match self.value.take() {
697 Some((key, value)) => (key, seed.deserialize(value)),
698 None => return Err(de::Error::custom("value is missing")),
699 };
700 res.map_err(|mut error| {
701 error.add_key_context(&key);
702 error
703 })
704 }
705
706 fn size_hint(&self) -> Option<usize> {
707 match self.iter.size_hint() {
708 (lower, Some(upper)) if lower == upper => Some(upper),
709 _ => None,
710 }
711 }
712}
713
714impl<'de> de::IntoDeserializer<'de, crate::de::Error> for Value {
715 type Deserializer = Self;
716
717 fn into_deserializer(self) -> Self {
718 self
719 }
720}
721
722struct Serializer;
723
724impl ser::Serializer for Serializer {
725 type Ok = Value;
726 type Error = crate::ser::Error;
727
728 type SerializeSeq = SerializeVec;
729 type SerializeTuple = SerializeVec;
730 type SerializeTupleStruct = SerializeVec;
731 type SerializeTupleVariant = SerializeVec;
732 type SerializeMap = SerializeMap;
733 type SerializeStruct = SerializeMap;
734 type SerializeStructVariant = ser::Impossible<Value, crate::ser::Error>;
735
736 fn serialize_bool(self, value: bool) -> Result<Value, crate::ser::Error> {
737 Ok(Value::Boolean(value))
738 }
739
740 fn serialize_i8(self, value: i8) -> Result<Value, crate::ser::Error> {
741 self.serialize_i64(value.into())
742 }
743
744 fn serialize_i16(self, value: i16) -> Result<Value, crate::ser::Error> {
745 self.serialize_i64(value.into())
746 }
747
748 fn serialize_i32(self, value: i32) -> Result<Value, crate::ser::Error> {
749 self.serialize_i64(value.into())
750 }
751
752 fn serialize_i64(self, value: i64) -> Result<Value, crate::ser::Error> {
753 Ok(Value::Integer(value))
754 }
755
756 fn serialize_u8(self, value: u8) -> Result<Value, crate::ser::Error> {
757 self.serialize_i64(value.into())
758 }
759
760 fn serialize_u16(self, value: u16) -> Result<Value, crate::ser::Error> {
761 self.serialize_i64(value.into())
762 }
763
764 fn serialize_u32(self, value: u32) -> Result<Value, crate::ser::Error> {
765 self.serialize_i64(value.into())
766 }
767
768 fn serialize_u64(self, value: u64) -> Result<Value, crate::ser::Error> {
769 if value <= i64::max_value() as u64 {
770 self.serialize_i64(value as i64)
771 } else {
772 Err(ser::Error::custom("u64 value was too large"))
773 }
774 }
775
776 fn serialize_f32(self, value: f32) -> Result<Value, crate::ser::Error> {
777 self.serialize_f64(value.into())
778 }
779
780 fn serialize_f64(self, value: f64) -> Result<Value, crate::ser::Error> {
781 Ok(Value::Float(value))
782 }
783
784 fn serialize_char(self, value: char) -> Result<Value, crate::ser::Error> {
785 let mut s = String::new();
786 s.push(value);
787 self.serialize_str(&s)
788 }
789
790 fn serialize_str(self, value: &str) -> Result<Value, crate::ser::Error> {
791 Ok(Value::String(value.to_owned()))
792 }
793
794 fn serialize_bytes(self, value: &[u8]) -> Result<Value, crate::ser::Error> {
795 let vec = value.iter().map(|&b| Value::Integer(b.into())).collect();
796 Ok(Value::Array(vec))
797 }
798
799 fn serialize_unit(self) -> Result<Value, crate::ser::Error> {
800 Err(crate::ser::Error::UnsupportedType)
801 }
802
803 fn serialize_unit_struct(self, _name: &'static str) -> Result<Value, crate::ser::Error> {
804 Err(crate::ser::Error::UnsupportedType)
805 }
806
807 fn serialize_unit_variant(
808 self,
809 _name: &'static str,
810 _variant_index: u32,
811 _variant: &'static str,
812 ) -> Result<Value, crate::ser::Error> {
813 self.serialize_str(_variant)
814 }
815
816 fn serialize_newtype_struct<T: ?Sized>(
817 self,
818 _name: &'static str,
819 value: &T,
820 ) -> Result<Value, crate::ser::Error>
821 where
822 T: ser::Serialize,
823 {
824 value.serialize(self)
825 }
826
827 fn serialize_newtype_variant<T: ?Sized>(
828 self,
829 _name: &'static str,
830 _variant_index: u32,
831 _variant: &'static str,
832 _value: &T,
833 ) -> Result<Value, crate::ser::Error>
834 where
835 T: ser::Serialize,
836 {
837 Err(crate::ser::Error::UnsupportedType)
838 }
839
840 fn serialize_none(self) -> Result<Value, crate::ser::Error> {
841 Err(crate::ser::Error::UnsupportedNone)
842 }
843
844 fn serialize_some<T: ?Sized>(self, value: &T) -> Result<Value, crate::ser::Error>
845 where
846 T: ser::Serialize,
847 {
848 value.serialize(self)
849 }
850
851 fn serialize_seq(self, len: Option<usize>) -> Result<Self::SerializeSeq, crate::ser::Error> {
852 Ok(SerializeVec {
853 vec: Vec::with_capacity(len.unwrap_or(0)),
854 })
855 }
856
857 fn serialize_tuple(self, len: usize) -> Result<Self::SerializeTuple, crate::ser::Error> {
858 self.serialize_seq(Some(len))
859 }
860
861 fn serialize_tuple_struct(
862 self,
863 _name: &'static str,
864 len: usize,
865 ) -> Result<Self::SerializeTupleStruct, crate::ser::Error> {
866 self.serialize_seq(Some(len))
867 }
868
869 fn serialize_tuple_variant(
870 self,
871 _name: &'static str,
872 _variant_index: u32,
873 _variant: &'static str,
874 len: usize,
875 ) -> Result<Self::SerializeTupleVariant, crate::ser::Error> {
876 self.serialize_seq(Some(len))
877 }
878
879 fn serialize_map(self, _len: Option<usize>) -> Result<Self::SerializeMap, crate::ser::Error> {
880 Ok(SerializeMap {
881 map: Map::new(),
882 next_key: None,
883 })
884 }
885
886 fn serialize_struct(
887 self,
888 _name: &'static str,
889 len: usize,
890 ) -> Result<Self::SerializeStruct, crate::ser::Error> {
891 self.serialize_map(Some(len))
892 }
893
894 fn serialize_struct_variant(
895 self,
896 _name: &'static str,
897 _variant_index: u32,
898 _variant: &'static str,
899 _len: usize,
900 ) -> Result<Self::SerializeStructVariant, crate::ser::Error> {
901 Err(crate::ser::Error::UnsupportedType)
902 }
903}
904
905struct SerializeVec {
906 vec: Vec<Value>,
907}
908
909struct SerializeMap {
910 map: Map<String, Value>,
911 next_key: Option<String>,
912}
913
914impl ser::SerializeSeq for SerializeVec {
915 type Ok = Value;
916 type Error = crate::ser::Error;
917
918 fn serialize_element<T: ?Sized>(&mut self, value: &T) -> Result<(), crate::ser::Error>
919 where
920 T: ser::Serialize,
921 {
922 self.vec.push(Value::try_from(value)?);
923 Ok(())
924 }
925
926 fn end(self) -> Result<Value, crate::ser::Error> {
927 Ok(Value::Array(self.vec))
928 }
929}
930
931impl ser::SerializeTuple for SerializeVec {
932 type Ok = Value;
933 type Error = crate::ser::Error;
934
935 fn serialize_element<T: ?Sized>(&mut self, value: &T) -> Result<(), crate::ser::Error>
936 where
937 T: ser::Serialize,
938 {
939 ser::SerializeSeq::serialize_element(self, value)
940 }
941
942 fn end(self) -> Result<Value, crate::ser::Error> {
943 ser::SerializeSeq::end(self)
944 }
945}
946
947impl ser::SerializeTupleStruct for SerializeVec {
948 type Ok = Value;
949 type Error = crate::ser::Error;
950
951 fn serialize_field<T: ?Sized>(&mut self, value: &T) -> Result<(), crate::ser::Error>
952 where
953 T: ser::Serialize,
954 {
955 ser::SerializeSeq::serialize_element(self, value)
956 }
957
958 fn end(self) -> Result<Value, crate::ser::Error> {
959 ser::SerializeSeq::end(self)
960 }
961}
962
963impl ser::SerializeTupleVariant for SerializeVec {
964 type Ok = Value;
965 type Error = crate::ser::Error;
966
967 fn serialize_field<T: ?Sized>(&mut self, value: &T) -> Result<(), crate::ser::Error>
968 where
969 T: ser::Serialize,
970 {
971 ser::SerializeSeq::serialize_element(self, value)
972 }
973
974 fn end(self) -> Result<Value, crate::ser::Error> {
975 ser::SerializeSeq::end(self)
976 }
977}
978
979impl ser::SerializeMap for SerializeMap {
980 type Ok = Value;
981 type Error = crate::ser::Error;
982
983 fn serialize_key<T: ?Sized>(&mut self, key: &T) -> Result<(), crate::ser::Error>
984 where
985 T: ser::Serialize,
986 {
987 match Value::try_from(key)? {
988 Value::String(s) => self.next_key = Some(s),
989 _ => return Err(crate::ser::Error::KeyNotString),
990 };
991 Ok(())
992 }
993
994 fn serialize_value<T: ?Sized>(&mut self, value: &T) -> Result<(), crate::ser::Error>
995 where
996 T: ser::Serialize,
997 {
998 let key = self.next_key.take();
999 let key = key.expect("serialize_value called before serialize_key");
1000 match Value::try_from(value) {
1001 Ok(value) => {
1002 self.map.insert(key, value);
1003 }
1004 Err(crate::ser::Error::UnsupportedNone) => {}
1005 Err(e) => return Err(e),
1006 }
1007 Ok(())
1008 }
1009
1010 fn end(self) -> Result<Value, crate::ser::Error> {
1011 Ok(Value::Table(self.map))
1012 }
1013}
1014
1015impl ser::SerializeStruct for SerializeMap {
1016 type Ok = Value;
1017 type Error = crate::ser::Error;
1018
1019 fn serialize_field<T: ?Sized>(
1020 &mut self,
1021 key: &'static str,
1022 value: &T,
1023 ) -> Result<(), crate::ser::Error>
1024 where
1025 T: ser::Serialize,
1026 {
1027 ser::SerializeMap::serialize_key(self, key)?;
1028 ser::SerializeMap::serialize_value(self, value)
1029 }
1030
1031 fn end(self) -> Result<Value, crate::ser::Error> {
1032 ser::SerializeMap::end(self)
1033 }
1034}
1035
1036struct DatetimeOrTable<'a> {
1037 key: &'a mut String,
1038}
1039
1040impl<'a, 'de> de::DeserializeSeed<'de> for DatetimeOrTable<'a> {
1041 type Value = bool;
1042
1043 fn deserialize<D>(self, deserializer: D) -> Result<Self::Value, D::Error>
1044 where
1045 D: de::Deserializer<'de>,
1046 {
1047 deserializer.deserialize_any(self)
1048 }
1049}
1050
1051impl<'a, 'de> de::Visitor<'de> for DatetimeOrTable<'a> {
1052 type Value = bool;
1053
1054 fn expecting(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
1055 formatter.write_str("a string key")
1056 }
1057
1058 fn visit_str<E>(self, s: &str) -> Result<bool, E>
1059 where
1060 E: de::Error,
1061 {
1062 if s == datetime::FIELD {
1063 Ok(true)
1064 } else {
1065 self.key.push_str(s);
1066 Ok(false)
1067 }
1068 }
1069
1070 fn visit_string<E>(self, s: String) -> Result<bool, E>
1071 where
1072 E: de::Error,
1073 {
1074 if s == datetime::FIELD {
1075 Ok(true)
1076 } else {
1077 *self.key = s;
1078 Ok(false)
1079 }
1080 }
1081}
1082