1use 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::{Datetime, DatetimeParseError};
17
18pub use crate::map::Map;
19
20#[derive(PartialEq, Clone, Debug)]
22pub enum Value {
23 String(String),
25 Integer(i64),
27 Float(f64),
29 Boolean(bool),
31 Datetime(Datetime),
33 Array(Array),
35 Table(Table),
37}
38
39pub type Array = Vec<Value>;
41
42pub type Table = Map<String, Value>;
46
47impl Value {
48 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 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 pub fn get<I: Index>(&self, index: I) -> Option<&Value> {
85 index.index(self)
86 }
87
88 pub fn get_mut<I: Index>(&mut self, index: I) -> Option<&mut Value> {
97 index.index_mut(self)
98 }
99
100 pub fn as_integer(&self) -> Option<i64> {
102 match *self {
103 Value::Integer(i) => Some(i),
104 _ => None,
105 }
106 }
107
108 pub fn is_integer(&self) -> bool {
110 self.as_integer().is_some()
111 }
112
113 pub fn as_float(&self) -> Option<f64> {
115 match *self {
116 Value::Float(f) => Some(f),
117 _ => None,
118 }
119 }
120
121 pub fn is_float(&self) -> bool {
123 self.as_float().is_some()
124 }
125
126 pub fn as_bool(&self) -> Option<bool> {
128 match *self {
129 Value::Boolean(b) => Some(b),
130 _ => None,
131 }
132 }
133
134 pub fn is_bool(&self) -> bool {
136 self.as_bool().is_some()
137 }
138
139 pub fn as_str(&self) -> Option<&str> {
141 match *self {
142 Value::String(ref s) => Some(&**s),
143 _ => None,
144 }
145 }
146
147 pub fn is_str(&self) -> bool {
149 self.as_str().is_some()
150 }
151
152 pub fn as_datetime(&self) -> Option<&Datetime> {
161 match *self {
162 Value::Datetime(ref s) => Some(s),
163 _ => None,
164 }
165 }
166
167 pub fn is_datetime(&self) -> bool {
169 self.as_datetime().is_some()
170 }
171
172 pub fn as_array(&self) -> Option<&Vec<Value>> {
174 match *self {
175 Value::Array(ref s) => Some(s),
176 _ => None,
177 }
178 }
179
180 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 pub fn is_array(&self) -> bool {
190 self.as_array().is_some()
191 }
192
193 pub fn as_table(&self) -> Option<&Table> {
195 match *self {
196 Value::Table(ref s) => Some(s),
197 _ => None,
198 }
199 }
200
201 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 pub fn is_table(&self) -> bool {
211 self.as_table().is_some()
212 }
213
214 pub fn same_type(&self, other: &Value) -> bool {
216 discriminant(self) == discriminant(other)
217 }
218
219 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("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("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.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 = val.into_iter().map(|(s, 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 = val.into_iter().map(|(s, 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
305pub 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#[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) => 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) => 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) => 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) => 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 crate::ser::to_string(self)
386 .expect("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 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()? {
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
544impl<'de> de::Deserializer<'de> for Value {
545 type Error = crate::de::Error;
546
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]
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 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
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
628struct SeqDeserializer {
629 iter: vec::IntoIter<Value>,
630}
631
632impl SeqDeserializer {
633 fn new(vec: Vec<Value>) -> Self {
634 SeqDeserializer {
635 iter: vec.into_iter(),
636 }
637 }
638}
639
640impl<'de> de::SeqAccess<'de> for SeqDeserializer {
641 type Error = crate::de::Error;
642
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
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
661struct MapDeserializer {
662 iter: <Map<String, Value> as IntoIterator>::IntoIter,
663 value: Option<(String, Value)>,
664}
665
666impl MapDeserializer {
667 fn new(map: Map<String, Value>) -> Self {
668 MapDeserializer {
669 iter: map.into_iter(),
670 value: None,
671 }
672 }
673}
674
675impl<'de> de::MapAccess<'de> for MapDeserializer {
676 type Error = crate::de::Error;
677
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
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
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
713impl<'de> de::IntoDeserializer<'de, crate::de::Error> for Value {
714 type Deserializer = Self;
715
716 fn into_deserializer(self) -> Self {
717 self
718 }
719}
720
721struct Serializer;
722
723impl 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
735 fn serialize_bool(self, value: bool) -> Result<Value, crate::ser::Error> {
736 Ok(Value::Boolean(value))
737 }
738
739 fn serialize_i8(self, value: i8) -> Result<Value, crate::ser::Error> {
740 self.serialize_i64(value.into())
741 }
742
743 fn serialize_i16(self, value: i16) -> Result<Value, crate::ser::Error> {
744 self.serialize_i64(value.into())
745 }
746
747 fn serialize_i32(self, value: i32) -> Result<Value, crate::ser::Error> {
748 self.serialize_i64(value.into())
749 }
750
751 fn serialize_i64(self, value: i64) -> Result<Value, crate::ser::Error> {
752 Ok(Value::Integer(value))
753 }
754
755 fn serialize_u8(self, value: u8) -> Result<Value, crate::ser::Error> {
756 self.serialize_i64(value.into())
757 }
758
759 fn serialize_u16(self, value: u16) -> Result<Value, crate::ser::Error> {
760 self.serialize_i64(value.into())
761 }
762
763 fn serialize_u32(self, value: u32) -> Result<Value, crate::ser::Error> {
764 self.serialize_i64(value.into())
765 }
766
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
775 fn serialize_f32(self, value: f32) -> Result<Value, crate::ser::Error> {
776 self.serialize_f64(value.into())
777 }
778
779 fn serialize_f64(self, value: f64) -> Result<Value, crate::ser::Error> {
780 Ok(Value::Float(value))
781 }
782
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
789 fn serialize_str(self, value: &str) -> Result<Value, crate::ser::Error> {
790 Ok(Value::String(value.to_owned()))
791 }
792
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
798 fn serialize_unit(self) -> Result<Value, crate::ser::Error> {
799 Err(crate::ser::Error::UnsupportedType)
800 }
801
802 fn serialize_unit_struct(self, _name: &'static str) -> Result<Value, crate::ser::Error> {
803 Err(crate::ser::Error::UnsupportedType)
804 }
805
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
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
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
839 fn serialize_none(self) -> Result<Value, crate::ser::Error> {
840 Err(crate::ser::Error::UnsupportedNone)
841 }
842
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
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
856 fn serialize_tuple(self, len: usize) -> Result<Self::SerializeTuple, crate::ser::Error> {
857 self.serialize_seq(Some(len))
858 }
859
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
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
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
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
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
904struct SerializeVec {
905 vec: Vec<Value>,
906}
907
908struct SerializeMap {
909 map: Map<String, Value>,
910 next_key: Option<String>,
911}
912
913impl ser::SerializeSeq for SerializeVec {
914 type Ok = Value;
915 type Error = crate::ser::Error;
916
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
925 fn end(self) -> Result<Value, crate::ser::Error> {
926 Ok(Value::Array(self.vec))
927 }
928}
929
930impl ser::SerializeTuple for SerializeVec {
931 type Ok = Value;
932 type Error = crate::ser::Error;
933
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
941 fn end(self) -> Result<Value, crate::ser::Error> {
942 ser::SerializeSeq::end(self)
943 }
944}
945
946impl ser::SerializeTupleStruct for SerializeVec {
947 type Ok = Value;
948 type Error = crate::ser::Error;
949
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
957 fn end(self) -> Result<Value, crate::ser::Error> {
958 ser::SerializeSeq::end(self)
959 }
960}
961
962impl ser::SerializeTupleVariant for SerializeVec {
963 type Ok = Value;
964 type Error = crate::ser::Error;
965
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
973 fn end(self) -> Result<Value, crate::ser::Error> {
974 ser::SerializeSeq::end(self)
975 }
976}
977
978impl ser::SerializeMap for SerializeMap {
979 type Ok = Value;
980 type Error = crate::ser::Error;
981
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
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
1009 fn end(self) -> Result<Value, crate::ser::Error> {
1010 Ok(Value::Table(self.map))
1011 }
1012}
1013
1014impl ser::SerializeStruct for SerializeMap {
1015 type Ok = Value;
1016 type Error = crate::ser::Error;
1017
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
1030 fn end(self) -> Result<Value, crate::ser::Error> {
1031 ser::SerializeMap::end(self)
1032 }
1033}
1034
1035struct DatetimeOrTable<'a> {
1036 key: &'a mut String,
1037}
1038
1039impl<'a, 'de> de::DeserializeSeed<'de> for DatetimeOrTable<'a> {
1040 type Value = bool;
1041
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
1050impl<'a, 'de> de::Visitor<'de> for DatetimeOrTable<'a> {
1051 type Value = bool;
1052
1053 fn expecting(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
1054 formatter.write_str("a string key")
1055 }
1056
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
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}