1 //! Serializing Rust structures into TOML.
3 //! This module contains all the Serde support for serializing Rust structures
4 //! into TOML documents (as strings). Note that some top-level functions here
5 //! are also provided at the top of the crate.
7 //! Note that the TOML format has a restriction that if a table itself contains
8 //! tables, all keys with non-table values must be emitted first. This is
9 //! typically easy to ensure happens when you're defining a `struct` as you can
10 //! reorder the fields manually, but when working with maps (such as `BTreeMap`
11 //! or `HashMap`) this can lead to serialization errors. In those situations you
12 //! may use the `tables_last` function in this module like so:
15 //! # use serde_derive::Serialize;
16 //! # use std::collections::HashMap;
17 //! #[derive(Serialize)]
20 //! #[serde(serialize_with = "toml::ser::tables_last")]
21 //! dependencies: HashMap<String, Dependency>,
23 //! # type Package = String;
24 //! # type Dependency = String;
30 use std
::fmt
::{self, Write}
;
37 /// Serialize the given data structure as a TOML byte vector.
39 /// Serialization can fail if `T`'s implementation of `Serialize` decides to
40 /// fail, if `T` contains a map with non-string keys, or if `T` attempts to
41 /// serialize an unsupported datatype such as an enum, tuple, or tuple struct.
42 pub fn to_vec
<T
: ?Sized
>(value
: &T
) -> Result
<Vec
<u8>, Error
>
46 to_string(value
).map(|e
| e
.into_bytes())
49 /// Serialize the given data structure as a String of TOML.
51 /// Serialization can fail if `T`'s implementation of `Serialize` decides to
52 /// fail, if `T` contains a map with non-string keys, or if `T` attempts to
53 /// serialize an unsupported datatype such as an enum, tuple, or tuple struct.
58 /// use serde_derive::Serialize;
60 /// #[derive(Serialize)]
62 /// database: Database,
65 /// #[derive(Serialize)]
69 /// connection_max: u32,
74 /// let config = Config {
75 /// database: Database {
76 /// ip: "192.168.1.1".to_string(),
77 /// port: vec![8001, 8002, 8003],
78 /// connection_max: 5000,
83 /// let toml = toml::to_string(&config).unwrap();
84 /// println!("{}", toml)
87 pub fn to_string
<T
: ?Sized
>(value
: &T
) -> Result
<String
, Error
>
91 let mut dst
= String
::with_capacity(128);
92 value
.serialize(&mut Serializer
::new(&mut dst
))?
;
96 /// Serialize the given data structure as a "pretty" String of TOML.
98 /// This is identical to `to_string` except the output string has a more
99 /// "pretty" output. See `Serializer::pretty` for more details.
100 pub fn to_string_pretty
<T
: ?Sized
>(value
: &T
) -> Result
<String
, Error
>
104 let mut dst
= String
::with_capacity(128);
105 value
.serialize(&mut Serializer
::pretty(&mut dst
))?
;
109 /// Errors that can occur when serializing a type.
110 #[derive(Debug, PartialEq, Eq, Clone)]
112 /// Indicates that a Rust type was requested to be serialized but it was not
115 /// Currently the TOML format does not support serializing types such as
116 /// enums, tuples and tuple structs.
119 /// The key of all TOML maps must be strings, but serialization was
120 /// attempted where the key of a map was not a string.
123 /// An error that we never omit but keep for backwards compatibility
127 /// An array had to be homogenous, but now it is allowed to be heterogenous.
131 /// All values in a TOML table must be emitted before further tables are
132 /// emitted. If a value is emitted *after* a table then this error is
136 /// A serialized date was invalid.
139 /// A serialized number was invalid.
142 /// None was attempted to be serialized, but it's not supported.
145 /// A custom error which could be generated when serializing a particular
153 #[derive(Debug, Default, Clone)]
154 /// Internal place for holding array setings
155 struct ArraySettings
{
157 trailing_comma
: bool
,
161 fn pretty() -> ArraySettings
{
164 trailing_comma
: true,
169 #[derive(Debug, Default, Clone)]
171 struct StringSettings
{
172 /// Whether to use literal strings when possible
176 impl StringSettings
{
177 fn pretty() -> StringSettings
{
178 StringSettings { literal: true }
182 #[derive(Debug, Default, Clone)]
183 /// Internal struct for holding serialization settings
185 array
: Option
<ArraySettings
>,
186 string
: Option
<StringSettings
>,
189 /// Serialization implementation for TOML.
191 /// This structure implements serialization support for TOML to serialize an
192 /// arbitrary type to TOML. Note that the TOML format does not support all
193 /// datatypes in Rust, such as enums, tuples, and tuple structs. These types
194 /// will generate an error when serialized.
196 /// Currently a serializer always writes its output to an in-memory `String`,
197 /// which is passed in when creating the serializer itself.
198 pub struct Serializer
<'a
> {
201 settings
: Rc
<Settings
>,
204 #[derive(Debug, Copy, Clone)]
210 #[derive(Debug, Clone)]
214 parent
: &'a State
<'a
>,
215 first
: &'a Cell
<bool
>,
216 table_emitted
: &'a Cell
<bool
>,
219 parent
: &'a State
<'a
>,
220 first
: &'a Cell
<bool
>,
221 type_
: &'a Cell
<Option
<ArrayState
>>,
228 pub struct SerializeSeq
<'a
, 'b
> {
229 ser
: &'b
mut Serializer
<'a
>,
231 type_
: Cell
<Option
<ArrayState
>>,
236 pub enum SerializeTable
<'a
, 'b
> {
237 Datetime(&'b
mut Serializer
<'a
>),
239 ser
: &'b
mut Serializer
<'a
>,
242 table_emitted
: Cell
<bool
>,
246 impl<'a
> Serializer
<'a
> {
247 /// Creates a new serializer which will emit TOML into the buffer provided.
249 /// The serializer can then be used to serialize a type after which the data
250 /// will be present in `dst`.
251 pub fn new(dst
: &'a
mut String
) -> Serializer
<'a
> {
255 settings
: Rc
::new(Settings
::default()),
259 /// Instantiate a "pretty" formatter
261 /// By default this will use:
263 /// - pretty strings: strings with newlines will use the `'''` syntax. See
264 /// `Serializer::pretty_string`
265 /// - pretty arrays: each item in arrays will be on a newline, have an indentation of 4 and
266 /// have a trailing comma. See `Serializer::pretty_array`
267 pub fn pretty(dst
: &'a
mut String
) -> Serializer
<'a
> {
271 settings
: Rc
::new(Settings
{
272 array
: Some(ArraySettings
::pretty()),
273 string
: Some(StringSettings
::pretty()),
278 /// Enable or Disable pretty strings
280 /// If enabled, literal strings will be used when possible and strings with
281 /// one or more newlines will use triple quotes (i.e.: `'''` or `"""`)
288 /// single = "no newlines"
289 /// text = "\nfoo\nbar\n"
295 /// single = 'no newlines'
301 pub fn pretty_string(&mut self, value
: bool
) -> &mut Self {
302 Rc
::get_mut(&mut self.settings
).unwrap().string
= if value
{
303 Some(StringSettings
::pretty())
310 /// Enable or Disable Literal strings for pretty strings
312 /// If enabled, literal strings will be used when possible and strings with
313 /// one or more newlines will use triple quotes (i.e.: `'''` or `"""`)
315 /// If disabled, literal strings will NEVER be used and strings with one or
316 /// more newlines will use `"""`
323 /// single = "no newlines"
324 /// text = "\nfoo\nbar\n"
330 /// single = "no newlines"
336 pub fn pretty_string_literal(&mut self, value
: bool
) -> &mut Self {
337 let use_default
= if let Some(ref mut s
) = Rc
::get_mut(&mut self.settings
).unwrap().string
{
345 let mut string
= StringSettings
::pretty();
346 string
.literal
= value
;
347 Rc
::get_mut(&mut self.settings
).unwrap().string
= Some(string
);
352 /// Enable or Disable pretty arrays
354 /// If enabled, arrays will always have each item on their own line.
356 /// Some specific features can be controlled via other builder methods:
358 /// - `Serializer::pretty_array_indent`: set the indent to a value other
360 /// - `Serializer::pretty_array_trailing_comma`: enable/disable the trailing
361 /// comma on the last item.
368 /// array = ["foo", "bar"]
379 pub fn pretty_array(&mut self, value
: bool
) -> &mut Self {
380 Rc
::get_mut(&mut self.settings
).unwrap().array
= if value
{
381 Some(ArraySettings
::pretty())
388 /// Set the indent for pretty arrays
390 /// See `Serializer::pretty_array` for more details.
391 pub fn pretty_array_indent(&mut self, value
: usize) -> &mut Self {
392 let use_default
= if let Some(ref mut a
) = Rc
::get_mut(&mut self.settings
).unwrap().array
{
400 let mut array
= ArraySettings
::pretty();
401 array
.indent
= value
;
402 Rc
::get_mut(&mut self.settings
).unwrap().array
= Some(array
);
407 /// Specify whether to use a trailing comma when serializing pretty arrays
409 /// See `Serializer::pretty_array` for more details.
410 pub fn pretty_array_trailing_comma(&mut self, value
: bool
) -> &mut Self {
411 let use_default
= if let Some(ref mut a
) = Rc
::get_mut(&mut self.settings
).unwrap().array
{
412 a
.trailing_comma
= value
;
419 let mut array
= ArraySettings
::pretty();
420 array
.trailing_comma
= value
;
421 Rc
::get_mut(&mut self.settings
).unwrap().array
= Some(array
);
426 fn display
<T
: fmt
::Display
>(&mut self, t
: T
, type_
: ArrayState
) -> Result
<(), Error
> {
427 self.emit_key(type_
)?
;
428 write
!(self.dst
, "{}", t
).map_err(ser
::Error
::custom
)?
;
429 if let State
::Table { .. }
= self.state
{
430 self.dst
.push_str("\n");
435 fn emit_key(&mut self, type_
: ArrayState
) -> Result
<(), Error
> {
436 self.array_type(type_
)?
;
437 let state
= self.state
.clone();
438 self._emit_key(&state
)
441 // recursive implementation of `emit_key` above
442 fn _emit_key(&mut self, state
: &State
<'_
>) -> Result
<(), Error
> {
444 State
::End
=> Ok(()),
451 assert
!(type_
.get().is_some());
453 self._emit_key(parent
)?
;
455 self.emit_array(first
, len
)
463 if table_emitted
.get() {
464 return Err(Error
::ValueAfterTable
);
467 self.emit_table_header(parent
)?
;
470 self.escape_key(key
)?
;
471 self.dst
.push_str(" = ");
477 fn emit_array(&mut self, first
: &Cell
<bool
>, len
: Option
<usize>) -> Result
<(), Error
> {
478 match (len
, &self.settings
.array
) {
479 (Some(0..=1), _
) | (_
, &None
) => {
481 self.dst
.push_str("[")
483 self.dst
.push_str(", ")
486 (_
, &Some(ref a
)) => {
488 self.dst
.push_str("[\n")
490 self.dst
.push_str(",\n")
492 for _
in 0..a
.indent
{
493 self.dst
.push_str(" ");
500 fn array_type(&mut self, type_
: ArrayState
) -> Result
<(), Error
> {
501 let prev
= match self.state
{
502 State
::Array { type_, .. }
=> type_
,
505 if prev
.get().is_none() {
506 prev
.set(Some(type_
));
511 fn escape_key(&mut self, key
: &str) -> Result
<(), Error
> {
512 let ok
= key
.len() > 0
513 && key
.chars().all(|c
| match c
{
514 'a'
..='z'
| 'A'
..='Z'
| '
0'
..='
9'
| '
-'
| '_'
=> true,
518 write
!(self.dst
, "{}", key
).map_err(ser
::Error
::custom
)?
;
520 self.emit_str(key
, true)?
;
525 fn emit_str(&mut self, value
: &str, is_key
: bool
) -> Result
<(), Error
> {
534 /// represent as a literal string (using '')
535 Literal(String
, Type
),
536 /// represent the std way (using "")
540 fn do_pretty(value
: &str) -> Repr
{
541 // For doing pretty prints we store in a new String
542 // because there are too many cases where pretty cannot
543 // work. We need to determine:
544 // - if we are a "multi-line" pretty (if there are \n)
545 // - if ['''] appears if multi or ['] if single
546 // - if there are any invalid control characters
548 // Doing it any other way would require multiple passes
549 // to determine if a pretty string works or not.
550 let mut out
= String
::with_capacity(value
.len() * 2);
551 let mut ty
= Type
::OnelineSingle
;
552 // found consecutive single quotes
553 let mut max_found_singles
= 0;
554 let mut found_singles
= 0;
555 let mut can_be_pretty
= true;
557 for ch
in value
.chars() {
561 if found_singles
>= 3 {
562 can_be_pretty
= false;
565 if found_singles
> max_found_singles
{
566 max_found_singles
= found_singles
;
572 '
\n'
=> ty
= Type
::NewlineTripple
,
573 // Escape codes are needed if any ascii control
574 // characters are present, including \b \f \r.
575 c
if c
<= '
\u{1f}'
|| c
== '
\u{7f}'
=> can_be_pretty
= false,
580 // the string cannot be represented as pretty,
581 // still check if it should be multiline
583 ty
= Type
::NewlineTripple
;
587 if can_be_pretty
&& found_singles
> 0 && value
.ends_with('
\''
) {
588 // We cannot escape the ending quote so we must use """
589 can_be_pretty
= false;
592 debug_assert
!(ty
!= Type
::OnelineTripple
);
593 return Repr
::Std(ty
);
595 if found_singles
> max_found_singles
{
596 max_found_singles
= found_singles
;
598 debug_assert
!(max_found_singles
< 3);
599 if ty
== Type
::OnelineSingle
&& max_found_singles
>= 1 {
600 // no newlines, but must use ''' because it has ' in it
601 ty
= Type
::OnelineTripple
;
603 Repr
::Literal(out
, ty
)
606 let repr
= if !is_key
&& self.settings
.string
.is_some() {
607 match (&self.settings
.string
, do_pretty(value
)) {
608 (&Some(StringSettings { literal: false, .. }
), Repr
::Literal(_
, ty
)) => {
614 Repr
::Std(Type
::OnelineSingle
)
617 Repr
::Literal(literal
, ty
) => {
620 Type
::NewlineTripple
=> self.dst
.push_str("'''\n"),
621 Type
::OnelineTripple
=> self.dst
.push_str("'''"),
622 Type
::OnelineSingle
=> self.dst
.push('
\''
),
624 self.dst
.push_str(&literal
);
626 Type
::OnelineSingle
=> self.dst
.push('
\''
),
627 _
=> self.dst
.push_str("'''"),
632 Type
::NewlineTripple
=> self.dst
.push_str("\"\"\"\n"),
633 // note: OnelineTripple can happen if do_pretty wants to do
634 // '''it's one line'''
635 // but settings.string.literal == false
636 Type
::OnelineSingle
| Type
::OnelineTripple
=> self.dst
.push('
"'),
638 for ch in value.chars() {
640 '\u{8}' => self.dst.push_str("\\b
"),
641 '\u{9}' => self.dst.push_str("\\t
"),
642 '\u{a}' => match ty {
643 Type::NewlineTripple => self.dst.push('\n'),
644 Type::OnelineSingle => self.dst.push_str("\\n
"),
647 '\u{c}' => self.dst.push_str("\\f
"),
648 '\u{d}' => self.dst.push_str("\\r
"),
649 '\u{22}' => self.dst.push_str("\\\""),
650 '\u{5c}' => self.dst.push_str("\\\\"),
651 c if c <= '\u{1f}' || c == '\u{7f}' => {
652 write!(self.dst, "\\u{:04X}
", ch as u32).map_err(ser::Error::custom)?;
654 ch => self.dst.push(ch),
658 Type::NewlineTripple => self.dst.push_str("\"\"\""),
659 Type::OnelineSingle | Type::OnelineTripple => self.dst.push('"'
),
666 fn emit_table_header(&mut self, state
: &State
<'_
>) -> Result
<(), Error
> {
667 let array_of_tables
= match *state
{
668 State
::End
=> return Ok(()),
669 State
::Array { .. }
=> true,
673 // Unlike [..]s, we can't omit [[..]] ancestors, so be sure to emit table
676 if let State
::Array { first, parent, .. }
= *state
{
681 while let State
::Table { first, parent, .. }
= *p
{
686 if let State
::Array
{
687 parent
: &State
::Table { .. }
,
691 self.emit_table_header(parent
)?
;
697 State
::Table { first, .. }
=> {
699 // Newline if we are a table that is not the first
700 // table in the document.
704 State
::Array { parent, first, .. }
=> {
706 // Always newline if we are not the first item in the
709 } else if let State
::Table { first, .. }
= *parent
{
711 // Newline if we are not the first item in the document
718 self.dst
.push_str("[");
720 self.dst
.push_str("[");
722 self.emit_key_part(state
)?
;
724 self.dst
.push_str("]");
726 self.dst
.push_str("]\n");
730 fn emit_key_part(&mut self, key
: &State
<'_
>) -> Result
<bool
, Error
> {
732 State
::Array { parent, .. }
=> self.emit_key_part(parent
),
733 State
::End
=> Ok(true),
740 table_emitted
.set(true);
741 let first
= self.emit_key_part(parent
)?
;
743 self.dst
.push_str(".");
745 self.escape_key(key
)?
;
752 macro_rules
! serialize_float
{
753 ($this
:expr
, $v
:expr
) => {{
754 $this
.emit_key(ArrayState
::Started
)?
;
755 match ($v
.is_sign_negative(), $v
.is_nan(), $v
== 0.0) {
756 (true, true, _
) => write
!($this
.dst
, "-nan"),
757 (false, true, _
) => write
!($this
.dst
, "nan"),
758 (true, false, true) => write
!($this
.dst
, "-0.0"),
759 (false, false, true) => write
!($this
.dst
, "0.0"),
760 (_
, false, false) => write
!($this
.dst
, "{}", $v
).and_then(|_
| {
762 write
!($this
.dst
, ".0")
768 .map_err(ser
::Error
::custom
)?
;
770 if let State
::Table { .. }
= $this
.state
{
771 $this
.dst
.push_str("\n");
777 impl<'a
, 'b
> ser
::Serializer
for &'b
mut Serializer
<'a
> {
780 type SerializeSeq
= SerializeSeq
<'a
, 'b
>;
781 type SerializeTuple
= SerializeSeq
<'a
, 'b
>;
782 type SerializeTupleStruct
= SerializeSeq
<'a
, 'b
>;
783 type SerializeTupleVariant
= SerializeSeq
<'a
, 'b
>;
784 type SerializeMap
= SerializeTable
<'a
, 'b
>;
785 type SerializeStruct
= SerializeTable
<'a
, 'b
>;
786 type SerializeStructVariant
= ser
::Impossible
<(), Error
>;
788 fn serialize_bool(self, v
: bool
) -> Result
<(), Self::Error
> {
789 self.display(v
, ArrayState
::Started
)
792 fn serialize_i8(self, v
: i8) -> Result
<(), Self::Error
> {
793 self.display(v
, ArrayState
::Started
)
796 fn serialize_i16(self, v
: i16) -> Result
<(), Self::Error
> {
797 self.display(v
, ArrayState
::Started
)
800 fn serialize_i32(self, v
: i32) -> Result
<(), Self::Error
> {
801 self.display(v
, ArrayState
::Started
)
804 fn serialize_i64(self, v
: i64) -> Result
<(), Self::Error
> {
805 self.display(v
, ArrayState
::Started
)
808 fn serialize_u8(self, v
: u8) -> Result
<(), Self::Error
> {
809 self.display(v
, ArrayState
::Started
)
812 fn serialize_u16(self, v
: u16) -> Result
<(), Self::Error
> {
813 self.display(v
, ArrayState
::Started
)
816 fn serialize_u32(self, v
: u32) -> Result
<(), Self::Error
> {
817 self.display(v
, ArrayState
::Started
)
820 fn serialize_u64(self, v
: u64) -> Result
<(), Self::Error
> {
821 self.display(v
, ArrayState
::Started
)
824 fn serialize_f32(self, v
: f32) -> Result
<(), Self::Error
> {
825 serialize_float
!(self, v
)
828 fn serialize_f64(self, v
: f64) -> Result
<(), Self::Error
> {
829 serialize_float
!(self, v
)
832 fn serialize_char(self, v
: char) -> Result
<(), Self::Error
> {
833 let mut buf
= [0; 4];
834 self.serialize_str(v
.encode_utf8(&mut buf
))
837 fn serialize_str(self, value
: &str) -> Result
<(), Self::Error
> {
838 self.emit_key(ArrayState
::Started
)?
;
839 self.emit_str(value
, false)?
;
840 if let State
::Table { .. }
= self.state
{
841 self.dst
.push_str("\n");
846 fn serialize_bytes(self, value
: &[u8]) -> Result
<(), Self::Error
> {
847 use serde
::ser
::Serialize
;
848 value
.serialize(self)
851 fn serialize_none(self) -> Result
<(), Self::Error
> {
852 Err(Error
::UnsupportedNone
)
855 fn serialize_some
<T
: ?Sized
>(self, value
: &T
) -> Result
<(), Self::Error
>
859 value
.serialize(self)
862 fn serialize_unit(self) -> Result
<(), Self::Error
> {
863 Err(Error
::UnsupportedType
)
866 fn serialize_unit_struct(self, _name
: &'
static str) -> Result
<(), Self::Error
> {
867 Err(Error
::UnsupportedType
)
870 fn serialize_unit_variant(
874 variant
: &'
static str,
875 ) -> Result
<(), Self::Error
> {
876 self.serialize_str(variant
)
879 fn serialize_newtype_struct
<T
: ?Sized
>(
883 ) -> Result
<(), Self::Error
>
887 value
.serialize(self)
890 fn serialize_newtype_variant
<T
: ?Sized
>(
894 _variant
: &'
static str,
896 ) -> Result
<(), Self::Error
>
900 Err(Error
::UnsupportedType
)
903 fn serialize_seq(self, len
: Option
<usize>) -> Result
<Self::SerializeSeq
, Self::Error
> {
904 self.array_type(ArrayState
::Started
)?
;
907 first
: Cell
::new(true),
908 type_
: Cell
::new(None
),
913 fn serialize_tuple(self, len
: usize) -> Result
<Self::SerializeTuple
, Self::Error
> {
914 self.serialize_seq(Some(len
))
917 fn serialize_tuple_struct(
921 ) -> Result
<Self::SerializeTupleStruct
, Self::Error
> {
922 self.serialize_seq(Some(len
))
925 fn serialize_tuple_variant(
929 _variant
: &'
static str,
931 ) -> Result
<Self::SerializeTupleVariant
, Self::Error
> {
932 self.serialize_seq(Some(len
))
935 fn serialize_map(self, _len
: Option
<usize>) -> Result
<Self::SerializeMap
, Self::Error
> {
936 self.array_type(ArrayState
::StartedAsATable
)?
;
937 Ok(SerializeTable
::Table
{
940 first
: Cell
::new(true),
941 table_emitted
: Cell
::new(false),
949 ) -> Result
<Self::SerializeStruct
, Self::Error
> {
950 if name
== datetime
::NAME
{
951 self.array_type(ArrayState
::Started
)?
;
952 Ok(SerializeTable
::Datetime(self))
954 self.array_type(ArrayState
::StartedAsATable
)?
;
955 Ok(SerializeTable
::Table
{
958 first
: Cell
::new(true),
959 table_emitted
: Cell
::new(false),
964 fn serialize_struct_variant(
968 _variant
: &'
static str,
970 ) -> Result
<Self::SerializeStructVariant
, Self::Error
> {
971 Err(Error
::UnsupportedType
)
975 impl<'a
, 'b
> ser
::SerializeSeq
for SerializeSeq
<'a
, 'b
> {
979 fn serialize_element
<T
: ?Sized
>(&mut self, value
: &T
) -> Result
<(), Error
>
983 value
.serialize(&mut Serializer
{
984 dst
: &mut *self.ser
.dst
,
985 state
: State
::Array
{
986 parent
: &self.ser
.state
,
991 settings
: self.ser
.settings
.clone(),
993 self.first
.set(false);
997 fn end(self) -> Result
<(), Error
> {
998 match self.type_
.get() {
999 Some(ArrayState
::StartedAsATable
) => return Ok(()),
1000 Some(ArrayState
::Started
) => match (self.len
, &self.ser
.settings
.array
) {
1001 (Some(0..=1), _
) | (_
, &None
) => {
1002 self.ser
.dst
.push_str("]");
1004 (_
, &Some(ref a
)) => {
1005 if a
.trailing_comma
{
1006 self.ser
.dst
.push_str(",");
1008 self.ser
.dst
.push_str("\n]");
1012 assert
!(self.first
.get());
1013 self.ser
.emit_key(ArrayState
::Started
)?
;
1014 self.ser
.dst
.push_str("[]")
1017 if let State
::Table { .. }
= self.ser
.state
{
1018 self.ser
.dst
.push_str("\n");
1024 impl<'a
, 'b
> ser
::SerializeTuple
for SerializeSeq
<'a
, 'b
> {
1028 fn serialize_element
<T
: ?Sized
>(&mut self, value
: &T
) -> Result
<(), Error
>
1032 ser
::SerializeSeq
::serialize_element(self, value
)
1035 fn end(self) -> Result
<(), Error
> {
1036 ser
::SerializeSeq
::end(self)
1040 impl<'a
, 'b
> ser
::SerializeTupleVariant
for SerializeSeq
<'a
, 'b
> {
1044 fn serialize_field
<T
: ?Sized
>(&mut self, value
: &T
) -> Result
<(), Error
>
1048 ser
::SerializeSeq
::serialize_element(self, value
)
1051 fn end(self) -> Result
<(), Error
> {
1052 ser
::SerializeSeq
::end(self)
1056 impl<'a
, 'b
> ser
::SerializeTupleStruct
for SerializeSeq
<'a
, 'b
> {
1060 fn serialize_field
<T
: ?Sized
>(&mut self, value
: &T
) -> Result
<(), Error
>
1064 ser
::SerializeSeq
::serialize_element(self, value
)
1067 fn end(self) -> Result
<(), Error
> {
1068 ser
::SerializeSeq
::end(self)
1072 impl<'a
, 'b
> ser
::SerializeMap
for SerializeTable
<'a
, 'b
> {
1076 fn serialize_key
<T
: ?Sized
>(&mut self, input
: &T
) -> Result
<(), Error
>
1081 SerializeTable
::Datetime(_
) => panic
!(), // shouldn't be possible
1082 SerializeTable
::Table { ref mut key, .. }
=> {
1084 *key
= input
.serialize(StringExtractor
)?
;
1090 fn serialize_value
<T
: ?Sized
>(&mut self, value
: &T
) -> Result
<(), Error
>
1095 SerializeTable
::Datetime(_
) => panic
!(), // shouldn't be possible
1096 SerializeTable
::Table
{
1103 let res
= value
.serialize(&mut Serializer
{
1105 state
: State
::Table
{
1111 settings
: ser
.settings
.clone(),
1114 Ok(()) => first
.set(false),
1115 Err(Error
::UnsupportedNone
) => {}
1116 Err(e
) => return Err(e
),
1123 fn end(self) -> Result
<(), Error
> {
1125 SerializeTable
::Datetime(_
) => panic
!(), // shouldn't be possible
1126 SerializeTable
::Table { ser, first, .. }
=> {
1128 let state
= ser
.state
.clone();
1129 ser
.emit_table_header(&state
)?
;
1137 impl<'a
, 'b
> ser
::SerializeStruct
for SerializeTable
<'a
, 'b
> {
1141 fn serialize_field
<T
: ?Sized
>(&mut self, key
: &'
static str, value
: &T
) -> Result
<(), Error
>
1146 SerializeTable
::Datetime(ref mut ser
) => {
1147 if key
== datetime
::FIELD
{
1148 value
.serialize(DateStrEmitter(&mut *ser
))?
;
1150 return Err(Error
::DateInvalid
);
1153 SerializeTable
::Table
{
1159 let res
= value
.serialize(&mut Serializer
{
1161 state
: State
::Table
{
1167 settings
: ser
.settings
.clone(),
1170 Ok(()) => first
.set(false),
1171 Err(Error
::UnsupportedNone
) => {}
1172 Err(e
) => return Err(e
),
1179 fn end(self) -> Result
<(), Error
> {
1181 SerializeTable
::Datetime(_
) => {}
1182 SerializeTable
::Table { ser, first, .. }
=> {
1184 let state
= ser
.state
.clone();
1185 ser
.emit_table_header(&state
)?
;
1193 struct DateStrEmitter
<'a
, 'b
>(&'b
mut Serializer
<'a
>);
1195 impl<'a
, 'b
> ser
::Serializer
for DateStrEmitter
<'a
, 'b
> {
1198 type SerializeSeq
= ser
::Impossible
<(), Error
>;
1199 type SerializeTuple
= ser
::Impossible
<(), Error
>;
1200 type SerializeTupleStruct
= ser
::Impossible
<(), Error
>;
1201 type SerializeTupleVariant
= ser
::Impossible
<(), Error
>;
1202 type SerializeMap
= ser
::Impossible
<(), Error
>;
1203 type SerializeStruct
= ser
::Impossible
<(), Error
>;
1204 type SerializeStructVariant
= ser
::Impossible
<(), Error
>;
1206 fn serialize_bool(self, _v
: bool
) -> Result
<(), Self::Error
> {
1207 Err(Error
::DateInvalid
)
1210 fn serialize_i8(self, _v
: i8) -> Result
<(), Self::Error
> {
1211 Err(Error
::DateInvalid
)
1214 fn serialize_i16(self, _v
: i16) -> Result
<(), Self::Error
> {
1215 Err(Error
::DateInvalid
)
1218 fn serialize_i32(self, _v
: i32) -> Result
<(), Self::Error
> {
1219 Err(Error
::DateInvalid
)
1222 fn serialize_i64(self, _v
: i64) -> Result
<(), Self::Error
> {
1223 Err(Error
::DateInvalid
)
1226 fn serialize_u8(self, _v
: u8) -> Result
<(), Self::Error
> {
1227 Err(Error
::DateInvalid
)
1230 fn serialize_u16(self, _v
: u16) -> Result
<(), Self::Error
> {
1231 Err(Error
::DateInvalid
)
1234 fn serialize_u32(self, _v
: u32) -> Result
<(), Self::Error
> {
1235 Err(Error
::DateInvalid
)
1238 fn serialize_u64(self, _v
: u64) -> Result
<(), Self::Error
> {
1239 Err(Error
::DateInvalid
)
1242 fn serialize_f32(self, _v
: f32) -> Result
<(), Self::Error
> {
1243 Err(Error
::DateInvalid
)
1246 fn serialize_f64(self, _v
: f64) -> Result
<(), Self::Error
> {
1247 Err(Error
::DateInvalid
)
1250 fn serialize_char(self, _v
: char) -> Result
<(), Self::Error
> {
1251 Err(Error
::DateInvalid
)
1254 fn serialize_str(self, value
: &str) -> Result
<(), Self::Error
> {
1255 self.0.display(value
, ArrayState
::Started
)?
;
1259 fn serialize_bytes(self, _value
: &[u8]) -> Result
<(), Self::Error
> {
1260 Err(Error
::DateInvalid
)
1263 fn serialize_none(self) -> Result
<(), Self::Error
> {
1264 Err(Error
::DateInvalid
)
1267 fn serialize_some
<T
: ?Sized
>(self, _value
: &T
) -> Result
<(), Self::Error
>
1271 Err(Error
::DateInvalid
)
1274 fn serialize_unit(self) -> Result
<(), Self::Error
> {
1275 Err(Error
::DateInvalid
)
1278 fn serialize_unit_struct(self, _name
: &'
static str) -> Result
<(), Self::Error
> {
1279 Err(Error
::DateInvalid
)
1282 fn serialize_unit_variant(
1284 _name
: &'
static str,
1285 _variant_index
: u32,
1286 _variant
: &'
static str,
1287 ) -> Result
<(), Self::Error
> {
1288 Err(Error
::DateInvalid
)
1291 fn serialize_newtype_struct
<T
: ?Sized
>(
1293 _name
: &'
static str,
1295 ) -> Result
<(), Self::Error
>
1299 Err(Error
::DateInvalid
)
1302 fn serialize_newtype_variant
<T
: ?Sized
>(
1304 _name
: &'
static str,
1305 _variant_index
: u32,
1306 _variant
: &'
static str,
1308 ) -> Result
<(), Self::Error
>
1312 Err(Error
::DateInvalid
)
1315 fn serialize_seq(self, _len
: Option
<usize>) -> Result
<Self::SerializeSeq
, Self::Error
> {
1316 Err(Error
::DateInvalid
)
1319 fn serialize_tuple(self, _len
: usize) -> Result
<Self::SerializeTuple
, Self::Error
> {
1320 Err(Error
::DateInvalid
)
1323 fn serialize_tuple_struct(
1325 _name
: &'
static str,
1327 ) -> Result
<Self::SerializeTupleStruct
, Self::Error
> {
1328 Err(Error
::DateInvalid
)
1331 fn serialize_tuple_variant(
1333 _name
: &'
static str,
1334 _variant_index
: u32,
1335 _variant
: &'
static str,
1337 ) -> Result
<Self::SerializeTupleVariant
, Self::Error
> {
1338 Err(Error
::DateInvalid
)
1341 fn serialize_map(self, _len
: Option
<usize>) -> Result
<Self::SerializeMap
, Self::Error
> {
1342 Err(Error
::DateInvalid
)
1345 fn serialize_struct(
1347 _name
: &'
static str,
1349 ) -> Result
<Self::SerializeStruct
, Self::Error
> {
1350 Err(Error
::DateInvalid
)
1353 fn serialize_struct_variant(
1355 _name
: &'
static str,
1356 _variant_index
: u32,
1357 _variant
: &'
static str,
1359 ) -> Result
<Self::SerializeStructVariant
, Self::Error
> {
1360 Err(Error
::DateInvalid
)
1364 struct StringExtractor
;
1366 impl ser
::Serializer
for StringExtractor
{
1369 type SerializeSeq
= ser
::Impossible
<String
, Error
>;
1370 type SerializeTuple
= ser
::Impossible
<String
, Error
>;
1371 type SerializeTupleStruct
= ser
::Impossible
<String
, Error
>;
1372 type SerializeTupleVariant
= ser
::Impossible
<String
, Error
>;
1373 type SerializeMap
= ser
::Impossible
<String
, Error
>;
1374 type SerializeStruct
= ser
::Impossible
<String
, Error
>;
1375 type SerializeStructVariant
= ser
::Impossible
<String
, Error
>;
1377 fn serialize_bool(self, _v
: bool
) -> Result
<String
, Self::Error
> {
1378 Err(Error
::KeyNotString
)
1381 fn serialize_i8(self, _v
: i8) -> Result
<String
, Self::Error
> {
1382 Err(Error
::KeyNotString
)
1385 fn serialize_i16(self, _v
: i16) -> Result
<String
, Self::Error
> {
1386 Err(Error
::KeyNotString
)
1389 fn serialize_i32(self, _v
: i32) -> Result
<String
, Self::Error
> {
1390 Err(Error
::KeyNotString
)
1393 fn serialize_i64(self, _v
: i64) -> Result
<String
, Self::Error
> {
1394 Err(Error
::KeyNotString
)
1397 fn serialize_u8(self, _v
: u8) -> Result
<String
, Self::Error
> {
1398 Err(Error
::KeyNotString
)
1401 fn serialize_u16(self, _v
: u16) -> Result
<String
, Self::Error
> {
1402 Err(Error
::KeyNotString
)
1405 fn serialize_u32(self, _v
: u32) -> Result
<String
, Self::Error
> {
1406 Err(Error
::KeyNotString
)
1409 fn serialize_u64(self, _v
: u64) -> Result
<String
, Self::Error
> {
1410 Err(Error
::KeyNotString
)
1413 fn serialize_f32(self, _v
: f32) -> Result
<String
, Self::Error
> {
1414 Err(Error
::KeyNotString
)
1417 fn serialize_f64(self, _v
: f64) -> Result
<String
, Self::Error
> {
1418 Err(Error
::KeyNotString
)
1421 fn serialize_char(self, _v
: char) -> Result
<String
, Self::Error
> {
1422 Err(Error
::KeyNotString
)
1425 fn serialize_str(self, value
: &str) -> Result
<String
, Self::Error
> {
1426 Ok(value
.to_string())
1429 fn serialize_bytes(self, _value
: &[u8]) -> Result
<String
, Self::Error
> {
1430 Err(Error
::KeyNotString
)
1433 fn serialize_none(self) -> Result
<String
, Self::Error
> {
1434 Err(Error
::KeyNotString
)
1437 fn serialize_some
<T
: ?Sized
>(self, _value
: &T
) -> Result
<String
, Self::Error
>
1441 Err(Error
::KeyNotString
)
1444 fn serialize_unit(self) -> Result
<String
, Self::Error
> {
1445 Err(Error
::KeyNotString
)
1448 fn serialize_unit_struct(self, _name
: &'
static str) -> Result
<String
, Self::Error
> {
1449 Err(Error
::KeyNotString
)
1452 fn serialize_unit_variant(
1454 _name
: &'
static str,
1455 _variant_index
: u32,
1456 _variant
: &'
static str,
1457 ) -> Result
<String
, Self::Error
> {
1458 Err(Error
::KeyNotString
)
1461 fn serialize_newtype_struct
<T
: ?Sized
>(
1463 _name
: &'
static str,
1465 ) -> Result
<String
, Self::Error
>
1469 value
.serialize(self)
1472 fn serialize_newtype_variant
<T
: ?Sized
>(
1474 _name
: &'
static str,
1475 _variant_index
: u32,
1476 _variant
: &'
static str,
1478 ) -> Result
<String
, Self::Error
>
1482 Err(Error
::KeyNotString
)
1485 fn serialize_seq(self, _len
: Option
<usize>) -> Result
<Self::SerializeSeq
, Self::Error
> {
1486 Err(Error
::KeyNotString
)
1489 fn serialize_tuple(self, _len
: usize) -> Result
<Self::SerializeTuple
, Self::Error
> {
1490 Err(Error
::KeyNotString
)
1493 fn serialize_tuple_struct(
1495 _name
: &'
static str,
1497 ) -> Result
<Self::SerializeTupleStruct
, Self::Error
> {
1498 Err(Error
::KeyNotString
)
1501 fn serialize_tuple_variant(
1503 _name
: &'
static str,
1504 _variant_index
: u32,
1505 _variant
: &'
static str,
1507 ) -> Result
<Self::SerializeTupleVariant
, Self::Error
> {
1508 Err(Error
::KeyNotString
)
1511 fn serialize_map(self, _len
: Option
<usize>) -> Result
<Self::SerializeMap
, Self::Error
> {
1512 Err(Error
::KeyNotString
)
1515 fn serialize_struct(
1517 _name
: &'
static str,
1519 ) -> Result
<Self::SerializeStruct
, Self::Error
> {
1520 Err(Error
::KeyNotString
)
1523 fn serialize_struct_variant(
1525 _name
: &'
static str,
1526 _variant_index
: u32,
1527 _variant
: &'
static str,
1529 ) -> Result
<Self::SerializeStructVariant
, Self::Error
> {
1530 Err(Error
::KeyNotString
)
1534 impl fmt
::Display
for Error
{
1535 fn fmt(&self, f
: &mut fmt
::Formatter
<'_
>) -> fmt
::Result
{
1537 Error
::UnsupportedType
=> "unsupported Rust type".fmt(f
),
1538 Error
::KeyNotString
=> "map key was not a string".fmt(f
),
1539 Error
::ValueAfterTable
=> "values must be emitted before tables".fmt(f
),
1540 Error
::DateInvalid
=> "a serialized date was invalid".fmt(f
),
1541 Error
::NumberInvalid
=> "a serialized number was invalid".fmt(f
),
1542 Error
::UnsupportedNone
=> "unsupported None value".fmt(f
),
1543 Error
::Custom(ref s
) => s
.fmt(f
),
1544 Error
::KeyNewline
=> unreachable
!(),
1545 Error
::ArrayMixedType
=> unreachable
!(),
1546 Error
::__Nonexhaustive
=> panic
!(),
1551 impl error
::Error
for Error {}
1553 impl ser
::Error
for Error
{
1554 fn custom
<T
: fmt
::Display
>(msg
: T
) -> Error
{
1555 Error
::Custom(msg
.to_string())
1565 /// Convenience function to serialize items in a map in an order valid with
1568 /// TOML carries the restriction that keys in a table must be serialized last if
1569 /// their value is a table itself. This isn't always easy to guarantee, so this
1570 /// helper can be used like so:
1573 /// # use serde_derive::Serialize;
1574 /// # use std::collections::HashMap;
1575 /// #[derive(Serialize)]
1576 /// struct Manifest {
1577 /// package: Package,
1578 /// #[serde(serialize_with = "toml::ser::tables_last")]
1579 /// dependencies: HashMap<String, Dependency>,
1581 /// # type Package = String;
1582 /// # type Dependency = String;
1585 pub fn tables_last
<'a
, I
, K
, V
, S
>(data
: &'a I
, serializer
: S
) -> Result
<S
::Ok
, S
::Error
>
1587 &'a I
: IntoIterator
<Item
= (K
, V
)>,
1592 use serde
::ser
::SerializeMap
;
1594 let mut map
= serializer
.serialize_map(None
)?
;
1595 for (k
, v
) in data
{
1596 if let Category
::Primitive
= v
.serialize(Categorize
::new())?
{
1597 map
.serialize_entry(&k
, &v
)?
;
1600 for (k
, v
) in data
{
1601 if let Category
::Array
= v
.serialize(Categorize
::new())?
{
1602 map
.serialize_entry(&k
, &v
)?
;
1605 for (k
, v
) in data
{
1606 if let Category
::Table
= v
.serialize(Categorize
::new())?
{
1607 map
.serialize_entry(&k
, &v
)?
;
1613 struct Categorize
<E
>(marker
::PhantomData
<E
>);
1615 impl<E
> Categorize
<E
> {
1617 Categorize(marker
::PhantomData
)
1621 impl<E
: ser
::Error
> ser
::Serializer
for Categorize
<E
> {
1624 type SerializeSeq
= Self;
1625 type SerializeTuple
= Self;
1626 type SerializeTupleStruct
= Self;
1627 type SerializeTupleVariant
= Self;
1628 type SerializeMap
= Self;
1629 type SerializeStruct
= Self;
1630 type SerializeStructVariant
= ser
::Impossible
<Category
, E
>;
1632 fn serialize_bool(self, _
: bool
) -> Result
<Self::Ok
, Self::Error
> {
1633 Ok(Category
::Primitive
)
1636 fn serialize_i8(self, _
: i8) -> Result
<Self::Ok
, Self::Error
> {
1637 Ok(Category
::Primitive
)
1640 fn serialize_i16(self, _
: i16) -> Result
<Self::Ok
, Self::Error
> {
1641 Ok(Category
::Primitive
)
1644 fn serialize_i32(self, _
: i32) -> Result
<Self::Ok
, Self::Error
> {
1645 Ok(Category
::Primitive
)
1648 fn serialize_i64(self, _
: i64) -> Result
<Self::Ok
, Self::Error
> {
1649 Ok(Category
::Primitive
)
1652 fn serialize_u8(self, _
: u8) -> Result
<Self::Ok
, Self::Error
> {
1653 Ok(Category
::Primitive
)
1656 fn serialize_u16(self, _
: u16) -> Result
<Self::Ok
, Self::Error
> {
1657 Ok(Category
::Primitive
)
1660 fn serialize_u32(self, _
: u32) -> Result
<Self::Ok
, Self::Error
> {
1661 Ok(Category
::Primitive
)
1664 fn serialize_u64(self, _
: u64) -> Result
<Self::Ok
, Self::Error
> {
1665 Ok(Category
::Primitive
)
1668 fn serialize_f32(self, _
: f32) -> Result
<Self::Ok
, Self::Error
> {
1669 Ok(Category
::Primitive
)
1672 fn serialize_f64(self, _
: f64) -> Result
<Self::Ok
, Self::Error
> {
1673 Ok(Category
::Primitive
)
1676 fn serialize_char(self, _
: char) -> Result
<Self::Ok
, Self::Error
> {
1677 Ok(Category
::Primitive
)
1680 fn serialize_str(self, _
: &str) -> Result
<Self::Ok
, Self::Error
> {
1681 Ok(Category
::Primitive
)
1684 fn serialize_bytes(self, _
: &[u8]) -> Result
<Self::Ok
, Self::Error
> {
1688 fn serialize_none(self) -> Result
<Self::Ok
, Self::Error
> {
1689 Err(ser
::Error
::custom("unsupported"))
1692 fn serialize_some
<T
: ?Sized
+ ser
::Serialize
>(self, v
: &T
) -> Result
<Self::Ok
, Self::Error
> {
1696 fn serialize_unit(self) -> Result
<Self::Ok
, Self::Error
> {
1697 Err(ser
::Error
::custom("unsupported"))
1700 fn serialize_unit_struct(self, _
: &'
static str) -> Result
<Self::Ok
, Self::Error
> {
1701 Err(ser
::Error
::custom("unsupported"))
1704 fn serialize_unit_variant(
1709 ) -> Result
<Self::Ok
, Self::Error
> {
1710 Err(ser
::Error
::custom("unsupported"))
1713 fn serialize_newtype_struct
<T
: ?Sized
+ ser
::Serialize
>(
1717 ) -> Result
<Self::Ok
, Self::Error
> {
1721 fn serialize_newtype_variant
<T
: ?Sized
+ ser
::Serialize
>(
1727 ) -> Result
<Self::Ok
, Self::Error
> {
1728 Err(ser
::Error
::custom("unsupported"))
1731 fn serialize_seq(self, _
: Option
<usize>) -> Result
<Self, Self::Error
> {
1735 fn serialize_tuple(self, _
: usize) -> Result
<Self::SerializeTuple
, Self::Error
> {
1739 fn serialize_tuple_struct(
1743 ) -> Result
<Self::SerializeTupleStruct
, Self::Error
> {
1747 fn serialize_tuple_variant(
1753 ) -> Result
<Self::SerializeTupleVariant
, Self::Error
> {
1757 fn serialize_map(self, _
: Option
<usize>) -> Result
<Self, Self::Error
> {
1761 fn serialize_struct(self, _
: &'
static str, _
: usize) -> Result
<Self, Self::Error
> {
1765 fn serialize_struct_variant(
1771 ) -> Result
<Self::SerializeStructVariant
, Self::Error
> {
1772 Err(ser
::Error
::custom("unsupported"))
1776 impl<E
: ser
::Error
> ser
::SerializeSeq
for Categorize
<E
> {
1780 fn serialize_element
<T
: ?Sized
+ ser
::Serialize
>(&mut self, _
: &T
) -> Result
<(), Self::Error
> {
1784 fn end(self) -> Result
<Self::Ok
, Self::Error
> {
1789 impl<E
: ser
::Error
> ser
::SerializeTuple
for Categorize
<E
> {
1793 fn serialize_element
<T
: ?Sized
+ ser
::Serialize
>(&mut self, _
: &T
) -> Result
<(), Self::Error
> {
1797 fn end(self) -> Result
<Self::Ok
, Self::Error
> {
1802 impl<E
: ser
::Error
> ser
::SerializeTupleVariant
for Categorize
<E
> {
1806 fn serialize_field
<T
: ?Sized
+ ser
::Serialize
>(&mut self, _
: &T
) -> Result
<(), Self::Error
> {
1810 fn end(self) -> Result
<Self::Ok
, Self::Error
> {
1815 impl<E
: ser
::Error
> ser
::SerializeTupleStruct
for Categorize
<E
> {
1819 fn serialize_field
<T
: ?Sized
+ ser
::Serialize
>(&mut self, _
: &T
) -> Result
<(), Self::Error
> {
1823 fn end(self) -> Result
<Self::Ok
, Self::Error
> {
1828 impl<E
: ser
::Error
> ser
::SerializeMap
for Categorize
<E
> {
1832 fn serialize_key
<T
: ?Sized
+ ser
::Serialize
>(&mut self, _
: &T
) -> Result
<(), Self::Error
> {
1836 fn serialize_value
<T
: ?Sized
+ ser
::Serialize
>(&mut self, _
: &T
) -> Result
<(), Self::Error
> {
1840 fn end(self) -> Result
<Self::Ok
, Self::Error
> {
1845 impl<E
: ser
::Error
> ser
::SerializeStruct
for Categorize
<E
> {
1849 fn serialize_field
<T
: ?Sized
>(&mut self, _
: &'
static str, _
: &T
) -> Result
<(), Self::Error
>
1856 fn end(self) -> Result
<Self::Ok
, Self::Error
> {