toml/
ser.rs

1//! Serializing Rust structures into TOML.
2//!
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.
6//!
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:
13//!
14//! ```rust
15//! # use serde_derive::Serialize;
16//! # use std::collections::HashMap;
17//! #[derive(Serialize)]
18//! struct Manifest {
19//!     package: Package,
20//!     #[serde(serialize_with = "toml::ser::tables_last")]
21//!     dependencies: HashMap<String, Dependency>,
22//! }
23//! # type Package = String;
24//! # type Dependency = String;
25//! # fn main() {}
26//! ```
27
28use std::cell::Cell;
29use std::error;
30use std::fmt::{self, Write};
31use std::marker;
32use std::rc::Rc;
33
34use crate::datetime;
35use serde::ser;
36
37/// Serialize the given data structure as a TOML byte vector.
38///
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.
42pub fn to_vec<T: ?Sized>(value: &T) -> Result<Vec<u8>, Error>
43where
44    T: ser::Serialize,
45{
46    to_string(value).map(|e| e.into_bytes())
47}
48
49/// Serialize the given data structure as a String of TOML.
50///
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.
54///
55/// # Examples
56///
57/// ```
58/// use serde_derive::Serialize;
59///
60/// #[derive(Serialize)]
61/// struct Config {
62///     database: Database,
63/// }
64///
65/// #[derive(Serialize)]
66/// struct Database {
67///     ip: String,
68///     port: Vec<u16>,
69///     connection_max: u32,
70///     enabled: bool,
71/// }
72///
73/// fn main() {
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,
79///             enabled: false,
80///         },
81///     };
82///
83///     let toml = toml::to_string(&config).unwrap();
84///     println!("{}", toml)
85/// }
86/// ```
87pub fn to_string<T: ?Sized>(value: &T) -> Result<String, Error>
88where
89    T: ser::Serialize,
90{
91    let mut dst = String::with_capacity(128);
92    value.serialize(&mut Serializer::new(&mut dst))?;
93    Ok(dst)
94}
95
96/// Serialize the given data structure as a "pretty" String of TOML.
97///
98/// This is identical to `to_string` except the output string has a more
99/// "pretty" output. See `Serializer::pretty` for more details.
100pub fn to_string_pretty<T: ?Sized>(value: &T) -> Result<String, Error>
101where
102    T: ser::Serialize,
103{
104    let mut dst = String::with_capacity(128);
105    value.serialize(&mut Serializer::pretty(&mut dst))?;
106    Ok(dst)
107}
108
109/// Errors that can occur when serializing a type.
110#[derive(Debug, PartialEq, Eq, Clone)]
111pub enum Error {
112    /// Indicates that a Rust type was requested to be serialized but it was not
113    /// supported.
114    ///
115    /// Currently the TOML format does not support serializing types such as
116    /// enums, tuples and tuple structs.
117    UnsupportedType,
118
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.
121    KeyNotString,
122
123    /// An error that we never omit but keep for backwards compatibility
124    #[doc(hidden)]
125    KeyNewline,
126
127    /// Arrays in TOML must have a homogenous type, but a heterogeneous array
128    /// was emitted.
129    ArrayMixedType,
130
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
133    /// generated.
134    ValueAfterTable,
135
136    /// A serialized date was invalid.
137    DateInvalid,
138
139    /// A serialized number was invalid.
140    NumberInvalid,
141
142    /// None was attempted to be serialized, but it's not supported.
143    UnsupportedNone,
144
145    /// A custom error which could be generated when serializing a particular
146    /// type.
147    Custom(String),
148
149    #[doc(hidden)]
150    __Nonexhaustive,
151}
152
153#[derive(Debug, Default, Clone)]
154/// Internal place for holding array setings
155struct ArraySettings {
156    indent: usize,
157    trailing_comma: bool,
158}
159
160impl ArraySettings {
161    fn pretty() -> ArraySettings {
162        ArraySettings {
163            indent: 4,
164            trailing_comma: true,
165        }
166    }
167}
168
169#[derive(Debug, Default, Clone)]
170/// String settings
171struct StringSettings {
172    /// Whether to use literal strings when possible
173    literal: bool,
174}
175
176impl StringSettings {
177    fn pretty() -> StringSettings {
178        StringSettings { literal: true }
179    }
180}
181
182#[derive(Debug, Default, Clone)]
183/// Internal struct for holding serialization settings
184struct Settings {
185    array: Option<ArraySettings>,
186    string: Option<StringSettings>,
187}
188
189/// Serialization implementation for TOML.
190///
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.
195///
196/// Currently a serializer always writes its output to an in-memory `String`,
197/// which is passed in when creating the serializer itself.
198pub struct Serializer<'a> {
199    dst: &'a mut String,
200    state: State<'a>,
201    settings: Rc<Settings>,
202}
203
204#[derive(Debug, Clone)]
205enum State<'a> {
206    Table {
207        key: &'a str,
208        parent: &'a State<'a>,
209        first: &'a Cell<bool>,
210        table_emitted: &'a Cell<bool>,
211    },
212    Array {
213        parent: &'a State<'a>,
214        first: &'a Cell<bool>,
215        type_: &'a Cell<Option<&'static str>>,
216        len: Option<usize>,
217    },
218    End,
219}
220
221#[doc(hidden)]
222pub struct SerializeSeq<'a, 'b> {
223    ser: &'b mut Serializer<'a>,
224    first: Cell<bool>,
225    type_: Cell<Option<&'static str>>,
226    len: Option<usize>,
227}
228
229#[doc(hidden)]
230pub enum SerializeTable<'a, 'b> {
231    Datetime(&'b mut Serializer<'a>),
232    Table {
233        ser: &'b mut Serializer<'a>,
234        key: String,
235        first: Cell<bool>,
236        table_emitted: Cell<bool>,
237    },
238}
239
240impl<'a> Serializer<'a> {
241    /// Creates a new serializer which will emit TOML into the buffer provided.
242    ///
243    /// The serializer can then be used to serialize a type after which the data
244    /// will be present in `dst`.
245    pub fn new(dst: &'a mut String) -> Serializer<'a> {
246        Serializer {
247            dst,
248            state: State::End,
249            settings: Rc::new(Settings::default()),
250        }
251    }
252
253    /// Instantiate a "pretty" formatter
254    ///
255    /// By default this will use:
256    ///
257    /// - pretty strings: strings with newlines will use the `'''` syntax. See
258    ///   `Serializer::pretty_string`
259    /// - pretty arrays: each item in arrays will be on a newline, have an indentation of 4 and
260    ///   have a trailing comma. See `Serializer::pretty_array`
261    pub fn pretty(dst: &'a mut String) -> Serializer<'a> {
262        Serializer {
263            dst,
264            state: State::End,
265            settings: Rc::new(Settings {
266                array: Some(ArraySettings::pretty()),
267                string: Some(StringSettings::pretty()),
268            }),
269        }
270    }
271
272    /// Enable or Disable pretty strings
273    ///
274    /// If enabled, literal strings will be used when possible and strings with
275    /// one or more newlines will use triple quotes (i.e.: `'''` or `"""`)
276    ///
277    /// # Examples
278    ///
279    /// Instead of:
280    ///
281    /// ```toml,ignore
282    /// single = "no newlines"
283    /// text = "\nfoo\nbar\n"
284    /// ```
285    ///
286    /// You will have:
287    ///
288    /// ```toml,ignore
289    /// single = 'no newlines'
290    /// text = '''
291    /// foo
292    /// bar
293    /// '''
294    /// ```
295    pub fn pretty_string(&mut self, value: bool) -> &mut Self {
296        Rc::get_mut(&mut self.settings).unwrap().string = if value {
297            Some(StringSettings::pretty())
298        } else {
299            None
300        };
301        self
302    }
303
304    /// Enable or Disable Literal strings for pretty strings
305    ///
306    /// If enabled, literal strings will be used when possible and strings with
307    /// one or more newlines will use triple quotes (i.e.: `'''` or `"""`)
308    ///
309    /// If disabled, literal strings will NEVER be used and strings with one or
310    /// more newlines will use `"""`
311    ///
312    /// # Examples
313    ///
314    /// Instead of:
315    ///
316    /// ```toml,ignore
317    /// single = "no newlines"
318    /// text = "\nfoo\nbar\n"
319    /// ```
320    ///
321    /// You will have:
322    ///
323    /// ```toml,ignore
324    /// single = "no newlines"
325    /// text = """
326    /// foo
327    /// bar
328    /// """
329    /// ```
330    pub fn pretty_string_literal(&mut self, value: bool) -> &mut Self {
331        let use_default = if let Some(ref mut s) = Rc::get_mut(&mut self.settings).unwrap().string {
332            s.literal = value;
333            false
334        } else {
335            true
336        };
337
338        if use_default {
339            let mut string = StringSettings::pretty();
340            string.literal = value;
341            Rc::get_mut(&mut self.settings).unwrap().string = Some(string);
342        }
343        self
344    }
345
346    /// Enable or Disable pretty arrays
347    ///
348    /// If enabled, arrays will always have each item on their own line.
349    ///
350    /// Some specific features can be controlled via other builder methods:
351    ///
352    /// - `Serializer::pretty_array_indent`: set the indent to a value other
353    ///   than 4.
354    /// - `Serializer::pretty_array_trailing_comma`: enable/disable the trailing
355    ///   comma on the last item.
356    ///
357    /// # Examples
358    ///
359    /// Instead of:
360    ///
361    /// ```toml,ignore
362    /// array = ["foo", "bar"]
363    /// ```
364    ///
365    /// You will have:
366    ///
367    /// ```toml,ignore
368    /// array = [
369    ///     "foo",
370    ///     "bar",
371    /// ]
372    /// ```
373    pub fn pretty_array(&mut self, value: bool) -> &mut Self {
374        Rc::get_mut(&mut self.settings).unwrap().array = if value {
375            Some(ArraySettings::pretty())
376        } else {
377            None
378        };
379        self
380    }
381
382    /// Set the indent for pretty arrays
383    ///
384    /// See `Serializer::pretty_array` for more details.
385    pub fn pretty_array_indent(&mut self, value: usize) -> &mut Self {
386        let use_default = if let Some(ref mut a) = Rc::get_mut(&mut self.settings).unwrap().array {
387            a.indent = value;
388            false
389        } else {
390            true
391        };
392
393        if use_default {
394            let mut array = ArraySettings::pretty();
395            array.indent = value;
396            Rc::get_mut(&mut self.settings).unwrap().array = Some(array);
397        }
398        self
399    }
400
401    /// Specify whether to use a trailing comma when serializing pretty arrays
402    ///
403    /// See `Serializer::pretty_array` for more details.
404    pub fn pretty_array_trailing_comma(&mut self, value: bool) -> &mut Self {
405        let use_default = if let Some(ref mut a) = Rc::get_mut(&mut self.settings).unwrap().array {
406            a.trailing_comma = value;
407            false
408        } else {
409            true
410        };
411
412        if use_default {
413            let mut array = ArraySettings::pretty();
414            array.trailing_comma = value;
415            Rc::get_mut(&mut self.settings).unwrap().array = Some(array);
416        }
417        self
418    }
419
420    fn display<T: fmt::Display>(&mut self, t: T, type_: &'static str) -> Result<(), Error> {
421        self.emit_key(type_)?;
422        write!(self.dst, "{}", t).map_err(ser::Error::custom)?;
423        if let State::Table { .. } = self.state {
424            self.dst.push_str("\n");
425        }
426        Ok(())
427    }
428
429    fn emit_key(&mut self, type_: &'static str) -> Result<(), Error> {
430        self.array_type(type_)?;
431        let state = self.state.clone();
432        self._emit_key(&state)
433    }
434
435    // recursive implementation of `emit_key` above
436    fn _emit_key(&mut self, state: &State<'_>) -> Result<(), Error> {
437        match *state {
438            State::End => Ok(()),
439            State::Array {
440                parent,
441                first,
442                type_,
443                len,
444            } => {
445                assert!(type_.get().is_some());
446                if first.get() {
447                    self._emit_key(parent)?;
448                }
449                self.emit_array(first, len)
450            }
451            State::Table {
452                parent,
453                first,
454                table_emitted,
455                key,
456            } => {
457                if table_emitted.get() {
458                    return Err(Error::ValueAfterTable);
459                }
460                if first.get() {
461                    self.emit_table_header(parent)?;
462                    first.set(false);
463                }
464                self.escape_key(key)?;
465                self.dst.push_str(" = ");
466                Ok(())
467            }
468        }
469    }
470
471    fn emit_array(&mut self, first: &Cell<bool>, len: Option<usize>) -> Result<(), Error> {
472        match (len, &self.settings.array) {
473            (Some(0..=1), _) | (_, &None) => {
474                if first.get() {
475                    self.dst.push_str("[")
476                } else {
477                    self.dst.push_str(", ")
478                }
479            }
480            (_, &Some(ref a)) => {
481                if first.get() {
482                    self.dst.push_str("[\n")
483                } else {
484                    self.dst.push_str(",\n")
485                }
486                for _ in 0..a.indent {
487                    self.dst.push_str(" ");
488                }
489            }
490        }
491        Ok(())
492    }
493
494    fn array_type(&mut self, type_: &'static str) -> Result<(), Error> {
495        let prev = match self.state {
496            State::Array { type_, .. } => type_,
497            _ => return Ok(()),
498        };
499        if let Some(prev) = prev.get() {
500            if prev != type_ {
501                return Err(Error::ArrayMixedType);
502            }
503        } else {
504            prev.set(Some(type_));
505        }
506        Ok(())
507    }
508
509    fn escape_key(&mut self, key: &str) -> Result<(), Error> {
510        let ok = key.chars().all(|c| match c {
511            'a'..='z' | 'A'..='Z' | '0'..='9' | '-' | '_' => true,
512            _ => false,
513        });
514        if ok {
515            write!(self.dst, "{}", key).map_err(ser::Error::custom)?;
516        } else {
517            self.emit_str(key, true)?;
518        }
519        Ok(())
520    }
521
522    fn emit_str(&mut self, value: &str, is_key: bool) -> Result<(), Error> {
523        #[derive(PartialEq)]
524        enum Type {
525            NewlineTripple,
526            OnelineTripple,
527            OnelineSingle,
528        }
529
530        enum Repr {
531            /// represent as a literal string (using '')
532            Literal(String, Type),
533            /// represent the std way (using "")
534            Std(Type),
535        }
536
537        fn do_pretty(value: &str) -> Repr {
538            // For doing pretty prints we store in a new String
539            // because there are too many cases where pretty cannot
540            // work. We need to determine:
541            // - if we are a "multi-line" pretty (if there are \n)
542            // - if ['''] appears if multi or ['] if single
543            // - if there are any invalid control characters
544            //
545            // Doing it any other way would require multiple passes
546            // to determine if a pretty string works or not.
547            let mut out = String::with_capacity(value.len() * 2);
548            let mut ty = Type::OnelineSingle;
549            // found consecutive single quotes
550            let mut max_found_singles = 0;
551            let mut found_singles = 0;
552            let mut can_be_pretty = true;
553
554            for ch in value.chars() {
555                if can_be_pretty {
556                    if ch == '\'' {
557                        found_singles += 1;
558                        if found_singles >= 3 {
559                            can_be_pretty = false;
560                        }
561                    } else {
562                        if found_singles > max_found_singles {
563                            max_found_singles = found_singles;
564                        }
565                        found_singles = 0
566                    }
567                    match ch {
568                        '\t' => {}
569                        '\n' => ty = Type::NewlineTripple,
570                        // note that the following are invalid: \b \f \r
571                        c if c < '\u{1f}' => can_be_pretty = false, // Invalid control character
572                        _ => {}
573                    }
574                    out.push(ch);
575                } else {
576                    // the string cannot be represented as pretty,
577                    // still check if it should be multiline
578                    if ch == '\n' {
579                        ty = Type::NewlineTripple;
580                    }
581                }
582            }
583            if can_be_pretty && found_singles > 0 && value.ends_with('\'') {
584                // We cannot escape the ending quote so we must use """
585                can_be_pretty = false;
586            }
587            if !can_be_pretty {
588                debug_assert!(ty != Type::OnelineTripple);
589                return Repr::Std(ty);
590            }
591            if found_singles > max_found_singles {
592                max_found_singles = found_singles;
593            }
594            debug_assert!(max_found_singles < 3);
595            if ty == Type::OnelineSingle && max_found_singles >= 1 {
596                // no newlines, but must use ''' because it has ' in it
597                ty = Type::OnelineTripple;
598            }
599            Repr::Literal(out, ty)
600        }
601
602        let repr = if !is_key && self.settings.string.is_some() {
603            match (&self.settings.string, do_pretty(value)) {
604                (&Some(StringSettings { literal: false, .. }), Repr::Literal(_, ty)) => {
605                    Repr::Std(ty)
606                }
607                (_, r) => r,
608            }
609        } else {
610            Repr::Std(Type::OnelineSingle)
611        };
612        match repr {
613            Repr::Literal(literal, ty) => {
614                // A pretty string
615                match ty {
616                    Type::NewlineTripple => self.dst.push_str("'''\n"),
617                    Type::OnelineTripple => self.dst.push_str("'''"),
618                    Type::OnelineSingle => self.dst.push('\''),
619                }
620                self.dst.push_str(&literal);
621                match ty {
622                    Type::OnelineSingle => self.dst.push('\''),
623                    _ => self.dst.push_str("'''"),
624                }
625            }
626            Repr::Std(ty) => {
627                match ty {
628                    Type::NewlineTripple => self.dst.push_str("\"\"\"\n"),
629                    // note: OnelineTripple can happen if do_pretty wants to do
630                    // '''it's one line'''
631                    // but settings.string.literal == false
632                    Type::OnelineSingle | Type::OnelineTripple => self.dst.push('"'),
633                }
634                for ch in value.chars() {
635                    match ch {
636                        '\u{8}' => self.dst.push_str("\\b"),
637                        '\u{9}' => self.dst.push_str("\\t"),
638                        '\u{a}' => match ty {
639                            Type::NewlineTripple => self.dst.push('\n'),
640                            Type::OnelineSingle => self.dst.push_str("\\n"),
641                            _ => unreachable!(),
642                        },
643                        '\u{c}' => self.dst.push_str("\\f"),
644                        '\u{d}' => self.dst.push_str("\\r"),
645                        '\u{22}' => self.dst.push_str("\\\""),
646                        '\u{5c}' => self.dst.push_str("\\\\"),
647                        c if c < '\u{1f}' => {
648                            write!(self.dst, "\\u{:04X}", ch as u32).map_err(ser::Error::custom)?;
649                        }
650                        ch => self.dst.push(ch),
651                    }
652                }
653                match ty {
654                    Type::NewlineTripple => self.dst.push_str("\"\"\""),
655                    Type::OnelineSingle | Type::OnelineTripple => self.dst.push('"'),
656                }
657            }
658        }
659        Ok(())
660    }
661
662    fn emit_table_header(&mut self, state: &State<'_>) -> Result<(), Error> {
663        let array_of_tables = match *state {
664            State::End => return Ok(()),
665            State::Array { .. } => true,
666            _ => false,
667        };
668
669        // Unlike [..]s, we can't omit [[..]] ancestors, so be sure to emit table
670        // headers for them.
671        let mut p = state;
672        if let State::Array { first, parent, .. } = *state {
673            if first.get() {
674                p = parent;
675            }
676        }
677        while let State::Table { first, parent, .. } = *p {
678            p = parent;
679            if !first.get() {
680                break;
681            }
682            if let State::Array {
683                parent: &State::Table { .. },
684                ..
685            } = *parent
686            {
687                self.emit_table_header(parent)?;
688                break;
689            }
690        }
691
692        match *state {
693            State::Table { first, .. } => {
694                if !first.get() {
695                    // Newline if we are a table that is not the first
696                    // table in the document.
697                    self.dst.push('\n');
698                }
699            }
700            State::Array { parent, first, .. } => {
701                if !first.get() {
702                    // Always newline if we are not the first item in the
703                    // table-array
704                    self.dst.push('\n');
705                } else if let State::Table { first, .. } = *parent {
706                    if !first.get() {
707                        // Newline if we are not the first item in the document
708                        self.dst.push('\n');
709                    }
710                }
711            }
712            _ => {}
713        }
714        self.dst.push_str("[");
715        if array_of_tables {
716            self.dst.push_str("[");
717        }
718        self.emit_key_part(state)?;
719        if array_of_tables {
720            self.dst.push_str("]");
721        }
722        self.dst.push_str("]\n");
723        Ok(())
724    }
725
726    fn emit_key_part(&mut self, key: &State<'_>) -> Result<bool, Error> {
727        match *key {
728            State::Array { parent, .. } => self.emit_key_part(parent),
729            State::End => Ok(true),
730            State::Table {
731                key,
732                parent,
733                table_emitted,
734                ..
735            } => {
736                table_emitted.set(true);
737                let first = self.emit_key_part(parent)?;
738                if !first {
739                    self.dst.push_str(".");
740                }
741                self.escape_key(key)?;
742                Ok(false)
743            }
744        }
745    }
746}
747
748macro_rules! serialize_float {
749    ($this:expr, $v:expr) => {{
750        $this.emit_key("float")?;
751        if ($v.is_nan() || $v == 0.0) && $v.is_sign_negative() {
752            write!($this.dst, "-").map_err(ser::Error::custom)?;
753        }
754        if $v.is_nan() {
755            write!($this.dst, "nan").map_err(ser::Error::custom)?;
756        } else {
757            write!($this.dst, "{}", $v).map_err(ser::Error::custom)?;
758        }
759        if $v % 1.0 == 0.0 {
760            write!($this.dst, ".0").map_err(ser::Error::custom)?;
761        }
762        if let State::Table { .. } = $this.state {
763            $this.dst.push_str("\n");
764        }
765        return Ok(());
766    }};
767}
768
769impl<'a, 'b> ser::Serializer for &'b mut Serializer<'a> {
770    type Ok = ();
771    type Error = Error;
772    type SerializeSeq = SerializeSeq<'a, 'b>;
773    type SerializeTuple = SerializeSeq<'a, 'b>;
774    type SerializeTupleStruct = SerializeSeq<'a, 'b>;
775    type SerializeTupleVariant = SerializeSeq<'a, 'b>;
776    type SerializeMap = SerializeTable<'a, 'b>;
777    type SerializeStruct = SerializeTable<'a, 'b>;
778    type SerializeStructVariant = ser::Impossible<(), Error>;
779
780    fn serialize_bool(self, v: bool) -> Result<(), Self::Error> {
781        self.display(v, "bool")
782    }
783
784    fn serialize_i8(self, v: i8) -> Result<(), Self::Error> {
785        self.display(v, "integer")
786    }
787
788    fn serialize_i16(self, v: i16) -> Result<(), Self::Error> {
789        self.display(v, "integer")
790    }
791
792    fn serialize_i32(self, v: i32) -> Result<(), Self::Error> {
793        self.display(v, "integer")
794    }
795
796    fn serialize_i64(self, v: i64) -> Result<(), Self::Error> {
797        self.display(v, "integer")
798    }
799
800    fn serialize_u8(self, v: u8) -> Result<(), Self::Error> {
801        self.display(v, "integer")
802    }
803
804    fn serialize_u16(self, v: u16) -> Result<(), Self::Error> {
805        self.display(v, "integer")
806    }
807
808    fn serialize_u32(self, v: u32) -> Result<(), Self::Error> {
809        self.display(v, "integer")
810    }
811
812    fn serialize_u64(self, v: u64) -> Result<(), Self::Error> {
813        self.display(v, "integer")
814    }
815
816    fn serialize_f32(self, v: f32) -> Result<(), Self::Error> {
817        serialize_float!(self, v)
818    }
819
820    fn serialize_f64(self, v: f64) -> Result<(), Self::Error> {
821        serialize_float!(self, v)
822    }
823
824    fn serialize_char(self, v: char) -> Result<(), Self::Error> {
825        let mut buf = [0; 4];
826        self.serialize_str(v.encode_utf8(&mut buf))
827    }
828
829    fn serialize_str(self, value: &str) -> Result<(), Self::Error> {
830        self.emit_key("string")?;
831        self.emit_str(value, false)?;
832        if let State::Table { .. } = self.state {
833            self.dst.push_str("\n");
834        }
835        Ok(())
836    }
837
838    fn serialize_bytes(self, value: &[u8]) -> Result<(), Self::Error> {
839        use serde::ser::Serialize;
840        value.serialize(self)
841    }
842
843    fn serialize_none(self) -> Result<(), Self::Error> {
844        Err(Error::UnsupportedNone)
845    }
846
847    fn serialize_some<T: ?Sized>(self, value: &T) -> Result<(), Self::Error>
848    where
849        T: ser::Serialize,
850    {
851        value.serialize(self)
852    }
853
854    fn serialize_unit(self) -> Result<(), Self::Error> {
855        Err(Error::UnsupportedType)
856    }
857
858    fn serialize_unit_struct(self, _name: &'static str) -> Result<(), Self::Error> {
859        Err(Error::UnsupportedType)
860    }
861
862    fn serialize_unit_variant(
863        self,
864        _name: &'static str,
865        _variant_index: u32,
866        variant: &'static str,
867    ) -> Result<(), Self::Error> {
868        self.serialize_str(variant)
869    }
870
871    fn serialize_newtype_struct<T: ?Sized>(
872        self,
873        _name: &'static str,
874        value: &T,
875    ) -> Result<(), Self::Error>
876    where
877        T: ser::Serialize,
878    {
879        value.serialize(self)
880    }
881
882    fn serialize_newtype_variant<T: ?Sized>(
883        self,
884        _name: &'static str,
885        _variant_index: u32,
886        _variant: &'static str,
887        _value: &T,
888    ) -> Result<(), Self::Error>
889    where
890        T: ser::Serialize,
891    {
892        Err(Error::UnsupportedType)
893    }
894
895    fn serialize_seq(self, len: Option<usize>) -> Result<Self::SerializeSeq, Self::Error> {
896        self.array_type("array")?;
897        Ok(SerializeSeq {
898            ser: self,
899            first: Cell::new(true),
900            type_: Cell::new(None),
901            len,
902        })
903    }
904
905    fn serialize_tuple(self, len: usize) -> Result<Self::SerializeTuple, Self::Error> {
906        self.serialize_seq(Some(len))
907    }
908
909    fn serialize_tuple_struct(
910        self,
911        _name: &'static str,
912        len: usize,
913    ) -> Result<Self::SerializeTupleStruct, Self::Error> {
914        self.serialize_seq(Some(len))
915    }
916
917    fn serialize_tuple_variant(
918        self,
919        _name: &'static str,
920        _variant_index: u32,
921        _variant: &'static str,
922        len: usize,
923    ) -> Result<Self::SerializeTupleVariant, Self::Error> {
924        self.serialize_seq(Some(len))
925    }
926
927    fn serialize_map(self, _len: Option<usize>) -> Result<Self::SerializeMap, Self::Error> {
928        self.array_type("table")?;
929        Ok(SerializeTable::Table {
930            ser: self,
931            key: String::new(),
932            first: Cell::new(true),
933            table_emitted: Cell::new(false),
934        })
935    }
936
937    fn serialize_struct(
938        self,
939        name: &'static str,
940        _len: usize,
941    ) -> Result<Self::SerializeStruct, Self::Error> {
942        if name == datetime::NAME {
943            self.array_type("datetime")?;
944            Ok(SerializeTable::Datetime(self))
945        } else {
946            self.array_type("table")?;
947            Ok(SerializeTable::Table {
948                ser: self,
949                key: String::new(),
950                first: Cell::new(true),
951                table_emitted: Cell::new(false),
952            })
953        }
954    }
955
956    fn serialize_struct_variant(
957        self,
958        _name: &'static str,
959        _variant_index: u32,
960        _variant: &'static str,
961        _len: usize,
962    ) -> Result<Self::SerializeStructVariant, Self::Error> {
963        Err(Error::UnsupportedType)
964    }
965}
966
967impl<'a, 'b> ser::SerializeSeq for SerializeSeq<'a, 'b> {
968    type Ok = ();
969    type Error = Error;
970
971    fn serialize_element<T: ?Sized>(&mut self, value: &T) -> Result<(), Error>
972    where
973        T: ser::Serialize,
974    {
975        value.serialize(&mut Serializer {
976            dst: &mut *self.ser.dst,
977            state: State::Array {
978                parent: &self.ser.state,
979                first: &self.first,
980                type_: &self.type_,
981                len: self.len,
982            },
983            settings: self.ser.settings.clone(),
984        })?;
985        self.first.set(false);
986        Ok(())
987    }
988
989    fn end(self) -> Result<(), Error> {
990        match self.type_.get() {
991            Some("table") => return Ok(()),
992            Some(_) => match (self.len, &self.ser.settings.array) {
993                (Some(0..=1), _) | (_, &None) => {
994                    self.ser.dst.push_str("]");
995                }
996                (_, &Some(ref a)) => {
997                    if a.trailing_comma {
998                        self.ser.dst.push_str(",");
999                    }
1000                    self.ser.dst.push_str("\n]");
1001                }
1002            },
1003            None => {
1004                assert!(self.first.get());
1005                self.ser.emit_key("array")?;
1006                self.ser.dst.push_str("[]")
1007            }
1008        }
1009        if let State::Table { .. } = self.ser.state {
1010            self.ser.dst.push_str("\n");
1011        }
1012        Ok(())
1013    }
1014}
1015
1016impl<'a, 'b> ser::SerializeTuple for SerializeSeq<'a, 'b> {
1017    type Ok = ();
1018    type Error = Error;
1019
1020    fn serialize_element<T: ?Sized>(&mut self, value: &T) -> Result<(), Error>
1021    where
1022        T: ser::Serialize,
1023    {
1024        ser::SerializeSeq::serialize_element(self, value)
1025    }
1026
1027    fn end(self) -> Result<(), Error> {
1028        ser::SerializeSeq::end(self)
1029    }
1030}
1031
1032impl<'a, 'b> ser::SerializeTupleVariant for SerializeSeq<'a, 'b> {
1033    type Ok = ();
1034    type Error = Error;
1035
1036    fn serialize_field<T: ?Sized>(&mut self, value: &T) -> Result<(), Error>
1037    where
1038        T: ser::Serialize,
1039    {
1040        ser::SerializeSeq::serialize_element(self, value)
1041    }
1042
1043    fn end(self) -> Result<(), Error> {
1044        ser::SerializeSeq::end(self)
1045    }
1046}
1047
1048impl<'a, 'b> ser::SerializeTupleStruct for SerializeSeq<'a, 'b> {
1049    type Ok = ();
1050    type Error = Error;
1051
1052    fn serialize_field<T: ?Sized>(&mut self, value: &T) -> Result<(), Error>
1053    where
1054        T: ser::Serialize,
1055    {
1056        ser::SerializeSeq::serialize_element(self, value)
1057    }
1058
1059    fn end(self) -> Result<(), Error> {
1060        ser::SerializeSeq::end(self)
1061    }
1062}
1063
1064impl<'a, 'b> ser::SerializeMap for SerializeTable<'a, 'b> {
1065    type Ok = ();
1066    type Error = Error;
1067
1068    fn serialize_key<T: ?Sized>(&mut self, input: &T) -> Result<(), Error>
1069    where
1070        T: ser::Serialize,
1071    {
1072        match *self {
1073            SerializeTable::Datetime(_) => panic!(), // shouldn't be possible
1074            SerializeTable::Table { ref mut key, .. } => {
1075                key.truncate(0);
1076                *key = input.serialize(StringExtractor)?;
1077            }
1078        }
1079        Ok(())
1080    }
1081
1082    fn serialize_value<T: ?Sized>(&mut self, value: &T) -> Result<(), Error>
1083    where
1084        T: ser::Serialize,
1085    {
1086        match *self {
1087            SerializeTable::Datetime(_) => panic!(), // shouldn't be possible
1088            SerializeTable::Table {
1089                ref mut ser,
1090                ref key,
1091                ref first,
1092                ref table_emitted,
1093                ..
1094            } => {
1095                let res = value.serialize(&mut Serializer {
1096                    dst: &mut *ser.dst,
1097                    state: State::Table {
1098                        key,
1099                        parent: &ser.state,
1100                        first,
1101                        table_emitted,
1102                    },
1103                    settings: ser.settings.clone(),
1104                });
1105                match res {
1106                    Ok(()) => first.set(false),
1107                    Err(Error::UnsupportedNone) => {}
1108                    Err(e) => return Err(e),
1109                }
1110            }
1111        }
1112        Ok(())
1113    }
1114
1115    fn end(self) -> Result<(), Error> {
1116        match self {
1117            SerializeTable::Datetime(_) => panic!(), // shouldn't be possible
1118            SerializeTable::Table { ser, first, .. } => {
1119                if first.get() {
1120                    let state = ser.state.clone();
1121                    ser.emit_table_header(&state)?;
1122                }
1123            }
1124        }
1125        Ok(())
1126    }
1127}
1128
1129impl<'a, 'b> ser::SerializeStruct for SerializeTable<'a, 'b> {
1130    type Ok = ();
1131    type Error = Error;
1132
1133    fn serialize_field<T: ?Sized>(&mut self, key: &'static str, value: &T) -> Result<(), Error>
1134    where
1135        T: ser::Serialize,
1136    {
1137        match *self {
1138            SerializeTable::Datetime(ref mut ser) => {
1139                if key == datetime::FIELD {
1140                    value.serialize(DateStrEmitter(&mut *ser))?;
1141                } else {
1142                    return Err(Error::DateInvalid);
1143                }
1144            }
1145            SerializeTable::Table {
1146                ref mut ser,
1147                ref first,
1148                ref table_emitted,
1149                ..
1150            } => {
1151                let res = value.serialize(&mut Serializer {
1152                    dst: &mut *ser.dst,
1153                    state: State::Table {
1154                        key,
1155                        parent: &ser.state,
1156                        first,
1157                        table_emitted,
1158                    },
1159                    settings: ser.settings.clone(),
1160                });
1161                match res {
1162                    Ok(()) => first.set(false),
1163                    Err(Error::UnsupportedNone) => {}
1164                    Err(e) => return Err(e),
1165                }
1166            }
1167        }
1168        Ok(())
1169    }
1170
1171    fn end(self) -> Result<(), Error> {
1172        match self {
1173            SerializeTable::Datetime(_) => {}
1174            SerializeTable::Table { ser, first, .. } => {
1175                if first.get() {
1176                    let state = ser.state.clone();
1177                    ser.emit_table_header(&state)?;
1178                }
1179            }
1180        }
1181        Ok(())
1182    }
1183}
1184
1185struct DateStrEmitter<'a, 'b>(&'b mut Serializer<'a>);
1186
1187impl<'a, 'b> ser::Serializer for DateStrEmitter<'a, 'b> {
1188    type Ok = ();
1189    type Error = Error;
1190    type SerializeSeq = ser::Impossible<(), Error>;
1191    type SerializeTuple = ser::Impossible<(), Error>;
1192    type SerializeTupleStruct = ser::Impossible<(), Error>;
1193    type SerializeTupleVariant = ser::Impossible<(), Error>;
1194    type SerializeMap = ser::Impossible<(), Error>;
1195    type SerializeStruct = ser::Impossible<(), Error>;
1196    type SerializeStructVariant = ser::Impossible<(), Error>;
1197
1198    fn serialize_bool(self, _v: bool) -> Result<(), Self::Error> {
1199        Err(Error::DateInvalid)
1200    }
1201
1202    fn serialize_i8(self, _v: i8) -> Result<(), Self::Error> {
1203        Err(Error::DateInvalid)
1204    }
1205
1206    fn serialize_i16(self, _v: i16) -> Result<(), Self::Error> {
1207        Err(Error::DateInvalid)
1208    }
1209
1210    fn serialize_i32(self, _v: i32) -> Result<(), Self::Error> {
1211        Err(Error::DateInvalid)
1212    }
1213
1214    fn serialize_i64(self, _v: i64) -> Result<(), Self::Error> {
1215        Err(Error::DateInvalid)
1216    }
1217
1218    fn serialize_u8(self, _v: u8) -> Result<(), Self::Error> {
1219        Err(Error::DateInvalid)
1220    }
1221
1222    fn serialize_u16(self, _v: u16) -> Result<(), Self::Error> {
1223        Err(Error::DateInvalid)
1224    }
1225
1226    fn serialize_u32(self, _v: u32) -> Result<(), Self::Error> {
1227        Err(Error::DateInvalid)
1228    }
1229
1230    fn serialize_u64(self, _v: u64) -> Result<(), Self::Error> {
1231        Err(Error::DateInvalid)
1232    }
1233
1234    fn serialize_f32(self, _v: f32) -> Result<(), Self::Error> {
1235        Err(Error::DateInvalid)
1236    }
1237
1238    fn serialize_f64(self, _v: f64) -> Result<(), Self::Error> {
1239        Err(Error::DateInvalid)
1240    }
1241
1242    fn serialize_char(self, _v: char) -> Result<(), Self::Error> {
1243        Err(Error::DateInvalid)
1244    }
1245
1246    fn serialize_str(self, value: &str) -> Result<(), Self::Error> {
1247        self.0.display(value, "datetime")?;
1248        Ok(())
1249    }
1250
1251    fn serialize_bytes(self, _value: &[u8]) -> Result<(), Self::Error> {
1252        Err(Error::DateInvalid)
1253    }
1254
1255    fn serialize_none(self) -> Result<(), Self::Error> {
1256        Err(Error::DateInvalid)
1257    }
1258
1259    fn serialize_some<T: ?Sized>(self, _value: &T) -> Result<(), Self::Error>
1260    where
1261        T: ser::Serialize,
1262    {
1263        Err(Error::KeyNotString)
1264    }
1265
1266    fn serialize_unit(self) -> Result<(), Self::Error> {
1267        Err(Error::KeyNotString)
1268    }
1269
1270    fn serialize_unit_struct(self, _name: &'static str) -> Result<(), Self::Error> {
1271        Err(Error::DateInvalid)
1272    }
1273
1274    fn serialize_unit_variant(
1275        self,
1276        _name: &'static str,
1277        _variant_index: u32,
1278        _variant: &'static str,
1279    ) -> Result<(), Self::Error> {
1280        Err(Error::DateInvalid)
1281    }
1282
1283    fn serialize_newtype_struct<T: ?Sized>(
1284        self,
1285        _name: &'static str,
1286        _value: &T,
1287    ) -> Result<(), Self::Error>
1288    where
1289        T: ser::Serialize,
1290    {
1291        Err(Error::DateInvalid)
1292    }
1293
1294    fn serialize_newtype_variant<T: ?Sized>(
1295        self,
1296        _name: &'static str,
1297        _variant_index: u32,
1298        _variant: &'static str,
1299        _value: &T,
1300    ) -> Result<(), Self::Error>
1301    where
1302        T: ser::Serialize,
1303    {
1304        Err(Error::DateInvalid)
1305    }
1306
1307    fn serialize_seq(self, _len: Option<usize>) -> Result<Self::SerializeSeq, Self::Error> {
1308        Err(Error::DateInvalid)
1309    }
1310
1311    fn serialize_tuple(self, _len: usize) -> Result<Self::SerializeTuple, Self::Error> {
1312        Err(Error::DateInvalid)
1313    }
1314
1315    fn serialize_tuple_struct(
1316        self,
1317        _name: &'static str,
1318        _len: usize,
1319    ) -> Result<Self::SerializeTupleStruct, Self::Error> {
1320        Err(Error::DateInvalid)
1321    }
1322
1323    fn serialize_tuple_variant(
1324        self,
1325        _name: &'static str,
1326        _variant_index: u32,
1327        _variant: &'static str,
1328        _len: usize,
1329    ) -> Result<Self::SerializeTupleVariant, Self::Error> {
1330        Err(Error::DateInvalid)
1331    }
1332
1333    fn serialize_map(self, _len: Option<usize>) -> Result<Self::SerializeMap, Self::Error> {
1334        Err(Error::DateInvalid)
1335    }
1336
1337    fn serialize_struct(
1338        self,
1339        _name: &'static str,
1340        _len: usize,
1341    ) -> Result<Self::SerializeStruct, Self::Error> {
1342        Err(Error::DateInvalid)
1343    }
1344
1345    fn serialize_struct_variant(
1346        self,
1347        _name: &'static str,
1348        _variant_index: u32,
1349        _variant: &'static str,
1350        _len: usize,
1351    ) -> Result<Self::SerializeStructVariant, Self::Error> {
1352        Err(Error::DateInvalid)
1353    }
1354}
1355
1356struct StringExtractor;
1357
1358impl ser::Serializer for StringExtractor {
1359    type Ok = String;
1360    type Error = Error;
1361    type SerializeSeq = ser::Impossible<String, Error>;
1362    type SerializeTuple = ser::Impossible<String, Error>;
1363    type SerializeTupleStruct = ser::Impossible<String, Error>;
1364    type SerializeTupleVariant = ser::Impossible<String, Error>;
1365    type SerializeMap = ser::Impossible<String, Error>;
1366    type SerializeStruct = ser::Impossible<String, Error>;
1367    type SerializeStructVariant = ser::Impossible<String, Error>;
1368
1369    fn serialize_bool(self, _v: bool) -> Result<String, Self::Error> {
1370        Err(Error::KeyNotString)
1371    }
1372
1373    fn serialize_i8(self, _v: i8) -> Result<String, Self::Error> {
1374        Err(Error::KeyNotString)
1375    }
1376
1377    fn serialize_i16(self, _v: i16) -> Result<String, Self::Error> {
1378        Err(Error::KeyNotString)
1379    }
1380
1381    fn serialize_i32(self, _v: i32) -> Result<String, Self::Error> {
1382        Err(Error::KeyNotString)
1383    }
1384
1385    fn serialize_i64(self, _v: i64) -> Result<String, Self::Error> {
1386        Err(Error::KeyNotString)
1387    }
1388
1389    fn serialize_u8(self, _v: u8) -> Result<String, Self::Error> {
1390        Err(Error::KeyNotString)
1391    }
1392
1393    fn serialize_u16(self, _v: u16) -> Result<String, Self::Error> {
1394        Err(Error::KeyNotString)
1395    }
1396
1397    fn serialize_u32(self, _v: u32) -> Result<String, Self::Error> {
1398        Err(Error::KeyNotString)
1399    }
1400
1401    fn serialize_u64(self, _v: u64) -> Result<String, Self::Error> {
1402        Err(Error::KeyNotString)
1403    }
1404
1405    fn serialize_f32(self, _v: f32) -> Result<String, Self::Error> {
1406        Err(Error::KeyNotString)
1407    }
1408
1409    fn serialize_f64(self, _v: f64) -> Result<String, Self::Error> {
1410        Err(Error::KeyNotString)
1411    }
1412
1413    fn serialize_char(self, _v: char) -> Result<String, Self::Error> {
1414        Err(Error::KeyNotString)
1415    }
1416
1417    fn serialize_str(self, value: &str) -> Result<String, Self::Error> {
1418        Ok(value.to_string())
1419    }
1420
1421    fn serialize_bytes(self, _value: &[u8]) -> Result<String, Self::Error> {
1422        Err(Error::KeyNotString)
1423    }
1424
1425    fn serialize_none(self) -> Result<String, Self::Error> {
1426        Err(Error::KeyNotString)
1427    }
1428
1429    fn serialize_some<T: ?Sized>(self, _value: &T) -> Result<String, Self::Error>
1430    where
1431        T: ser::Serialize,
1432    {
1433        Err(Error::KeyNotString)
1434    }
1435
1436    fn serialize_unit(self) -> Result<String, Self::Error> {
1437        Err(Error::KeyNotString)
1438    }
1439
1440    fn serialize_unit_struct(self, _name: &'static str) -> Result<String, Self::Error> {
1441        Err(Error::KeyNotString)
1442    }
1443
1444    fn serialize_unit_variant(
1445        self,
1446        _name: &'static str,
1447        _variant_index: u32,
1448        _variant: &'static str,
1449    ) -> Result<String, Self::Error> {
1450        Err(Error::KeyNotString)
1451    }
1452
1453    fn serialize_newtype_struct<T: ?Sized>(
1454        self,
1455        _name: &'static str,
1456        value: &T,
1457    ) -> Result<String, Self::Error>
1458    where
1459        T: ser::Serialize,
1460    {
1461        value.serialize(self)
1462    }
1463
1464    fn serialize_newtype_variant<T: ?Sized>(
1465        self,
1466        _name: &'static str,
1467        _variant_index: u32,
1468        _variant: &'static str,
1469        _value: &T,
1470    ) -> Result<String, Self::Error>
1471    where
1472        T: ser::Serialize,
1473    {
1474        Err(Error::KeyNotString)
1475    }
1476
1477    fn serialize_seq(self, _len: Option<usize>) -> Result<Self::SerializeSeq, Self::Error> {
1478        Err(Error::KeyNotString)
1479    }
1480
1481    fn serialize_tuple(self, _len: usize) -> Result<Self::SerializeTuple, Self::Error> {
1482        Err(Error::KeyNotString)
1483    }
1484
1485    fn serialize_tuple_struct(
1486        self,
1487        _name: &'static str,
1488        _len: usize,
1489    ) -> Result<Self::SerializeTupleStruct, Self::Error> {
1490        Err(Error::KeyNotString)
1491    }
1492
1493    fn serialize_tuple_variant(
1494        self,
1495        _name: &'static str,
1496        _variant_index: u32,
1497        _variant: &'static str,
1498        _len: usize,
1499    ) -> Result<Self::SerializeTupleVariant, Self::Error> {
1500        Err(Error::KeyNotString)
1501    }
1502
1503    fn serialize_map(self, _len: Option<usize>) -> Result<Self::SerializeMap, Self::Error> {
1504        Err(Error::KeyNotString)
1505    }
1506
1507    fn serialize_struct(
1508        self,
1509        _name: &'static str,
1510        _len: usize,
1511    ) -> Result<Self::SerializeStruct, Self::Error> {
1512        Err(Error::KeyNotString)
1513    }
1514
1515    fn serialize_struct_variant(
1516        self,
1517        _name: &'static str,
1518        _variant_index: u32,
1519        _variant: &'static str,
1520        _len: usize,
1521    ) -> Result<Self::SerializeStructVariant, Self::Error> {
1522        Err(Error::KeyNotString)
1523    }
1524}
1525
1526impl fmt::Display for Error {
1527    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1528        match *self {
1529            Error::UnsupportedType => "unsupported Rust type".fmt(f),
1530            Error::KeyNotString => "map key was not a string".fmt(f),
1531            Error::ArrayMixedType => "arrays cannot have mixed types".fmt(f),
1532            Error::ValueAfterTable => "values must be emitted before tables".fmt(f),
1533            Error::DateInvalid => "a serialized date was invalid".fmt(f),
1534            Error::NumberInvalid => "a serialized number was invalid".fmt(f),
1535            Error::UnsupportedNone => "unsupported None value".fmt(f),
1536            Error::Custom(ref s) => s.fmt(f),
1537            Error::KeyNewline => unreachable!(),
1538            Error::__Nonexhaustive => panic!(),
1539        }
1540    }
1541}
1542
1543impl error::Error for Error {
1544    fn description(&self) -> &str {
1545        match *self {
1546            Error::UnsupportedType => "unsupported Rust type",
1547            Error::KeyNotString => "map key was not a string",
1548            Error::ArrayMixedType => "arrays cannot have mixed types",
1549            Error::ValueAfterTable => "values must be emitted before tables",
1550            Error::DateInvalid => "a serialized date was invalid",
1551            Error::NumberInvalid => "a serialized number was invalid",
1552            Error::UnsupportedNone => "unsupported None value",
1553            Error::Custom(_) => "custom error",
1554            Error::KeyNewline => unreachable!(),
1555            Error::__Nonexhaustive => panic!(),
1556        }
1557    }
1558}
1559
1560impl ser::Error for Error {
1561    fn custom<T: fmt::Display>(msg: T) -> Error {
1562        Error::Custom(msg.to_string())
1563    }
1564}
1565
1566enum Category {
1567    Primitive,
1568    Array,
1569    Table,
1570}
1571
1572/// Convenience function to serialize items in a map in an order valid with
1573/// TOML.
1574///
1575/// TOML carries the restriction that keys in a table must be serialized last if
1576/// their value is a table itself. This isn't always easy to guarantee, so this
1577/// helper can be used like so:
1578///
1579/// ```rust
1580/// # use serde_derive::Serialize;
1581/// # use std::collections::HashMap;
1582/// #[derive(Serialize)]
1583/// struct Manifest {
1584///     package: Package,
1585///     #[serde(serialize_with = "toml::ser::tables_last")]
1586///     dependencies: HashMap<String, Dependency>,
1587/// }
1588/// # type Package = String;
1589/// # type Dependency = String;
1590/// # fn main() {}
1591/// ```
1592pub fn tables_last<'a, I, K, V, S>(data: &'a I, serializer: S) -> Result<S::Ok, S::Error>
1593where
1594    &'a I: IntoIterator<Item = (K, V)>,
1595    K: ser::Serialize,
1596    V: ser::Serialize,
1597    S: ser::Serializer,
1598{
1599    use serde::ser::SerializeMap;
1600
1601    let mut map = serializer.serialize_map(None)?;
1602    for (k, v) in data {
1603        if let Category::Primitive = v.serialize(Categorize::new())? {
1604            map.serialize_entry(&k, &v)?;
1605        }
1606    }
1607    for (k, v) in data {
1608        if let Category::Array = v.serialize(Categorize::new())? {
1609            map.serialize_entry(&k, &v)?;
1610        }
1611    }
1612    for (k, v) in data {
1613        if let Category::Table = v.serialize(Categorize::new())? {
1614            map.serialize_entry(&k, &v)?;
1615        }
1616    }
1617    map.end()
1618}
1619
1620struct Categorize<E>(marker::PhantomData<E>);
1621
1622impl<E> Categorize<E> {
1623    fn new() -> Self {
1624        Categorize(marker::PhantomData)
1625    }
1626}
1627
1628impl<E: ser::Error> ser::Serializer for Categorize<E> {
1629    type Ok = Category;
1630    type Error = E;
1631    type SerializeSeq = Self;
1632    type SerializeTuple = Self;
1633    type SerializeTupleStruct = Self;
1634    type SerializeTupleVariant = Self;
1635    type SerializeMap = Self;
1636    type SerializeStruct = Self;
1637    type SerializeStructVariant = ser::Impossible<Category, E>;
1638
1639    fn serialize_bool(self, _: bool) -> Result<Self::Ok, Self::Error> {
1640        Ok(Category::Primitive)
1641    }
1642
1643    fn serialize_i8(self, _: i8) -> Result<Self::Ok, Self::Error> {
1644        Ok(Category::Primitive)
1645    }
1646
1647    fn serialize_i16(self, _: i16) -> Result<Self::Ok, Self::Error> {
1648        Ok(Category::Primitive)
1649    }
1650
1651    fn serialize_i32(self, _: i32) -> Result<Self::Ok, Self::Error> {
1652        Ok(Category::Primitive)
1653    }
1654
1655    fn serialize_i64(self, _: i64) -> Result<Self::Ok, Self::Error> {
1656        Ok(Category::Primitive)
1657    }
1658
1659    fn serialize_u8(self, _: u8) -> Result<Self::Ok, Self::Error> {
1660        Ok(Category::Primitive)
1661    }
1662
1663    fn serialize_u16(self, _: u16) -> Result<Self::Ok, Self::Error> {
1664        Ok(Category::Primitive)
1665    }
1666
1667    fn serialize_u32(self, _: u32) -> Result<Self::Ok, Self::Error> {
1668        Ok(Category::Primitive)
1669    }
1670
1671    fn serialize_u64(self, _: u64) -> Result<Self::Ok, Self::Error> {
1672        Ok(Category::Primitive)
1673    }
1674
1675    fn serialize_f32(self, _: f32) -> Result<Self::Ok, Self::Error> {
1676        Ok(Category::Primitive)
1677    }
1678
1679    fn serialize_f64(self, _: f64) -> Result<Self::Ok, Self::Error> {
1680        Ok(Category::Primitive)
1681    }
1682
1683    fn serialize_char(self, _: char) -> Result<Self::Ok, Self::Error> {
1684        Ok(Category::Primitive)
1685    }
1686
1687    fn serialize_str(self, _: &str) -> Result<Self::Ok, Self::Error> {
1688        Ok(Category::Primitive)
1689    }
1690
1691    fn serialize_bytes(self, _: &[u8]) -> Result<Self::Ok, Self::Error> {
1692        Ok(Category::Array)
1693    }
1694
1695    fn serialize_none(self) -> Result<Self::Ok, Self::Error> {
1696        Err(ser::Error::custom("unsupported"))
1697    }
1698
1699    fn serialize_some<T: ?Sized + ser::Serialize>(self, v: &T) -> Result<Self::Ok, Self::Error> {
1700        v.serialize(self)
1701    }
1702
1703    fn serialize_unit(self) -> Result<Self::Ok, Self::Error> {
1704        Err(ser::Error::custom("unsupported"))
1705    }
1706
1707    fn serialize_unit_struct(self, _: &'static str) -> Result<Self::Ok, Self::Error> {
1708        Err(ser::Error::custom("unsupported"))
1709    }
1710
1711    fn serialize_unit_variant(
1712        self,
1713        _: &'static str,
1714        _: u32,
1715        _: &'static str,
1716    ) -> Result<Self::Ok, Self::Error> {
1717        Err(ser::Error::custom("unsupported"))
1718    }
1719
1720    fn serialize_newtype_struct<T: ?Sized + ser::Serialize>(
1721        self,
1722        _: &'static str,
1723        v: &T,
1724    ) -> Result<Self::Ok, Self::Error> {
1725        v.serialize(self)
1726    }
1727
1728    fn serialize_newtype_variant<T: ?Sized + ser::Serialize>(
1729        self,
1730        _: &'static str,
1731        _: u32,
1732        _: &'static str,
1733        _: &T,
1734    ) -> Result<Self::Ok, Self::Error> {
1735        Err(ser::Error::custom("unsupported"))
1736    }
1737
1738    fn serialize_seq(self, _: Option<usize>) -> Result<Self, Self::Error> {
1739        Ok(self)
1740    }
1741
1742    fn serialize_tuple(self, _: usize) -> Result<Self::SerializeTuple, Self::Error> {
1743        Ok(self)
1744    }
1745
1746    fn serialize_tuple_struct(
1747        self,
1748        _: &'static str,
1749        _: usize,
1750    ) -> Result<Self::SerializeTupleStruct, Self::Error> {
1751        Ok(self)
1752    }
1753
1754    fn serialize_tuple_variant(
1755        self,
1756        _: &'static str,
1757        _: u32,
1758        _: &'static str,
1759        _: usize,
1760    ) -> Result<Self::SerializeTupleVariant, Self::Error> {
1761        Ok(self)
1762    }
1763
1764    fn serialize_map(self, _: Option<usize>) -> Result<Self, Self::Error> {
1765        Ok(self)
1766    }
1767
1768    fn serialize_struct(self, _: &'static str, _: usize) -> Result<Self, Self::Error> {
1769        Ok(self)
1770    }
1771
1772    fn serialize_struct_variant(
1773        self,
1774        _: &'static str,
1775        _: u32,
1776        _: &'static str,
1777        _: usize,
1778    ) -> Result<Self::SerializeStructVariant, Self::Error> {
1779        Err(ser::Error::custom("unsupported"))
1780    }
1781}
1782
1783impl<E: ser::Error> ser::SerializeSeq for Categorize<E> {
1784    type Ok = Category;
1785    type Error = E;
1786
1787    fn serialize_element<T: ?Sized + ser::Serialize>(&mut self, _: &T) -> Result<(), Self::Error> {
1788        Ok(())
1789    }
1790
1791    fn end(self) -> Result<Self::Ok, Self::Error> {
1792        Ok(Category::Array)
1793    }
1794}
1795
1796impl<E: ser::Error> ser::SerializeTuple for Categorize<E> {
1797    type Ok = Category;
1798    type Error = E;
1799
1800    fn serialize_element<T: ?Sized + ser::Serialize>(&mut self, _: &T) -> Result<(), Self::Error> {
1801        Ok(())
1802    }
1803
1804    fn end(self) -> Result<Self::Ok, Self::Error> {
1805        Ok(Category::Array)
1806    }
1807}
1808
1809impl<E: ser::Error> ser::SerializeTupleVariant for Categorize<E> {
1810    type Ok = Category;
1811    type Error = E;
1812
1813    fn serialize_field<T: ?Sized + ser::Serialize>(&mut self, _: &T) -> Result<(), Self::Error> {
1814        Ok(())
1815    }
1816
1817    fn end(self) -> Result<Self::Ok, Self::Error> {
1818        Ok(Category::Array)
1819    }
1820}
1821
1822impl<E: ser::Error> ser::SerializeTupleStruct for Categorize<E> {
1823    type Ok = Category;
1824    type Error = E;
1825
1826    fn serialize_field<T: ?Sized + ser::Serialize>(&mut self, _: &T) -> Result<(), Self::Error> {
1827        Ok(())
1828    }
1829
1830    fn end(self) -> Result<Self::Ok, Self::Error> {
1831        Ok(Category::Array)
1832    }
1833}
1834
1835impl<E: ser::Error> ser::SerializeMap for Categorize<E> {
1836    type Ok = Category;
1837    type Error = E;
1838
1839    fn serialize_key<T: ?Sized + ser::Serialize>(&mut self, _: &T) -> Result<(), Self::Error> {
1840        Ok(())
1841    }
1842
1843    fn serialize_value<T: ?Sized + ser::Serialize>(&mut self, _: &T) -> Result<(), Self::Error> {
1844        Ok(())
1845    }
1846
1847    fn end(self) -> Result<Self::Ok, Self::Error> {
1848        Ok(Category::Table)
1849    }
1850}
1851
1852impl<E: ser::Error> ser::SerializeStruct for Categorize<E> {
1853    type Ok = Category;
1854    type Error = E;
1855
1856    fn serialize_field<T: ?Sized>(&mut self, _: &'static str, _: &T) -> Result<(), Self::Error>
1857    where
1858        T: ser::Serialize,
1859    {
1860        Ok(())
1861    }
1862
1863    fn end(self) -> Result<Self::Ok, Self::Error> {
1864        Ok(Category::Table)
1865    }
1866}