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