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