This repository has been archived by the owner on Sep 24, 2022. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 189
/
ser.rs
1859 lines (1643 loc) · 52.6 KB
/
ser.rs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
//! Serializing Rust structures into TOML.
//!
//! This module contains all the Serde support for serializing Rust structures
//! into TOML documents (as strings). Note that some top-level functions here
//! are also provided at the top of the crate.
//!
//! Note that the TOML format has a restriction that if a table itself contains
//! tables, all keys with non-table values must be emitted first. This is
//! typically easy to ensure happens when you're defining a `struct` as you can
//! reorder the fields manually, but when working with maps (such as `BTreeMap`
//! or `HashMap`) this can lead to serialization errors. In those situations you
//! may use the `tables_last` function in this module like so:
//!
//! ```rust
//! # use serde_derive::Serialize;
//! # use std::collections::HashMap;
//! #[derive(Serialize)]
//! struct Manifest {
//! package: Package,
//! #[serde(serialize_with = "toml::ser::tables_last")]
//! dependencies: HashMap<String, Dependency>,
//! }
//! # type Package = String;
//! # type Dependency = String;
//! # fn main() {}
//! ```
use std::cell::Cell;
use std::error;
use std::fmt::{self, Write};
use std::marker;
use std::rc::Rc;
use crate::datetime;
use serde::ser;
/// Serialize the given data structure as a TOML byte vector.
///
/// Serialization can fail if `T`'s implementation of `Serialize` decides to
/// fail, if `T` contains a map with non-string keys, or if `T` attempts to
/// serialize an unsupported datatype such as an enum, tuple, or tuple struct.
pub fn to_vec<T: ?Sized>(value: &T) -> Result<Vec<u8>, Error>
where
T: ser::Serialize,
{
to_string(value).map(|e| e.into_bytes())
}
/// Serialize the given data structure as a String of TOML.
///
/// Serialization can fail if `T`'s implementation of `Serialize` decides to
/// fail, if `T` contains a map with non-string keys, or if `T` attempts to
/// serialize an unsupported datatype such as an enum, tuple, or tuple struct.
///
/// # Examples
///
/// ```
/// use serde_derive::Serialize;
///
/// #[derive(Serialize)]
/// struct Config {
/// database: Database,
/// }
///
/// #[derive(Serialize)]
/// struct Database {
/// ip: String,
/// port: Vec<u16>,
/// connection_max: u32,
/// enabled: bool,
/// }
///
/// fn main() {
/// let config = Config {
/// database: Database {
/// ip: "192.168.1.1".to_string(),
/// port: vec![8001, 8002, 8003],
/// connection_max: 5000,
/// enabled: false,
/// },
/// };
///
/// let toml = toml::to_string(&config).unwrap();
/// println!("{}", toml)
/// }
/// ```
pub fn to_string<T: ?Sized>(value: &T) -> Result<String, Error>
where
T: ser::Serialize,
{
let mut dst = String::with_capacity(128);
value.serialize(&mut Serializer::new(&mut dst))?;
Ok(dst)
}
/// Serialize the given data structure as a "pretty" String of TOML.
///
/// This is identical to `to_string` except the output string has a more
/// "pretty" output. See `Serializer::pretty` for more details.
pub fn to_string_pretty<T: ?Sized>(value: &T) -> Result<String, Error>
where
T: ser::Serialize,
{
let mut dst = String::with_capacity(128);
value.serialize(&mut Serializer::pretty(&mut dst))?;
Ok(dst)
}
/// Errors that can occur when serializing a type.
#[derive(Debug, PartialEq, Eq, Clone)]
pub enum Error {
/// Indicates that a Rust type was requested to be serialized but it was not
/// supported.
///
/// Currently the TOML format does not support serializing types such as
/// enums, tuples and tuple structs.
UnsupportedType,
/// The key of all TOML maps must be strings, but serialization was
/// attempted where the key of a map was not a string.
KeyNotString,
/// An error that we never omit but keep for backwards compatibility
#[doc(hidden)]
KeyNewline,
/// An array had to be homogeneous, but now it is allowed to be heterogeneous.
#[doc(hidden)]
ArrayMixedType,
/// All values in a TOML table must be emitted before further tables are
/// emitted. If a value is emitted *after* a table then this error is
/// generated.
ValueAfterTable,
/// A serialized date was invalid.
DateInvalid,
/// A serialized number was invalid.
NumberInvalid,
/// None was attempted to be serialized, but it's not supported.
UnsupportedNone,
/// A custom error which could be generated when serializing a particular
/// type.
Custom(String),
#[doc(hidden)]
__Nonexhaustive,
}
#[derive(Debug, Default, Clone)]
/// Internal place for holding array settings
struct ArraySettings {
indent: usize,
trailing_comma: bool,
}
impl ArraySettings {
fn pretty() -> ArraySettings {
ArraySettings {
indent: 4,
trailing_comma: true,
}
}
}
#[derive(Debug, Default, Clone)]
/// String settings
struct StringSettings {
/// Whether to use literal strings when possible
literal: bool,
}
impl StringSettings {
fn pretty() -> StringSettings {
StringSettings { literal: true }
}
}
#[derive(Debug, Default, Clone)]
/// Internal struct for holding serialization settings
struct Settings {
array: Option<ArraySettings>,
string: Option<StringSettings>,
}
/// Serialization implementation for TOML.
///
/// This structure implements serialization support for TOML to serialize an
/// arbitrary type to TOML. Note that the TOML format does not support all
/// datatypes in Rust, such as enums, tuples, and tuple structs. These types
/// will generate an error when serialized.
///
/// Currently a serializer always writes its output to an in-memory `String`,
/// which is passed in when creating the serializer itself.
pub struct Serializer<'a> {
dst: &'a mut String,
state: State<'a>,
settings: Rc<Settings>,
}
#[derive(Debug, Copy, Clone)]
enum ArrayState {
Started,
StartedAsATable,
}
#[derive(Debug, Clone)]
enum State<'a> {
Table {
key: &'a str,
parent: &'a State<'a>,
first: &'a Cell<bool>,
table_emitted: &'a Cell<bool>,
},
Array {
parent: &'a State<'a>,
first: &'a Cell<bool>,
type_: &'a Cell<Option<ArrayState>>,
len: Option<usize>,
},
End,
}
#[doc(hidden)]
pub struct SerializeSeq<'a, 'b> {
ser: &'b mut Serializer<'a>,
first: Cell<bool>,
type_: Cell<Option<ArrayState>>,
len: Option<usize>,
}
#[doc(hidden)]
pub enum SerializeTable<'a, 'b> {
Datetime(&'b mut Serializer<'a>),
Table {
ser: &'b mut Serializer<'a>,
key: String,
first: Cell<bool>,
table_emitted: Cell<bool>,
},
}
impl<'a> Serializer<'a> {
/// Creates a new serializer which will emit TOML into the buffer provided.
///
/// The serializer can then be used to serialize a type after which the data
/// will be present in `dst`.
pub fn new(dst: &'a mut String) -> Serializer<'a> {
Serializer {
dst,
state: State::End,
settings: Rc::new(Settings::default()),
}
}
/// Instantiate a "pretty" formatter
///
/// By default this will use:
///
/// - pretty strings: strings with newlines will use the `'''` syntax. See
/// `Serializer::pretty_string`
/// - pretty arrays: each item in arrays will be on a newline, have an indentation of 4 and
/// have a trailing comma. See `Serializer::pretty_array`
pub fn pretty(dst: &'a mut String) -> Serializer<'a> {
Serializer {
dst,
state: State::End,
settings: Rc::new(Settings {
array: Some(ArraySettings::pretty()),
string: Some(StringSettings::pretty()),
}),
}
}
/// Enable or Disable pretty strings
///
/// If enabled, literal strings will be used when possible and strings with
/// one or more newlines will use triple quotes (i.e.: `'''` or `"""`)
///
/// # Examples
///
/// Instead of:
///
/// ```toml,ignore
/// single = "no newlines"
/// text = "\nfoo\nbar\n"
/// ```
///
/// You will have:
///
/// ```toml,ignore
/// single = 'no newlines'
/// text = '''
/// foo
/// bar
/// '''
/// ```
pub fn pretty_string(&mut self, value: bool) -> &mut Self {
Rc::get_mut(&mut self.settings).unwrap().string = if value {
Some(StringSettings::pretty())
} else {
None
};
self
}
/// Enable or Disable Literal strings for pretty strings
///
/// If enabled, literal strings will be used when possible and strings with
/// one or more newlines will use triple quotes (i.e.: `'''` or `"""`)
///
/// If disabled, literal strings will NEVER be used and strings with one or
/// more newlines will use `"""`
///
/// # Examples
///
/// Instead of:
///
/// ```toml,ignore
/// single = "no newlines"
/// text = "\nfoo\nbar\n"
/// ```
///
/// You will have:
///
/// ```toml,ignore
/// single = "no newlines"
/// text = """
/// foo
/// bar
/// """
/// ```
pub fn pretty_string_literal(&mut self, value: bool) -> &mut Self {
let use_default = if let Some(ref mut s) = Rc::get_mut(&mut self.settings).unwrap().string {
s.literal = value;
false
} else {
true
};
if use_default {
let mut string = StringSettings::pretty();
string.literal = value;
Rc::get_mut(&mut self.settings).unwrap().string = Some(string);
}
self
}
/// Enable or Disable pretty arrays
///
/// If enabled, arrays will always have each item on their own line.
///
/// Some specific features can be controlled via other builder methods:
///
/// - `Serializer::pretty_array_indent`: set the indent to a value other
/// than 4.
/// - `Serializer::pretty_array_trailing_comma`: enable/disable the trailing
/// comma on the last item.
///
/// # Examples
///
/// Instead of:
///
/// ```toml,ignore
/// array = ["foo", "bar"]
/// ```
///
/// You will have:
///
/// ```toml,ignore
/// array = [
/// "foo",
/// "bar",
/// ]
/// ```
pub fn pretty_array(&mut self, value: bool) -> &mut Self {
Rc::get_mut(&mut self.settings).unwrap().array = if value {
Some(ArraySettings::pretty())
} else {
None
};
self
}
/// Set the indent for pretty arrays
///
/// See `Serializer::pretty_array` for more details.
pub fn pretty_array_indent(&mut self, value: usize) -> &mut Self {
let use_default = if let Some(ref mut a) = Rc::get_mut(&mut self.settings).unwrap().array {
a.indent = value;
false
} else {
true
};
if use_default {
let mut array = ArraySettings::pretty();
array.indent = value;
Rc::get_mut(&mut self.settings).unwrap().array = Some(array);
}
self
}
/// Specify whether to use a trailing comma when serializing pretty arrays
///
/// See `Serializer::pretty_array` for more details.
pub fn pretty_array_trailing_comma(&mut self, value: bool) -> &mut Self {
let use_default = if let Some(ref mut a) = Rc::get_mut(&mut self.settings).unwrap().array {
a.trailing_comma = value;
false
} else {
true
};
if use_default {
let mut array = ArraySettings::pretty();
array.trailing_comma = value;
Rc::get_mut(&mut self.settings).unwrap().array = Some(array);
}
self
}
fn display<T: fmt::Display>(&mut self, t: T, type_: ArrayState) -> Result<(), Error> {
self.emit_key(type_)?;
write!(self.dst, "{}", t).map_err(ser::Error::custom)?;
if let State::Table { .. } = self.state {
self.dst.push_str("\n");
}
Ok(())
}
fn emit_key(&mut self, type_: ArrayState) -> Result<(), Error> {
self.array_type(type_)?;
let state = self.state.clone();
self._emit_key(&state)
}
// recursive implementation of `emit_key` above
fn _emit_key(&mut self, state: &State<'_>) -> Result<(), Error> {
match *state {
State::End => Ok(()),
State::Array {
parent,
first,
type_,
len,
} => {
assert!(type_.get().is_some());
if first.get() {
self._emit_key(parent)?;
}
self.emit_array(first, len)
}
State::Table {
parent,
first,
table_emitted,
key,
} => {
if table_emitted.get() {
return Err(Error::ValueAfterTable);
}
if first.get() {
self.emit_table_header(parent)?;
first.set(false);
}
self.escape_key(key)?;
self.dst.push_str(" = ");
Ok(())
}
}
}
fn emit_array(&mut self, first: &Cell<bool>, len: Option<usize>) -> Result<(), Error> {
match (len, &self.settings.array) {
(Some(0..=1), _) | (_, &None) => {
if first.get() {
self.dst.push_str("[")
} else {
self.dst.push_str(", ")
}
}
(_, &Some(ref a)) => {
if first.get() {
self.dst.push_str("[\n")
} else {
self.dst.push_str(",\n")
}
for _ in 0..a.indent {
self.dst.push_str(" ");
}
}
}
Ok(())
}
fn array_type(&mut self, type_: ArrayState) -> Result<(), Error> {
let prev = match self.state {
State::Array { type_, .. } => type_,
_ => return Ok(()),
};
if prev.get().is_none() {
prev.set(Some(type_));
}
Ok(())
}
fn escape_key(&mut self, key: &str) -> Result<(), Error> {
let ok = key.len() > 0
&& key.chars().all(|c| match c {
'a'..='z' | 'A'..='Z' | '0'..='9' | '-' | '_' => true,
_ => false,
});
if ok {
write!(self.dst, "{}", key).map_err(ser::Error::custom)?;
} else {
self.emit_str(key, true)?;
}
Ok(())
}
fn emit_str(&mut self, value: &str, is_key: bool) -> Result<(), Error> {
#[derive(PartialEq)]
enum Type {
NewlineTripple,
OnelineTripple,
OnelineSingle,
}
enum Repr {
/// represent as a literal string (using '')
Literal(String, Type),
/// represent the std way (using "")
Std(Type),
}
fn do_pretty(value: &str) -> Repr {
// For doing pretty prints we store in a new String
// because there are too many cases where pretty cannot
// work. We need to determine:
// - if we are a "multi-line" pretty (if there are \n)
// - if ['''] appears if multi or ['] if single
// - if there are any invalid control characters
//
// Doing it any other way would require multiple passes
// to determine if a pretty string works or not.
let mut out = String::with_capacity(value.len() * 2);
let mut ty = Type::OnelineSingle;
// found consecutive single quotes
let mut max_found_singles = 0;
let mut found_singles = 0;
let mut can_be_pretty = true;
for ch in value.chars() {
if can_be_pretty {
if ch == '\'' {
found_singles += 1;
if found_singles >= 3 {
can_be_pretty = false;
}
} else {
if found_singles > max_found_singles {
max_found_singles = found_singles;
}
found_singles = 0
}
match ch {
'\t' => {}
'\n' => ty = Type::NewlineTripple,
// Escape codes are needed if any ascii control
// characters are present, including \b \f \r.
c if c <= '\u{1f}' || c == '\u{7f}' => can_be_pretty = false,
_ => {}
}
out.push(ch);
} else {
// the string cannot be represented as pretty,
// still check if it should be multiline
if ch == '\n' {
ty = Type::NewlineTripple;
}
}
}
if can_be_pretty && found_singles > 0 && value.ends_with('\'') {
// We cannot escape the ending quote so we must use """
can_be_pretty = false;
}
if !can_be_pretty {
debug_assert!(ty != Type::OnelineTripple);
return Repr::Std(ty);
}
if found_singles > max_found_singles {
max_found_singles = found_singles;
}
debug_assert!(max_found_singles < 3);
if ty == Type::OnelineSingle && max_found_singles >= 1 {
// no newlines, but must use ''' because it has ' in it
ty = Type::OnelineTripple;
}
Repr::Literal(out, ty)
}
let repr = if !is_key && self.settings.string.is_some() {
match (&self.settings.string, do_pretty(value)) {
(&Some(StringSettings { literal: false, .. }), Repr::Literal(_, ty)) => {
Repr::Std(ty)
}
(_, r) => r,
}
} else {
Repr::Std(Type::OnelineSingle)
};
match repr {
Repr::Literal(literal, ty) => {
// A pretty string
match ty {
Type::NewlineTripple => self.dst.push_str("'''\n"),
Type::OnelineTripple => self.dst.push_str("'''"),
Type::OnelineSingle => self.dst.push('\''),
}
self.dst.push_str(&literal);
match ty {
Type::OnelineSingle => self.dst.push('\''),
_ => self.dst.push_str("'''"),
}
}
Repr::Std(ty) => {
match ty {
Type::NewlineTripple => self.dst.push_str("\"\"\"\n"),
// note: OnelineTripple can happen if do_pretty wants to do
// '''it's one line'''
// but settings.string.literal == false
Type::OnelineSingle | Type::OnelineTripple => self.dst.push('"'),
}
for ch in value.chars() {
match ch {
'\u{8}' => self.dst.push_str("\\b"),
'\u{9}' => self.dst.push_str("\\t"),
'\u{a}' => match ty {
Type::NewlineTripple => self.dst.push('\n'),
Type::OnelineSingle => self.dst.push_str("\\n"),
_ => unreachable!(),
},
'\u{c}' => self.dst.push_str("\\f"),
'\u{d}' => self.dst.push_str("\\r"),
'\u{22}' => self.dst.push_str("\\\""),
'\u{5c}' => self.dst.push_str("\\\\"),
c if c <= '\u{1f}' || c == '\u{7f}' => {
write!(self.dst, "\\u{:04X}", ch as u32).map_err(ser::Error::custom)?;
}
ch => self.dst.push(ch),
}
}
match ty {
Type::NewlineTripple => self.dst.push_str("\"\"\""),
Type::OnelineSingle | Type::OnelineTripple => self.dst.push('"'),
}
}
}
Ok(())
}
fn emit_table_header(&mut self, state: &State<'_>) -> Result<(), Error> {
let array_of_tables = match *state {
State::End => return Ok(()),
State::Array { .. } => true,
_ => false,
};
// Unlike [..]s, we can't omit [[..]] ancestors, so be sure to emit table
// headers for them.
let mut p = state;
if let State::Array { first, parent, .. } = *state {
if first.get() {
p = parent;
}
}
while let State::Table { first, parent, .. } = *p {
p = parent;
if !first.get() {
break;
}
if let State::Array {
parent: &State::Table { .. },
..
} = *parent
{
self.emit_table_header(parent)?;
break;
}
}
match *state {
State::Table { first, .. } => {
if !first.get() {
// Newline if we are a table that is not the first
// table in the document.
self.dst.push('\n');
}
}
State::Array { parent, first, .. } => {
if !first.get() {
// Always newline if we are not the first item in the
// table-array
self.dst.push('\n');
} else if let State::Table { first, .. } = *parent {
if !first.get() {
// Newline if we are not the first item in the document
self.dst.push('\n');
}
}
}
_ => {}
}
self.dst.push_str("[");
if array_of_tables {
self.dst.push_str("[");
}
self.emit_key_part(state)?;
if array_of_tables {
self.dst.push_str("]");
}
self.dst.push_str("]\n");
Ok(())
}
fn emit_key_part(&mut self, key: &State<'_>) -> Result<bool, Error> {
match *key {
State::Array { parent, .. } => self.emit_key_part(parent),
State::End => Ok(true),
State::Table {
key,
parent,
table_emitted,
..
} => {
table_emitted.set(true);
let first = self.emit_key_part(parent)?;
if !first {
self.dst.push_str(".");
}
self.escape_key(key)?;
Ok(false)
}
}
}
}
macro_rules! serialize_float {
($this:expr, $v:expr) => {{
$this.emit_key(ArrayState::Started)?;
match ($v.is_sign_negative(), $v.is_nan(), $v == 0.0) {
(true, true, _) => write!($this.dst, "-nan"),
(false, true, _) => write!($this.dst, "nan"),
(true, false, true) => write!($this.dst, "-0.0"),
(false, false, true) => write!($this.dst, "0.0"),
(_, false, false) => write!($this.dst, "{}", $v).and_then(|_| {
if $v % 1.0 == 0.0 {
write!($this.dst, ".0")
} else {
Ok(())
}
}),
}
.map_err(ser::Error::custom)?;
if let State::Table { .. } = $this.state {
$this.dst.push_str("\n");
}
return Ok(());
}};
}
impl<'a, 'b> ser::Serializer for &'b mut Serializer<'a> {
type Ok = ();
type Error = Error;
type SerializeSeq = SerializeSeq<'a, 'b>;
type SerializeTuple = SerializeSeq<'a, 'b>;
type SerializeTupleStruct = SerializeSeq<'a, 'b>;
type SerializeTupleVariant = SerializeSeq<'a, 'b>;
type SerializeMap = SerializeTable<'a, 'b>;
type SerializeStruct = SerializeTable<'a, 'b>;
type SerializeStructVariant = ser::Impossible<(), Error>;
fn serialize_bool(self, v: bool) -> Result<(), Self::Error> {
self.display(v, ArrayState::Started)
}
fn serialize_i8(self, v: i8) -> Result<(), Self::Error> {
self.display(v, ArrayState::Started)
}
fn serialize_i16(self, v: i16) -> Result<(), Self::Error> {
self.display(v, ArrayState::Started)
}
fn serialize_i32(self, v: i32) -> Result<(), Self::Error> {
self.display(v, ArrayState::Started)
}
fn serialize_i64(self, v: i64) -> Result<(), Self::Error> {
self.display(v, ArrayState::Started)
}
fn serialize_u8(self, v: u8) -> Result<(), Self::Error> {
self.display(v, ArrayState::Started)
}
fn serialize_u16(self, v: u16) -> Result<(), Self::Error> {
self.display(v, ArrayState::Started)
}
fn serialize_u32(self, v: u32) -> Result<(), Self::Error> {
self.display(v, ArrayState::Started)
}
fn serialize_u64(self, v: u64) -> Result<(), Self::Error> {
self.display(v, ArrayState::Started)
}
fn serialize_f32(self, v: f32) -> Result<(), Self::Error> {
serialize_float!(self, v)
}
fn serialize_f64(self, v: f64) -> Result<(), Self::Error> {
serialize_float!(self, v)
}
fn serialize_char(self, v: char) -> Result<(), Self::Error> {
let mut buf = [0; 4];
self.serialize_str(v.encode_utf8(&mut buf))
}
fn serialize_str(self, value: &str) -> Result<(), Self::Error> {
self.emit_key(ArrayState::Started)?;
self.emit_str(value, false)?;
if let State::Table { .. } = self.state {
self.dst.push_str("\n");
}
Ok(())
}
fn serialize_bytes(self, value: &[u8]) -> Result<(), Self::Error> {
use serde::ser::Serialize;
value.serialize(self)
}
fn serialize_none(self) -> Result<(), Self::Error> {
Err(Error::UnsupportedNone)
}
fn serialize_some<T: ?Sized>(self, value: &T) -> Result<(), Self::Error>
where
T: ser::Serialize,
{
value.serialize(self)
}
fn serialize_unit(self) -> Result<(), Self::Error> {
Err(Error::UnsupportedType)
}
fn serialize_unit_struct(self, _name: &'static str) -> Result<(), Self::Error> {
Err(Error::UnsupportedType)
}
fn serialize_unit_variant(
self,
_name: &'static str,
_variant_index: u32,
variant: &'static str,
) -> Result<(), Self::Error> {
self.serialize_str(variant)
}
fn serialize_newtype_struct<T: ?Sized>(
self,
_name: &'static str,
value: &T,
) -> Result<(), Self::Error>
where
T: ser::Serialize,
{
value.serialize(self)
}
fn serialize_newtype_variant<T: ?Sized>(
self,
_name: &'static str,
_variant_index: u32,
_variant: &'static str,
_value: &T,
) -> Result<(), Self::Error>
where
T: ser::Serialize,
{
Err(Error::UnsupportedType)
}
fn serialize_seq(self, len: Option<usize>) -> Result<Self::SerializeSeq, Self::Error> {
self.array_type(ArrayState::Started)?;
Ok(SerializeSeq {
ser: self,
first: Cell::new(true),
type_: Cell::new(None),
len,
})
}
fn serialize_tuple(self, len: usize) -> Result<Self::SerializeTuple, Self::Error> {
self.serialize_seq(Some(len))
}
fn serialize_tuple_struct(
self,
_name: &'static str,
len: usize,
) -> Result<Self::SerializeTupleStruct, Self::Error> {
self.serialize_seq(Some(len))
}
fn serialize_tuple_variant(
self,
_name: &'static str,
_variant_index: u32,
_variant: &'static str,
len: usize,
) -> Result<Self::SerializeTupleVariant, Self::Error> {
self.serialize_seq(Some(len))
}
fn serialize_map(self, _len: Option<usize>) -> Result<Self::SerializeMap, Self::Error> {
self.array_type(ArrayState::StartedAsATable)?;
Ok(SerializeTable::Table {
ser: self,
key: String::new(),
first: Cell::new(true),
table_emitted: Cell::new(false),
})
}
fn serialize_struct(
self,
name: &'static str,
_len: usize,
) -> Result<Self::SerializeStruct, Self::Error> {
if name == datetime::NAME {
self.array_type(ArrayState::Started)?;
Ok(SerializeTable::Datetime(self))
} else {
self.array_type(ArrayState::StartedAsATable)?;
Ok(SerializeTable::Table {
ser: self,
key: String::new(),
first: Cell::new(true),
table_emitted: Cell::new(false),
})
}
}
fn serialize_struct_variant(
self,
_name: &'static str,
_variant_index: u32,
_variant: &'static str,
_len: usize,
) -> Result<Self::SerializeStructVariant, Self::Error> {
Err(Error::UnsupportedType)
}
}
impl<'a, 'b> ser::SerializeSeq for SerializeSeq<'a, 'b> {
type Ok = ();
type Error = Error;
fn serialize_element<T: ?Sized>(&mut self, value: &T) -> Result<(), Error>
where
T: ser::Serialize,
{
value.serialize(&mut Serializer {
dst: &mut *self.ser.dst,
state: State::Array {
parent: &self.ser.state,
first: &self.first,
type_: &self.type_,
len: self.len,
},
settings: self.ser.settings.clone(),
})?;
self.first.set(false);
Ok(())
}
fn end(self) -> Result<(), Error> {
match self.type_.get() {
Some(ArrayState::StartedAsATable) => return Ok(()),
Some(ArrayState::Started) => match (self.len, &self.ser.settings.array) {