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