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 prev.get().is_none() {
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 // Escape codes are needed if any ascii control
573 // characters are present, including \b \f \r.
574 c if c <= '\u{1f}' || c == '\u{7f}' => can_be_pretty = false,
575 _ => {}
576 }
577 out.push(ch);
578 } else {
579 // the string cannot be represented as pretty,
580 // still check if it should be multiline
581 if ch == '\n' {
582 ty = Type::NewlineTripple;
583 }
584 }
585 }
586 if can_be_pretty && found_singles > 0 && value.ends_with('\'') {
587 // We cannot escape the ending quote so we must use """
588 can_be_pretty = false;
589 }
590 if !can_be_pretty {
591 debug_assert!(ty != Type::OnelineTripple);
592 return Repr::Std(ty);
593 }
594 if found_singles > max_found_singles {
595 max_found_singles = found_singles;
596 }
597 debug_assert!(max_found_singles < 3);
598 if ty == Type::OnelineSingle && max_found_singles >= 1 {
599 // no newlines, but must use ''' because it has ' in it
600 ty = Type::OnelineTripple;
601 }
602 Repr::Literal(out, ty)
603 }
604
605 let repr = if !is_key && self.settings.string.is_some() {
606 match (&self.settings.string, do_pretty(value)) {
607 (&Some(StringSettings { literal: false, .. }), Repr::Literal(_, ty)) => {
608 Repr::Std(ty)
609 }
610 (_, r) => r,
611 }
612 } else {
613 Repr::Std(Type::OnelineSingle)
614 };
615 match repr {
616 Repr::Literal(literal, ty) => {
617 // A pretty string
618 match ty {
619 Type::NewlineTripple => self.dst.push_str("'''\n"),
620 Type::OnelineTripple => self.dst.push_str("'''"),
621 Type::OnelineSingle => self.dst.push('\''),
622 }
623 self.dst.push_str(&literal);
624 match ty {
625 Type::OnelineSingle => self.dst.push('\''),
626 _ => self.dst.push_str("'''"),
627 }
628 }
629 Repr::Std(ty) => {
630 match ty {
631 Type::NewlineTripple => self.dst.push_str("\"\"\"\n"),
632 // note: OnelineTripple can happen if do_pretty wants to do
633 // '''it's one line'''
634 // but settings.string.literal == false
635 Type::OnelineSingle | Type::OnelineTripple => self.dst.push('"'),
636 }
637 for ch in value.chars() {
638 match ch {
639 '\u{8}' => self.dst.push_str("\\b"),
640 '\u{9}' => self.dst.push_str("\\t"),
641 '\u{a}' => match ty {
642 Type::NewlineTripple => self.dst.push('\n'),
643 Type::OnelineSingle => self.dst.push_str("\\n"),
644 _ => unreachable!(),
645 },
646 '\u{c}' => self.dst.push_str("\\f"),
647 '\u{d}' => self.dst.push_str("\\r"),
648 '\u{22}' => self.dst.push_str("\\\""),
649 '\u{5c}' => self.dst.push_str("\\\\"),
650 c if c <= '\u{1f}' || c == '\u{7f}' => {
651 write!(self.dst, "\\u{:04X}", ch as u32).map_err(ser::Error::custom)?;
652 }
653 ch => self.dst.push(ch),
654 }
655 }
656 match ty {
657 Type::NewlineTripple => self.dst.push_str("\"\"\""),
658 Type::OnelineSingle | Type::OnelineTripple => self.dst.push('"'),
659 }
660 }
661 }
662 Ok(())
663 }
664
emit_table_header(&mut self, state: &State<'_>) -> Result<(), Error>665 fn emit_table_header(&mut self, state: &State<'_>) -> Result<(), Error> {
666 let array_of_tables = match *state {
667 State::End => return Ok(()),
668 State::Array { .. } => true,
669 _ => false,
670 };
671
672 // Unlike [..]s, we can't omit [[..]] ancestors, so be sure to emit table
673 // headers for them.
674 let mut p = state;
675 if let State::Array { first, parent, .. } = *state {
676 if first.get() {
677 p = parent;
678 }
679 }
680 while let State::Table { first, parent, .. } = *p {
681 p = parent;
682 if !first.get() {
683 break;
684 }
685 if let State::Array {
686 parent: &State::Table { .. },
687 ..
688 } = *parent
689 {
690 self.emit_table_header(parent)?;
691 break;
692 }
693 }
694
695 match *state {
696 State::Table { first, .. } => {
697 if !first.get() {
698 // Newline if we are a table that is not the first
699 // table in the document.
700 self.dst.push('\n');
701 }
702 }
703 State::Array { parent, first, .. } => {
704 if !first.get() {
705 // Always newline if we are not the first item in the
706 // table-array
707 self.dst.push('\n');
708 } else if let State::Table { first, .. } = *parent {
709 if !first.get() {
710 // Newline if we are not the first item in the document
711 self.dst.push('\n');
712 }
713 }
714 }
715 _ => {}
716 }
717 self.dst.push_str("[");
718 if array_of_tables {
719 self.dst.push_str("[");
720 }
721 self.emit_key_part(state)?;
722 if array_of_tables {
723 self.dst.push_str("]");
724 }
725 self.dst.push_str("]\n");
726 Ok(())
727 }
728
emit_key_part(&mut self, key: &State<'_>) -> Result<bool, Error>729 fn emit_key_part(&mut self, key: &State<'_>) -> Result<bool, Error> {
730 match *key {
731 State::Array { parent, .. } => self.emit_key_part(parent),
732 State::End => Ok(true),
733 State::Table {
734 key,
735 parent,
736 table_emitted,
737 ..
738 } => {
739 table_emitted.set(true);
740 let first = self.emit_key_part(parent)?;
741 if !first {
742 self.dst.push_str(".");
743 }
744 self.escape_key(key)?;
745 Ok(false)
746 }
747 }
748 }
749 }
750
751 macro_rules! serialize_float {
752 ($this:expr, $v:expr) => {{
753 $this.emit_key(ArrayState::Started)?;
754 if ($v.is_nan() || $v == 0.0) && $v.is_sign_negative() {
755 write!($this.dst, "-").map_err(ser::Error::custom)?;
756 }
757 if $v.is_nan() {
758 write!($this.dst, "nan").map_err(ser::Error::custom)?;
759 } else {
760 write!($this.dst, "{}", $v).map_err(ser::Error::custom)?;
761 }
762 if $v % 1.0 == 0.0 {
763 write!($this.dst, ".0").map_err(ser::Error::custom)?;
764 }
765 if let State::Table { .. } = $this.state {
766 $this.dst.push_str("\n");
767 }
768 return Ok(());
769 }};
770 }
771
772 impl<'a, 'b> ser::Serializer for &'b mut Serializer<'a> {
773 type Ok = ();
774 type Error = Error;
775 type SerializeSeq = SerializeSeq<'a, 'b>;
776 type SerializeTuple = SerializeSeq<'a, 'b>;
777 type SerializeTupleStruct = SerializeSeq<'a, 'b>;
778 type SerializeTupleVariant = SerializeSeq<'a, 'b>;
779 type SerializeMap = SerializeTable<'a, 'b>;
780 type SerializeStruct = SerializeTable<'a, 'b>;
781 type SerializeStructVariant = ser::Impossible<(), Error>;
782
serialize_bool(self, v: bool) -> Result<(), Self::Error>783 fn serialize_bool(self, v: bool) -> Result<(), Self::Error> {
784 self.display(v, ArrayState::Started)
785 }
786
serialize_i8(self, v: i8) -> Result<(), Self::Error>787 fn serialize_i8(self, v: i8) -> Result<(), Self::Error> {
788 self.display(v, ArrayState::Started)
789 }
790
serialize_i16(self, v: i16) -> Result<(), Self::Error>791 fn serialize_i16(self, v: i16) -> Result<(), Self::Error> {
792 self.display(v, ArrayState::Started)
793 }
794
serialize_i32(self, v: i32) -> Result<(), Self::Error>795 fn serialize_i32(self, v: i32) -> Result<(), Self::Error> {
796 self.display(v, ArrayState::Started)
797 }
798
serialize_i64(self, v: i64) -> Result<(), Self::Error>799 fn serialize_i64(self, v: i64) -> Result<(), Self::Error> {
800 self.display(v, ArrayState::Started)
801 }
802
serialize_u8(self, v: u8) -> Result<(), Self::Error>803 fn serialize_u8(self, v: u8) -> Result<(), Self::Error> {
804 self.display(v, ArrayState::Started)
805 }
806
serialize_u16(self, v: u16) -> Result<(), Self::Error>807 fn serialize_u16(self, v: u16) -> Result<(), Self::Error> {
808 self.display(v, ArrayState::Started)
809 }
810
serialize_u32(self, v: u32) -> Result<(), Self::Error>811 fn serialize_u32(self, v: u32) -> Result<(), Self::Error> {
812 self.display(v, ArrayState::Started)
813 }
814
serialize_u64(self, v: u64) -> Result<(), Self::Error>815 fn serialize_u64(self, v: u64) -> Result<(), Self::Error> {
816 self.display(v, ArrayState::Started)
817 }
818
serialize_f32(self, v: f32) -> Result<(), Self::Error>819 fn serialize_f32(self, v: f32) -> Result<(), Self::Error> {
820 serialize_float!(self, v)
821 }
822
serialize_f64(self, v: f64) -> Result<(), Self::Error>823 fn serialize_f64(self, v: f64) -> Result<(), Self::Error> {
824 serialize_float!(self, v)
825 }
826
serialize_char(self, v: char) -> Result<(), Self::Error>827 fn serialize_char(self, v: char) -> Result<(), Self::Error> {
828 let mut buf = [0; 4];
829 self.serialize_str(v.encode_utf8(&mut buf))
830 }
831
serialize_str(self, value: &str) -> Result<(), Self::Error>832 fn serialize_str(self, value: &str) -> Result<(), Self::Error> {
833 self.emit_key(ArrayState::Started)?;
834 self.emit_str(value, false)?;
835 if let State::Table { .. } = self.state {
836 self.dst.push_str("\n");
837 }
838 Ok(())
839 }
840
serialize_bytes(self, value: &[u8]) -> Result<(), Self::Error>841 fn serialize_bytes(self, value: &[u8]) -> Result<(), Self::Error> {
842 use serde::ser::Serialize;
843 value.serialize(self)
844 }
845
serialize_none(self) -> Result<(), Self::Error>846 fn serialize_none(self) -> Result<(), Self::Error> {
847 Err(Error::UnsupportedNone)
848 }
849
serialize_some<T: ?Sized>(self, value: &T) -> Result<(), Self::Error> where T: ser::Serialize,850 fn serialize_some<T: ?Sized>(self, value: &T) -> Result<(), Self::Error>
851 where
852 T: ser::Serialize,
853 {
854 value.serialize(self)
855 }
856
serialize_unit(self) -> Result<(), Self::Error>857 fn serialize_unit(self) -> Result<(), Self::Error> {
858 Err(Error::UnsupportedType)
859 }
860
serialize_unit_struct(self, _name: &'static str) -> Result<(), Self::Error>861 fn serialize_unit_struct(self, _name: &'static str) -> Result<(), Self::Error> {
862 Err(Error::UnsupportedType)
863 }
864
serialize_unit_variant( self, _name: &'static str, _variant_index: u32, variant: &'static str, ) -> Result<(), Self::Error>865 fn serialize_unit_variant(
866 self,
867 _name: &'static str,
868 _variant_index: u32,
869 variant: &'static str,
870 ) -> Result<(), Self::Error> {
871 self.serialize_str(variant)
872 }
873
serialize_newtype_struct<T: ?Sized>( self, _name: &'static str, value: &T, ) -> Result<(), Self::Error> where T: ser::Serialize,874 fn serialize_newtype_struct<T: ?Sized>(
875 self,
876 _name: &'static str,
877 value: &T,
878 ) -> Result<(), Self::Error>
879 where
880 T: ser::Serialize,
881 {
882 value.serialize(self)
883 }
884
serialize_newtype_variant<T: ?Sized>( self, _name: &'static str, _variant_index: u32, _variant: &'static str, _value: &T, ) -> Result<(), Self::Error> where T: ser::Serialize,885 fn serialize_newtype_variant<T: ?Sized>(
886 self,
887 _name: &'static str,
888 _variant_index: u32,
889 _variant: &'static str,
890 _value: &T,
891 ) -> Result<(), Self::Error>
892 where
893 T: ser::Serialize,
894 {
895 Err(Error::UnsupportedType)
896 }
897
serialize_seq(self, len: Option<usize>) -> Result<Self::SerializeSeq, Self::Error>898 fn serialize_seq(self, len: Option<usize>) -> Result<Self::SerializeSeq, Self::Error> {
899 self.array_type(ArrayState::Started)?;
900 Ok(SerializeSeq {
901 ser: self,
902 first: Cell::new(true),
903 type_: Cell::new(None),
904 len,
905 })
906 }
907
serialize_tuple(self, len: usize) -> Result<Self::SerializeTuple, Self::Error>908 fn serialize_tuple(self, len: usize) -> Result<Self::SerializeTuple, Self::Error> {
909 self.serialize_seq(Some(len))
910 }
911
serialize_tuple_struct( self, _name: &'static str, len: usize, ) -> Result<Self::SerializeTupleStruct, Self::Error>912 fn serialize_tuple_struct(
913 self,
914 _name: &'static str,
915 len: usize,
916 ) -> Result<Self::SerializeTupleStruct, Self::Error> {
917 self.serialize_seq(Some(len))
918 }
919
serialize_tuple_variant( self, _name: &'static str, _variant_index: u32, _variant: &'static str, len: usize, ) -> Result<Self::SerializeTupleVariant, Self::Error>920 fn serialize_tuple_variant(
921 self,
922 _name: &'static str,
923 _variant_index: u32,
924 _variant: &'static str,
925 len: usize,
926 ) -> Result<Self::SerializeTupleVariant, Self::Error> {
927 self.serialize_seq(Some(len))
928 }
929
serialize_map(self, _len: Option<usize>) -> Result<Self::SerializeMap, Self::Error>930 fn serialize_map(self, _len: Option<usize>) -> Result<Self::SerializeMap, Self::Error> {
931 self.array_type(ArrayState::StartedAsATable)?;
932 Ok(SerializeTable::Table {
933 ser: self,
934 key: String::new(),
935 first: Cell::new(true),
936 table_emitted: Cell::new(false),
937 })
938 }
939
serialize_struct( self, name: &'static str, _len: usize, ) -> Result<Self::SerializeStruct, Self::Error>940 fn serialize_struct(
941 self,
942 name: &'static str,
943 _len: usize,
944 ) -> Result<Self::SerializeStruct, Self::Error> {
945 if name == datetime::NAME {
946 self.array_type(ArrayState::Started)?;
947 Ok(SerializeTable::Datetime(self))
948 } else {
949 self.array_type(ArrayState::StartedAsATable)?;
950 Ok(SerializeTable::Table {
951 ser: self,
952 key: String::new(),
953 first: Cell::new(true),
954 table_emitted: Cell::new(false),
955 })
956 }
957 }
958
serialize_struct_variant( self, _name: &'static str, _variant_index: u32, _variant: &'static str, _len: usize, ) -> Result<Self::SerializeStructVariant, Self::Error>959 fn serialize_struct_variant(
960 self,
961 _name: &'static str,
962 _variant_index: u32,
963 _variant: &'static str,
964 _len: usize,
965 ) -> Result<Self::SerializeStructVariant, Self::Error> {
966 Err(Error::UnsupportedType)
967 }
968 }
969
970 impl<'a, 'b> ser::SerializeSeq for SerializeSeq<'a, 'b> {
971 type Ok = ();
972 type Error = Error;
973
serialize_element<T: ?Sized>(&mut self, value: &T) -> Result<(), Error> where T: ser::Serialize,974 fn serialize_element<T: ?Sized>(&mut self, value: &T) -> Result<(), Error>
975 where
976 T: ser::Serialize,
977 {
978 value.serialize(&mut Serializer {
979 dst: &mut *self.ser.dst,
980 state: State::Array {
981 parent: &self.ser.state,
982 first: &self.first,
983 type_: &self.type_,
984 len: self.len,
985 },
986 settings: self.ser.settings.clone(),
987 })?;
988 self.first.set(false);
989 Ok(())
990 }
991
end(self) -> Result<(), Error>992 fn end(self) -> Result<(), Error> {
993 match self.type_.get() {
994 Some(ArrayState::StartedAsATable) => return Ok(()),
995 Some(ArrayState::Started) => match (self.len, &self.ser.settings.array) {
996 (Some(0..=1), _) | (_, &None) => {
997 self.ser.dst.push_str("]");
998 }
999 (_, &Some(ref a)) => {
1000 if a.trailing_comma {
1001 self.ser.dst.push_str(",");
1002 }
1003 self.ser.dst.push_str("\n]");
1004 }
1005 },
1006 None => {
1007 assert!(self.first.get());
1008 self.ser.emit_key(ArrayState::Started)?;
1009 self.ser.dst.push_str("[]")
1010 }
1011 }
1012 if let State::Table { .. } = self.ser.state {
1013 self.ser.dst.push_str("\n");
1014 }
1015 Ok(())
1016 }
1017 }
1018
1019 impl<'a, 'b> ser::SerializeTuple for SerializeSeq<'a, 'b> {
1020 type Ok = ();
1021 type Error = Error;
1022
serialize_element<T: ?Sized>(&mut self, value: &T) -> Result<(), Error> where T: ser::Serialize,1023 fn serialize_element<T: ?Sized>(&mut self, value: &T) -> Result<(), Error>
1024 where
1025 T: ser::Serialize,
1026 {
1027 ser::SerializeSeq::serialize_element(self, value)
1028 }
1029
end(self) -> Result<(), Error>1030 fn end(self) -> Result<(), Error> {
1031 ser::SerializeSeq::end(self)
1032 }
1033 }
1034
1035 impl<'a, 'b> ser::SerializeTupleVariant for SerializeSeq<'a, 'b> {
1036 type Ok = ();
1037 type Error = Error;
1038
serialize_field<T: ?Sized>(&mut self, value: &T) -> Result<(), Error> where T: ser::Serialize,1039 fn serialize_field<T: ?Sized>(&mut self, value: &T) -> Result<(), Error>
1040 where
1041 T: ser::Serialize,
1042 {
1043 ser::SerializeSeq::serialize_element(self, value)
1044 }
1045
end(self) -> Result<(), Error>1046 fn end(self) -> Result<(), Error> {
1047 ser::SerializeSeq::end(self)
1048 }
1049 }
1050
1051 impl<'a, 'b> ser::SerializeTupleStruct for SerializeSeq<'a, 'b> {
1052 type Ok = ();
1053 type Error = Error;
1054
serialize_field<T: ?Sized>(&mut self, value: &T) -> Result<(), Error> where T: ser::Serialize,1055 fn serialize_field<T: ?Sized>(&mut self, value: &T) -> Result<(), Error>
1056 where
1057 T: ser::Serialize,
1058 {
1059 ser::SerializeSeq::serialize_element(self, value)
1060 }
1061
end(self) -> Result<(), Error>1062 fn end(self) -> Result<(), Error> {
1063 ser::SerializeSeq::end(self)
1064 }
1065 }
1066
1067 impl<'a, 'b> ser::SerializeMap for SerializeTable<'a, 'b> {
1068 type Ok = ();
1069 type Error = Error;
1070
serialize_key<T: ?Sized>(&mut self, input: &T) -> Result<(), Error> where T: ser::Serialize,1071 fn serialize_key<T: ?Sized>(&mut self, input: &T) -> Result<(), Error>
1072 where
1073 T: ser::Serialize,
1074 {
1075 match *self {
1076 SerializeTable::Datetime(_) => panic!(), // shouldn't be possible
1077 SerializeTable::Table { ref mut key, .. } => {
1078 key.truncate(0);
1079 *key = input.serialize(StringExtractor)?;
1080 }
1081 }
1082 Ok(())
1083 }
1084
serialize_value<T: ?Sized>(&mut self, value: &T) -> Result<(), Error> where T: ser::Serialize,1085 fn serialize_value<T: ?Sized>(&mut self, value: &T) -> Result<(), Error>
1086 where
1087 T: ser::Serialize,
1088 {
1089 match *self {
1090 SerializeTable::Datetime(_) => panic!(), // shouldn't be possible
1091 SerializeTable::Table {
1092 ref mut ser,
1093 ref key,
1094 ref first,
1095 ref table_emitted,
1096 ..
1097 } => {
1098 let res = value.serialize(&mut Serializer {
1099 dst: &mut *ser.dst,
1100 state: State::Table {
1101 key,
1102 parent: &ser.state,
1103 first,
1104 table_emitted,
1105 },
1106 settings: ser.settings.clone(),
1107 });
1108 match res {
1109 Ok(()) => first.set(false),
1110 Err(Error::UnsupportedNone) => {}
1111 Err(e) => return Err(e),
1112 }
1113 }
1114 }
1115 Ok(())
1116 }
1117
end(self) -> Result<(), Error>1118 fn end(self) -> Result<(), Error> {
1119 match self {
1120 SerializeTable::Datetime(_) => panic!(), // shouldn't be possible
1121 SerializeTable::Table { ser, first, .. } => {
1122 if first.get() {
1123 let state = ser.state.clone();
1124 ser.emit_table_header(&state)?;
1125 }
1126 }
1127 }
1128 Ok(())
1129 }
1130 }
1131
1132 impl<'a, 'b> ser::SerializeStruct for SerializeTable<'a, 'b> {
1133 type Ok = ();
1134 type Error = Error;
1135
serialize_field<T: ?Sized>(&mut self, key: &'static str, value: &T) -> Result<(), Error> where T: ser::Serialize,1136 fn serialize_field<T: ?Sized>(&mut self, key: &'static str, value: &T) -> Result<(), Error>
1137 where
1138 T: ser::Serialize,
1139 {
1140 match *self {
1141 SerializeTable::Datetime(ref mut ser) => {
1142 if key == datetime::FIELD {
1143 value.serialize(DateStrEmitter(&mut *ser))?;
1144 } else {
1145 return Err(Error::DateInvalid);
1146 }
1147 }
1148 SerializeTable::Table {
1149 ref mut ser,
1150 ref first,
1151 ref table_emitted,
1152 ..
1153 } => {
1154 let res = value.serialize(&mut Serializer {
1155 dst: &mut *ser.dst,
1156 state: State::Table {
1157 key,
1158 parent: &ser.state,
1159 first,
1160 table_emitted,
1161 },
1162 settings: ser.settings.clone(),
1163 });
1164 match res {
1165 Ok(()) => first.set(false),
1166 Err(Error::UnsupportedNone) => {}
1167 Err(e) => return Err(e),
1168 }
1169 }
1170 }
1171 Ok(())
1172 }
1173
end(self) -> Result<(), Error>1174 fn end(self) -> Result<(), Error> {
1175 match self {
1176 SerializeTable::Datetime(_) => {}
1177 SerializeTable::Table { ser, first, .. } => {
1178 if first.get() {
1179 let state = ser.state.clone();
1180 ser.emit_table_header(&state)?;
1181 }
1182 }
1183 }
1184 Ok(())
1185 }
1186 }
1187
1188 struct DateStrEmitter<'a, 'b>(&'b mut Serializer<'a>);
1189
1190 impl<'a, 'b> ser::Serializer for DateStrEmitter<'a, 'b> {
1191 type Ok = ();
1192 type Error = Error;
1193 type SerializeSeq = ser::Impossible<(), Error>;
1194 type SerializeTuple = ser::Impossible<(), Error>;
1195 type SerializeTupleStruct = ser::Impossible<(), Error>;
1196 type SerializeTupleVariant = ser::Impossible<(), Error>;
1197 type SerializeMap = ser::Impossible<(), Error>;
1198 type SerializeStruct = ser::Impossible<(), Error>;
1199 type SerializeStructVariant = ser::Impossible<(), Error>;
1200
serialize_bool(self, _v: bool) -> Result<(), Self::Error>1201 fn serialize_bool(self, _v: bool) -> Result<(), Self::Error> {
1202 Err(Error::DateInvalid)
1203 }
1204
serialize_i8(self, _v: i8) -> Result<(), Self::Error>1205 fn serialize_i8(self, _v: i8) -> Result<(), Self::Error> {
1206 Err(Error::DateInvalid)
1207 }
1208
serialize_i16(self, _v: i16) -> Result<(), Self::Error>1209 fn serialize_i16(self, _v: i16) -> Result<(), Self::Error> {
1210 Err(Error::DateInvalid)
1211 }
1212
serialize_i32(self, _v: i32) -> Result<(), Self::Error>1213 fn serialize_i32(self, _v: i32) -> Result<(), Self::Error> {
1214 Err(Error::DateInvalid)
1215 }
1216
serialize_i64(self, _v: i64) -> Result<(), Self::Error>1217 fn serialize_i64(self, _v: i64) -> Result<(), Self::Error> {
1218 Err(Error::DateInvalid)
1219 }
1220
serialize_u8(self, _v: u8) -> Result<(), Self::Error>1221 fn serialize_u8(self, _v: u8) -> Result<(), Self::Error> {
1222 Err(Error::DateInvalid)
1223 }
1224
serialize_u16(self, _v: u16) -> Result<(), Self::Error>1225 fn serialize_u16(self, _v: u16) -> Result<(), Self::Error> {
1226 Err(Error::DateInvalid)
1227 }
1228
serialize_u32(self, _v: u32) -> Result<(), Self::Error>1229 fn serialize_u32(self, _v: u32) -> Result<(), Self::Error> {
1230 Err(Error::DateInvalid)
1231 }
1232
serialize_u64(self, _v: u64) -> Result<(), Self::Error>1233 fn serialize_u64(self, _v: u64) -> Result<(), Self::Error> {
1234 Err(Error::DateInvalid)
1235 }
1236
serialize_f32(self, _v: f32) -> Result<(), Self::Error>1237 fn serialize_f32(self, _v: f32) -> Result<(), Self::Error> {
1238 Err(Error::DateInvalid)
1239 }
1240
serialize_f64(self, _v: f64) -> Result<(), Self::Error>1241 fn serialize_f64(self, _v: f64) -> Result<(), Self::Error> {
1242 Err(Error::DateInvalid)
1243 }
1244
serialize_char(self, _v: char) -> Result<(), Self::Error>1245 fn serialize_char(self, _v: char) -> Result<(), Self::Error> {
1246 Err(Error::DateInvalid)
1247 }
1248
serialize_str(self, value: &str) -> Result<(), Self::Error>1249 fn serialize_str(self, value: &str) -> Result<(), Self::Error> {
1250 self.0.display(value, ArrayState::Started)?;
1251 Ok(())
1252 }
1253
serialize_bytes(self, _value: &[u8]) -> Result<(), Self::Error>1254 fn serialize_bytes(self, _value: &[u8]) -> Result<(), Self::Error> {
1255 Err(Error::DateInvalid)
1256 }
1257
serialize_none(self) -> Result<(), Self::Error>1258 fn serialize_none(self) -> Result<(), Self::Error> {
1259 Err(Error::DateInvalid)
1260 }
1261
serialize_some<T: ?Sized>(self, _value: &T) -> Result<(), Self::Error> where T: ser::Serialize,1262 fn serialize_some<T: ?Sized>(self, _value: &T) -> Result<(), Self::Error>
1263 where
1264 T: ser::Serialize,
1265 {
1266 Err(Error::DateInvalid)
1267 }
1268
serialize_unit(self) -> Result<(), Self::Error>1269 fn serialize_unit(self) -> Result<(), Self::Error> {
1270 Err(Error::DateInvalid)
1271 }
1272
serialize_unit_struct(self, _name: &'static str) -> Result<(), Self::Error>1273 fn serialize_unit_struct(self, _name: &'static str) -> Result<(), Self::Error> {
1274 Err(Error::DateInvalid)
1275 }
1276
serialize_unit_variant( self, _name: &'static str, _variant_index: u32, _variant: &'static str, ) -> Result<(), Self::Error>1277 fn serialize_unit_variant(
1278 self,
1279 _name: &'static str,
1280 _variant_index: u32,
1281 _variant: &'static str,
1282 ) -> Result<(), Self::Error> {
1283 Err(Error::DateInvalid)
1284 }
1285
serialize_newtype_struct<T: ?Sized>( self, _name: &'static str, _value: &T, ) -> Result<(), Self::Error> where T: ser::Serialize,1286 fn serialize_newtype_struct<T: ?Sized>(
1287 self,
1288 _name: &'static str,
1289 _value: &T,
1290 ) -> Result<(), Self::Error>
1291 where
1292 T: ser::Serialize,
1293 {
1294 Err(Error::DateInvalid)
1295 }
1296
serialize_newtype_variant<T: ?Sized>( self, _name: &'static str, _variant_index: u32, _variant: &'static str, _value: &T, ) -> Result<(), Self::Error> where T: ser::Serialize,1297 fn serialize_newtype_variant<T: ?Sized>(
1298 self,
1299 _name: &'static str,
1300 _variant_index: u32,
1301 _variant: &'static str,
1302 _value: &T,
1303 ) -> Result<(), Self::Error>
1304 where
1305 T: ser::Serialize,
1306 {
1307 Err(Error::DateInvalid)
1308 }
1309
serialize_seq(self, _len: Option<usize>) -> Result<Self::SerializeSeq, Self::Error>1310 fn serialize_seq(self, _len: Option<usize>) -> Result<Self::SerializeSeq, Self::Error> {
1311 Err(Error::DateInvalid)
1312 }
1313
serialize_tuple(self, _len: usize) -> Result<Self::SerializeTuple, Self::Error>1314 fn serialize_tuple(self, _len: usize) -> Result<Self::SerializeTuple, Self::Error> {
1315 Err(Error::DateInvalid)
1316 }
1317
serialize_tuple_struct( self, _name: &'static str, _len: usize, ) -> Result<Self::SerializeTupleStruct, Self::Error>1318 fn serialize_tuple_struct(
1319 self,
1320 _name: &'static str,
1321 _len: usize,
1322 ) -> Result<Self::SerializeTupleStruct, Self::Error> {
1323 Err(Error::DateInvalid)
1324 }
1325
serialize_tuple_variant( self, _name: &'static str, _variant_index: u32, _variant: &'static str, _len: usize, ) -> Result<Self::SerializeTupleVariant, Self::Error>1326 fn serialize_tuple_variant(
1327 self,
1328 _name: &'static str,
1329 _variant_index: u32,
1330 _variant: &'static str,
1331 _len: usize,
1332 ) -> Result<Self::SerializeTupleVariant, Self::Error> {
1333 Err(Error::DateInvalid)
1334 }
1335
serialize_map(self, _len: Option<usize>) -> Result<Self::SerializeMap, Self::Error>1336 fn serialize_map(self, _len: Option<usize>) -> Result<Self::SerializeMap, Self::Error> {
1337 Err(Error::DateInvalid)
1338 }
1339
serialize_struct( self, _name: &'static str, _len: usize, ) -> Result<Self::SerializeStruct, Self::Error>1340 fn serialize_struct(
1341 self,
1342 _name: &'static str,
1343 _len: usize,
1344 ) -> Result<Self::SerializeStruct, Self::Error> {
1345 Err(Error::DateInvalid)
1346 }
1347
serialize_struct_variant( self, _name: &'static str, _variant_index: u32, _variant: &'static str, _len: usize, ) -> Result<Self::SerializeStructVariant, Self::Error>1348 fn serialize_struct_variant(
1349 self,
1350 _name: &'static str,
1351 _variant_index: u32,
1352 _variant: &'static str,
1353 _len: usize,
1354 ) -> Result<Self::SerializeStructVariant, Self::Error> {
1355 Err(Error::DateInvalid)
1356 }
1357 }
1358
1359 struct StringExtractor;
1360
1361 impl ser::Serializer for StringExtractor {
1362 type Ok = String;
1363 type Error = Error;
1364 type SerializeSeq = ser::Impossible<String, Error>;
1365 type SerializeTuple = ser::Impossible<String, Error>;
1366 type SerializeTupleStruct = ser::Impossible<String, Error>;
1367 type SerializeTupleVariant = ser::Impossible<String, Error>;
1368 type SerializeMap = ser::Impossible<String, Error>;
1369 type SerializeStruct = ser::Impossible<String, Error>;
1370 type SerializeStructVariant = ser::Impossible<String, Error>;
1371
serialize_bool(self, _v: bool) -> Result<String, Self::Error>1372 fn serialize_bool(self, _v: bool) -> Result<String, Self::Error> {
1373 Err(Error::KeyNotString)
1374 }
1375
serialize_i8(self, _v: i8) -> Result<String, Self::Error>1376 fn serialize_i8(self, _v: i8) -> Result<String, Self::Error> {
1377 Err(Error::KeyNotString)
1378 }
1379
serialize_i16(self, _v: i16) -> Result<String, Self::Error>1380 fn serialize_i16(self, _v: i16) -> Result<String, Self::Error> {
1381 Err(Error::KeyNotString)
1382 }
1383
serialize_i32(self, _v: i32) -> Result<String, Self::Error>1384 fn serialize_i32(self, _v: i32) -> Result<String, Self::Error> {
1385 Err(Error::KeyNotString)
1386 }
1387
serialize_i64(self, _v: i64) -> Result<String, Self::Error>1388 fn serialize_i64(self, _v: i64) -> Result<String, Self::Error> {
1389 Err(Error::KeyNotString)
1390 }
1391
serialize_u8(self, _v: u8) -> Result<String, Self::Error>1392 fn serialize_u8(self, _v: u8) -> Result<String, Self::Error> {
1393 Err(Error::KeyNotString)
1394 }
1395
serialize_u16(self, _v: u16) -> Result<String, Self::Error>1396 fn serialize_u16(self, _v: u16) -> Result<String, Self::Error> {
1397 Err(Error::KeyNotString)
1398 }
1399
serialize_u32(self, _v: u32) -> Result<String, Self::Error>1400 fn serialize_u32(self, _v: u32) -> Result<String, Self::Error> {
1401 Err(Error::KeyNotString)
1402 }
1403
serialize_u64(self, _v: u64) -> Result<String, Self::Error>1404 fn serialize_u64(self, _v: u64) -> Result<String, Self::Error> {
1405 Err(Error::KeyNotString)
1406 }
1407
serialize_f32(self, _v: f32) -> Result<String, Self::Error>1408 fn serialize_f32(self, _v: f32) -> Result<String, Self::Error> {
1409 Err(Error::KeyNotString)
1410 }
1411
serialize_f64(self, _v: f64) -> Result<String, Self::Error>1412 fn serialize_f64(self, _v: f64) -> Result<String, Self::Error> {
1413 Err(Error::KeyNotString)
1414 }
1415
serialize_char(self, _v: char) -> Result<String, Self::Error>1416 fn serialize_char(self, _v: char) -> Result<String, Self::Error> {
1417 Err(Error::KeyNotString)
1418 }
1419
serialize_str(self, value: &str) -> Result<String, Self::Error>1420 fn serialize_str(self, value: &str) -> Result<String, Self::Error> {
1421 Ok(value.to_string())
1422 }
1423
serialize_bytes(self, _value: &[u8]) -> Result<String, Self::Error>1424 fn serialize_bytes(self, _value: &[u8]) -> Result<String, Self::Error> {
1425 Err(Error::KeyNotString)
1426 }
1427
serialize_none(self) -> Result<String, Self::Error>1428 fn serialize_none(self) -> Result<String, Self::Error> {
1429 Err(Error::KeyNotString)
1430 }
1431
serialize_some<T: ?Sized>(self, _value: &T) -> Result<String, Self::Error> where T: ser::Serialize,1432 fn serialize_some<T: ?Sized>(self, _value: &T) -> Result<String, Self::Error>
1433 where
1434 T: ser::Serialize,
1435 {
1436 Err(Error::KeyNotString)
1437 }
1438
serialize_unit(self) -> Result<String, Self::Error>1439 fn serialize_unit(self) -> Result<String, Self::Error> {
1440 Err(Error::KeyNotString)
1441 }
1442
serialize_unit_struct(self, _name: &'static str) -> Result<String, Self::Error>1443 fn serialize_unit_struct(self, _name: &'static str) -> Result<String, Self::Error> {
1444 Err(Error::KeyNotString)
1445 }
1446
serialize_unit_variant( self, _name: &'static str, _variant_index: u32, _variant: &'static str, ) -> Result<String, Self::Error>1447 fn serialize_unit_variant(
1448 self,
1449 _name: &'static str,
1450 _variant_index: u32,
1451 _variant: &'static str,
1452 ) -> Result<String, Self::Error> {
1453 Err(Error::KeyNotString)
1454 }
1455
serialize_newtype_struct<T: ?Sized>( self, _name: &'static str, value: &T, ) -> Result<String, Self::Error> where T: ser::Serialize,1456 fn serialize_newtype_struct<T: ?Sized>(
1457 self,
1458 _name: &'static str,
1459 value: &T,
1460 ) -> Result<String, Self::Error>
1461 where
1462 T: ser::Serialize,
1463 {
1464 value.serialize(self)
1465 }
1466
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,1467 fn serialize_newtype_variant<T: ?Sized>(
1468 self,
1469 _name: &'static str,
1470 _variant_index: u32,
1471 _variant: &'static str,
1472 _value: &T,
1473 ) -> Result<String, Self::Error>
1474 where
1475 T: ser::Serialize,
1476 {
1477 Err(Error::KeyNotString)
1478 }
1479
serialize_seq(self, _len: Option<usize>) -> Result<Self::SerializeSeq, Self::Error>1480 fn serialize_seq(self, _len: Option<usize>) -> Result<Self::SerializeSeq, Self::Error> {
1481 Err(Error::KeyNotString)
1482 }
1483
serialize_tuple(self, _len: usize) -> Result<Self::SerializeTuple, Self::Error>1484 fn serialize_tuple(self, _len: usize) -> Result<Self::SerializeTuple, Self::Error> {
1485 Err(Error::KeyNotString)
1486 }
1487
serialize_tuple_struct( self, _name: &'static str, _len: usize, ) -> Result<Self::SerializeTupleStruct, Self::Error>1488 fn serialize_tuple_struct(
1489 self,
1490 _name: &'static str,
1491 _len: usize,
1492 ) -> Result<Self::SerializeTupleStruct, Self::Error> {
1493 Err(Error::KeyNotString)
1494 }
1495
serialize_tuple_variant( self, _name: &'static str, _variant_index: u32, _variant: &'static str, _len: usize, ) -> Result<Self::SerializeTupleVariant, Self::Error>1496 fn serialize_tuple_variant(
1497 self,
1498 _name: &'static str,
1499 _variant_index: u32,
1500 _variant: &'static str,
1501 _len: usize,
1502 ) -> Result<Self::SerializeTupleVariant, Self::Error> {
1503 Err(Error::KeyNotString)
1504 }
1505
serialize_map(self, _len: Option<usize>) -> Result<Self::SerializeMap, Self::Error>1506 fn serialize_map(self, _len: Option<usize>) -> Result<Self::SerializeMap, Self::Error> {
1507 Err(Error::KeyNotString)
1508 }
1509
serialize_struct( self, _name: &'static str, _len: usize, ) -> Result<Self::SerializeStruct, Self::Error>1510 fn serialize_struct(
1511 self,
1512 _name: &'static str,
1513 _len: usize,
1514 ) -> Result<Self::SerializeStruct, Self::Error> {
1515 Err(Error::KeyNotString)
1516 }
1517
serialize_struct_variant( self, _name: &'static str, _variant_index: u32, _variant: &'static str, _len: usize, ) -> Result<Self::SerializeStructVariant, Self::Error>1518 fn serialize_struct_variant(
1519 self,
1520 _name: &'static str,
1521 _variant_index: u32,
1522 _variant: &'static str,
1523 _len: usize,
1524 ) -> Result<Self::SerializeStructVariant, Self::Error> {
1525 Err(Error::KeyNotString)
1526 }
1527 }
1528
1529 impl fmt::Display for Error {
fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result1530 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1531 match *self {
1532 Error::UnsupportedType => "unsupported Rust type".fmt(f),
1533 Error::KeyNotString => "map key was not a string".fmt(f),
1534 Error::ValueAfterTable => "values must be emitted before tables".fmt(f),
1535 Error::DateInvalid => "a serialized date was invalid".fmt(f),
1536 Error::NumberInvalid => "a serialized number was invalid".fmt(f),
1537 Error::UnsupportedNone => "unsupported None value".fmt(f),
1538 Error::Custom(ref s) => s.fmt(f),
1539 Error::KeyNewline => unreachable!(),
1540 Error::ArrayMixedType => unreachable!(),
1541 Error::__Nonexhaustive => panic!(),
1542 }
1543 }
1544 }
1545
1546 impl error::Error for Error {}
1547
1548 impl ser::Error for Error {
custom<T: fmt::Display>(msg: T) -> Error1549 fn custom<T: fmt::Display>(msg: T) -> Error {
1550 Error::Custom(msg.to_string())
1551 }
1552 }
1553
1554 enum Category {
1555 Primitive,
1556 Array,
1557 Table,
1558 }
1559
1560 /// Convenience function to serialize items in a map in an order valid with
1561 /// TOML.
1562 ///
1563 /// TOML carries the restriction that keys in a table must be serialized last if
1564 /// their value is a table itself. This isn't always easy to guarantee, so this
1565 /// helper can be used like so:
1566 ///
1567 /// ```rust
1568 /// # use serde_derive::Serialize;
1569 /// # use std::collections::HashMap;
1570 /// #[derive(Serialize)]
1571 /// struct Manifest {
1572 /// package: Package,
1573 /// #[serde(serialize_with = "toml::ser::tables_last")]
1574 /// dependencies: HashMap<String, Dependency>,
1575 /// }
1576 /// # type Package = String;
1577 /// # type Dependency = String;
1578 /// # fn main() {}
1579 /// ```
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,1580 pub fn tables_last<'a, I, K, V, S>(data: &'a I, serializer: S) -> Result<S::Ok, S::Error>
1581 where
1582 &'a I: IntoIterator<Item = (K, V)>,
1583 K: ser::Serialize,
1584 V: ser::Serialize,
1585 S: ser::Serializer,
1586 {
1587 use serde::ser::SerializeMap;
1588
1589 let mut map = serializer.serialize_map(None)?;
1590 for (k, v) in data {
1591 if let Category::Primitive = v.serialize(Categorize::new())? {
1592 map.serialize_entry(&k, &v)?;
1593 }
1594 }
1595 for (k, v) in data {
1596 if let Category::Array = v.serialize(Categorize::new())? {
1597 map.serialize_entry(&k, &v)?;
1598 }
1599 }
1600 for (k, v) in data {
1601 if let Category::Table = v.serialize(Categorize::new())? {
1602 map.serialize_entry(&k, &v)?;
1603 }
1604 }
1605 map.end()
1606 }
1607
1608 struct Categorize<E>(marker::PhantomData<E>);
1609
1610 impl<E> Categorize<E> {
new() -> Self1611 fn new() -> Self {
1612 Categorize(marker::PhantomData)
1613 }
1614 }
1615
1616 impl<E: ser::Error> ser::Serializer for Categorize<E> {
1617 type Ok = Category;
1618 type Error = E;
1619 type SerializeSeq = Self;
1620 type SerializeTuple = Self;
1621 type SerializeTupleStruct = Self;
1622 type SerializeTupleVariant = Self;
1623 type SerializeMap = Self;
1624 type SerializeStruct = Self;
1625 type SerializeStructVariant = ser::Impossible<Category, E>;
1626
serialize_bool(self, _: bool) -> Result<Self::Ok, Self::Error>1627 fn serialize_bool(self, _: bool) -> Result<Self::Ok, Self::Error> {
1628 Ok(Category::Primitive)
1629 }
1630
serialize_i8(self, _: i8) -> Result<Self::Ok, Self::Error>1631 fn serialize_i8(self, _: i8) -> Result<Self::Ok, Self::Error> {
1632 Ok(Category::Primitive)
1633 }
1634
serialize_i16(self, _: i16) -> Result<Self::Ok, Self::Error>1635 fn serialize_i16(self, _: i16) -> Result<Self::Ok, Self::Error> {
1636 Ok(Category::Primitive)
1637 }
1638
serialize_i32(self, _: i32) -> Result<Self::Ok, Self::Error>1639 fn serialize_i32(self, _: i32) -> Result<Self::Ok, Self::Error> {
1640 Ok(Category::Primitive)
1641 }
1642
serialize_i64(self, _: i64) -> Result<Self::Ok, Self::Error>1643 fn serialize_i64(self, _: i64) -> Result<Self::Ok, Self::Error> {
1644 Ok(Category::Primitive)
1645 }
1646
serialize_u8(self, _: u8) -> Result<Self::Ok, Self::Error>1647 fn serialize_u8(self, _: u8) -> Result<Self::Ok, Self::Error> {
1648 Ok(Category::Primitive)
1649 }
1650
serialize_u16(self, _: u16) -> Result<Self::Ok, Self::Error>1651 fn serialize_u16(self, _: u16) -> Result<Self::Ok, Self::Error> {
1652 Ok(Category::Primitive)
1653 }
1654
serialize_u32(self, _: u32) -> Result<Self::Ok, Self::Error>1655 fn serialize_u32(self, _: u32) -> Result<Self::Ok, Self::Error> {
1656 Ok(Category::Primitive)
1657 }
1658
serialize_u64(self, _: u64) -> Result<Self::Ok, Self::Error>1659 fn serialize_u64(self, _: u64) -> Result<Self::Ok, Self::Error> {
1660 Ok(Category::Primitive)
1661 }
1662
serialize_f32(self, _: f32) -> Result<Self::Ok, Self::Error>1663 fn serialize_f32(self, _: f32) -> Result<Self::Ok, Self::Error> {
1664 Ok(Category::Primitive)
1665 }
1666
serialize_f64(self, _: f64) -> Result<Self::Ok, Self::Error>1667 fn serialize_f64(self, _: f64) -> Result<Self::Ok, Self::Error> {
1668 Ok(Category::Primitive)
1669 }
1670
serialize_char(self, _: char) -> Result<Self::Ok, Self::Error>1671 fn serialize_char(self, _: char) -> Result<Self::Ok, Self::Error> {
1672 Ok(Category::Primitive)
1673 }
1674
serialize_str(self, _: &str) -> Result<Self::Ok, Self::Error>1675 fn serialize_str(self, _: &str) -> Result<Self::Ok, Self::Error> {
1676 Ok(Category::Primitive)
1677 }
1678
serialize_bytes(self, _: &[u8]) -> Result<Self::Ok, Self::Error>1679 fn serialize_bytes(self, _: &[u8]) -> Result<Self::Ok, Self::Error> {
1680 Ok(Category::Array)
1681 }
1682
serialize_none(self) -> Result<Self::Ok, Self::Error>1683 fn serialize_none(self) -> Result<Self::Ok, Self::Error> {
1684 Err(ser::Error::custom("unsupported"))
1685 }
1686
serialize_some<T: ?Sized + ser::Serialize>(self, v: &T) -> Result<Self::Ok, Self::Error>1687 fn serialize_some<T: ?Sized + ser::Serialize>(self, v: &T) -> Result<Self::Ok, Self::Error> {
1688 v.serialize(self)
1689 }
1690
serialize_unit(self) -> Result<Self::Ok, Self::Error>1691 fn serialize_unit(self) -> Result<Self::Ok, Self::Error> {
1692 Err(ser::Error::custom("unsupported"))
1693 }
1694
serialize_unit_struct(self, _: &'static str) -> Result<Self::Ok, Self::Error>1695 fn serialize_unit_struct(self, _: &'static str) -> Result<Self::Ok, Self::Error> {
1696 Err(ser::Error::custom("unsupported"))
1697 }
1698
serialize_unit_variant( self, _: &'static str, _: u32, _: &'static str, ) -> Result<Self::Ok, Self::Error>1699 fn serialize_unit_variant(
1700 self,
1701 _: &'static str,
1702 _: u32,
1703 _: &'static str,
1704 ) -> Result<Self::Ok, Self::Error> {
1705 Err(ser::Error::custom("unsupported"))
1706 }
1707
serialize_newtype_struct<T: ?Sized + ser::Serialize>( self, _: &'static str, v: &T, ) -> Result<Self::Ok, Self::Error>1708 fn serialize_newtype_struct<T: ?Sized + ser::Serialize>(
1709 self,
1710 _: &'static str,
1711 v: &T,
1712 ) -> Result<Self::Ok, Self::Error> {
1713 v.serialize(self)
1714 }
1715
serialize_newtype_variant<T: ?Sized + ser::Serialize>( self, _: &'static str, _: u32, _: &'static str, _: &T, ) -> Result<Self::Ok, Self::Error>1716 fn serialize_newtype_variant<T: ?Sized + ser::Serialize>(
1717 self,
1718 _: &'static str,
1719 _: u32,
1720 _: &'static str,
1721 _: &T,
1722 ) -> Result<Self::Ok, Self::Error> {
1723 Err(ser::Error::custom("unsupported"))
1724 }
1725
serialize_seq(self, _: Option<usize>) -> Result<Self, Self::Error>1726 fn serialize_seq(self, _: Option<usize>) -> Result<Self, Self::Error> {
1727 Ok(self)
1728 }
1729
serialize_tuple(self, _: usize) -> Result<Self::SerializeTuple, Self::Error>1730 fn serialize_tuple(self, _: usize) -> Result<Self::SerializeTuple, Self::Error> {
1731 Ok(self)
1732 }
1733
serialize_tuple_struct( self, _: &'static str, _: usize, ) -> Result<Self::SerializeTupleStruct, Self::Error>1734 fn serialize_tuple_struct(
1735 self,
1736 _: &'static str,
1737 _: usize,
1738 ) -> Result<Self::SerializeTupleStruct, Self::Error> {
1739 Ok(self)
1740 }
1741
serialize_tuple_variant( self, _: &'static str, _: u32, _: &'static str, _: usize, ) -> Result<Self::SerializeTupleVariant, Self::Error>1742 fn serialize_tuple_variant(
1743 self,
1744 _: &'static str,
1745 _: u32,
1746 _: &'static str,
1747 _: usize,
1748 ) -> Result<Self::SerializeTupleVariant, Self::Error> {
1749 Ok(self)
1750 }
1751
serialize_map(self, _: Option<usize>) -> Result<Self, Self::Error>1752 fn serialize_map(self, _: Option<usize>) -> Result<Self, Self::Error> {
1753 Ok(self)
1754 }
1755
serialize_struct(self, _: &'static str, _: usize) -> Result<Self, Self::Error>1756 fn serialize_struct(self, _: &'static str, _: usize) -> Result<Self, Self::Error> {
1757 Ok(self)
1758 }
1759
serialize_struct_variant( self, _: &'static str, _: u32, _: &'static str, _: usize, ) -> Result<Self::SerializeStructVariant, Self::Error>1760 fn serialize_struct_variant(
1761 self,
1762 _: &'static str,
1763 _: u32,
1764 _: &'static str,
1765 _: usize,
1766 ) -> Result<Self::SerializeStructVariant, Self::Error> {
1767 Err(ser::Error::custom("unsupported"))
1768 }
1769 }
1770
1771 impl<E: ser::Error> ser::SerializeSeq for Categorize<E> {
1772 type Ok = Category;
1773 type Error = E;
1774
serialize_element<T: ?Sized + ser::Serialize>(&mut self, _: &T) -> Result<(), Self::Error>1775 fn serialize_element<T: ?Sized + ser::Serialize>(&mut self, _: &T) -> Result<(), Self::Error> {
1776 Ok(())
1777 }
1778
end(self) -> Result<Self::Ok, Self::Error>1779 fn end(self) -> Result<Self::Ok, Self::Error> {
1780 Ok(Category::Array)
1781 }
1782 }
1783
1784 impl<E: ser::Error> ser::SerializeTuple for Categorize<E> {
1785 type Ok = Category;
1786 type Error = E;
1787
serialize_element<T: ?Sized + ser::Serialize>(&mut self, _: &T) -> Result<(), Self::Error>1788 fn serialize_element<T: ?Sized + ser::Serialize>(&mut self, _: &T) -> Result<(), Self::Error> {
1789 Ok(())
1790 }
1791
end(self) -> Result<Self::Ok, Self::Error>1792 fn end(self) -> Result<Self::Ok, Self::Error> {
1793 Ok(Category::Array)
1794 }
1795 }
1796
1797 impl<E: ser::Error> ser::SerializeTupleVariant for Categorize<E> {
1798 type Ok = Category;
1799 type Error = E;
1800
serialize_field<T: ?Sized + ser::Serialize>(&mut self, _: &T) -> Result<(), Self::Error>1801 fn serialize_field<T: ?Sized + ser::Serialize>(&mut self, _: &T) -> Result<(), Self::Error> {
1802 Ok(())
1803 }
1804
end(self) -> Result<Self::Ok, Self::Error>1805 fn end(self) -> Result<Self::Ok, Self::Error> {
1806 Ok(Category::Array)
1807 }
1808 }
1809
1810 impl<E: ser::Error> ser::SerializeTupleStruct for Categorize<E> {
1811 type Ok = Category;
1812 type Error = E;
1813
serialize_field<T: ?Sized + ser::Serialize>(&mut self, _: &T) -> Result<(), Self::Error>1814 fn serialize_field<T: ?Sized + ser::Serialize>(&mut self, _: &T) -> Result<(), Self::Error> {
1815 Ok(())
1816 }
1817
end(self) -> Result<Self::Ok, Self::Error>1818 fn end(self) -> Result<Self::Ok, Self::Error> {
1819 Ok(Category::Array)
1820 }
1821 }
1822
1823 impl<E: ser::Error> ser::SerializeMap for Categorize<E> {
1824 type Ok = Category;
1825 type Error = E;
1826
serialize_key<T: ?Sized + ser::Serialize>(&mut self, _: &T) -> Result<(), Self::Error>1827 fn serialize_key<T: ?Sized + ser::Serialize>(&mut self, _: &T) -> Result<(), Self::Error> {
1828 Ok(())
1829 }
1830
serialize_value<T: ?Sized + ser::Serialize>(&mut self, _: &T) -> Result<(), Self::Error>1831 fn serialize_value<T: ?Sized + ser::Serialize>(&mut self, _: &T) -> Result<(), Self::Error> {
1832 Ok(())
1833 }
1834
end(self) -> Result<Self::Ok, Self::Error>1835 fn end(self) -> Result<Self::Ok, Self::Error> {
1836 Ok(Category::Table)
1837 }
1838 }
1839
1840 impl<E: ser::Error> ser::SerializeStruct for Categorize<E> {
1841 type Ok = Category;
1842 type Error = E;
1843
serialize_field<T: ?Sized>(&mut self, _: &'static str, _: &T) -> Result<(), Self::Error> where T: ser::Serialize,1844 fn serialize_field<T: ?Sized>(&mut self, _: &'static str, _: &T) -> Result<(), Self::Error>
1845 where
1846 T: ser::Serialize,
1847 {
1848 Ok(())
1849 }
1850
end(self) -> Result<Self::Ok, Self::Error>1851 fn end(self) -> Result<Self::Ok, Self::Error> {
1852 Ok(Category::Table)
1853 }
1854 }
1855