1
use alloc::{borrow::Cow, string::String};
2
use core::fmt;
3

            
4
use serde::{ser, ser::Serialize};
5
use serde_derive::{Deserialize, Serialize};
6
use unicode_ident::is_xid_continue;
7

            
8
use crate::{
9
    error::{Error, Result},
10
    extensions::Extensions,
11
    options::Options,
12
    parse::{is_ident_first_char, is_ident_raw_char, is_whitespace_char, LargeSInt, LargeUInt},
13
};
14

            
15
pub mod path_meta;
16

            
17
mod raw;
18
#[cfg(test)]
19
mod tests;
20
mod value;
21

            
22
/// Serializes `value` into `writer`.
23
///
24
/// This function does not generate any newlines or nice formatting;
25
/// if you want that, you can use [`to_writer_pretty`] instead.
26
360
pub fn to_writer<W, T>(writer: W, value: &T) -> Result<()>
27
360
where
28
360
    W: fmt::Write,
29
360
    T: ?Sized + Serialize,
30
360
{
31
360
    Options::default().to_writer(writer, value)
32
360
}
33

            
34
/// Serializes `value` into `writer` in a pretty way.
35
360
pub fn to_writer_pretty<W, T>(writer: W, value: &T, config: PrettyConfig) -> Result<()>
36
360
where
37
360
    W: fmt::Write,
38
360
    T: ?Sized + Serialize,
39
360
{
40
360
    Options::default().to_writer_pretty(writer, value, config)
41
360
}
42

            
43
/// Serializes `value` and returns it as string.
44
///
45
/// This function does not generate any newlines or nice formatting;
46
/// if you want that, you can use [`to_string_pretty`] instead.
47
1612
pub fn to_string<T>(value: &T) -> Result<String>
48
1612
where
49
1612
    T: ?Sized + Serialize,
50
1612
{
51
1612
    Options::default().to_string(value)
52
1612
}
53

            
54
/// Serializes `value` in the recommended RON layout in a pretty way.
55
1392
pub fn to_string_pretty<T>(value: &T, config: PrettyConfig) -> Result<String>
56
1392
where
57
1392
    T: ?Sized + Serialize,
58
1392
{
59
1392
    Options::default().to_string_pretty(value, config)
60
1392
}
61

            
62
/// Pretty serializer state
63
struct Pretty {
64
    indent: usize,
65
}
66

            
67
/// Pretty serializer configuration.
68
///
69
/// # Examples
70
///
71
/// ```
72
/// use ron::ser::PrettyConfig;
73
///
74
/// let my_config = PrettyConfig::new()
75
///     .depth_limit(4)
76
///     // definitely superior (okay, just joking)
77
///     .indentor("\t");
78
/// ```
79
#[allow(clippy::struct_excessive_bools)]
80
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
81
#[serde(default)]
82
#[non_exhaustive]
83
pub struct PrettyConfig {
84
    /// Limit the pretty-ness up to the given depth.
85
    pub depth_limit: usize,
86
    /// New line string
87
    pub new_line: Cow<'static, str>,
88
    /// Indentation string
89
    pub indentor: Cow<'static, str>,
90
    /// Separator string
91
    pub separator: Cow<'static, str>,
92
    // Whether to emit struct names
93
    pub struct_names: bool,
94
    /// Separate tuple members with indentation
95
    pub separate_tuple_members: bool,
96
    /// Enumerate array items in comments
97
    pub enumerate_arrays: bool,
98
    /// Enable extensions. Only configures `implicit_some`,
99
    ///  `unwrap_newtypes`, and `unwrap_variant_newtypes` for now.
100
    pub extensions: Extensions,
101
    /// Enable compact arrays, which do not insert new lines and indentation
102
    ///  between the elements of an array
103
    pub compact_arrays: bool,
104
    /// Whether to serialize strings as escaped strings,
105
    ///  or fall back onto raw strings if necessary.
106
    pub escape_strings: bool,
107
    /// Enable compact structs, which do not insert new lines and indentation
108
    ///  between the fields of a struct
109
    pub compact_structs: bool,
110
    /// Enable compact maps, which do not insert new lines and indentation
111
    ///  between the entries of a struct
112
    pub compact_maps: bool,
113
    /// Enable explicit number type suffixes like `1u16`
114
    pub number_suffixes: bool,
115
    /// Additional path-based field metadata to serialize
116
    pub path_meta: Option<path_meta::Field>,
117
}
118

            
119
impl PrettyConfig {
120
    /// Creates a default [`PrettyConfig`].
121
    #[must_use]
122
4170
    pub fn new() -> Self {
123
4170
        Self::default()
124
4170
    }
125

            
126
    /// Limits the pretty-formatting based on the number of indentations.
127
    /// I.e., with a depth limit of 5, starting with an element of depth
128
    /// (indentation level) 6, everything will be put into the same line,
129
    /// without pretty formatting.
130
    ///
131
    /// Default: [`usize::MAX`]
132
    #[must_use]
133
834
    pub fn depth_limit(mut self, depth_limit: usize) -> Self {
134
834
        self.depth_limit = depth_limit;
135
834

            
136
834
        self
137
834
    }
138

            
139
    /// Configures the newlines used for serialization.
140
    ///
141
    /// Default: `\r\n` on Windows, `\n` otherwise
142
    #[must_use]
143
36
    pub fn new_line(mut self, new_line: impl Into<Cow<'static, str>>) -> Self {
144
36
        self.new_line = new_line.into();
145
36

            
146
36
        self
147
36
    }
148

            
149
    /// Configures the string sequence used for indentation.
150
    ///
151
    /// Default: 4 spaces
152
    #[must_use]
153
4
    pub fn indentor(mut self, indentor: impl Into<Cow<'static, str>>) -> Self {
154
4
        self.indentor = indentor.into();
155
4

            
156
4
        self
157
4
    }
158

            
159
    /// Configures the string sequence used to separate items inline.
160
    ///
161
    /// Default: 1 space
162
    #[must_use]
163
8
    pub fn separator(mut self, separator: impl Into<Cow<'static, str>>) -> Self {
164
8
        self.separator = separator.into();
165
8

            
166
8
        self
167
8
    }
168

            
169
    /// Configures whether to emit struct names.
170
    ///
171
    /// See also [`Extensions::EXPLICIT_STRUCT_NAMES`] for the extension equivalent.
172
    ///
173
    /// Default: `false`
174
    #[must_use]
175
4334
    pub fn struct_names(mut self, struct_names: bool) -> Self {
176
4334
        self.struct_names = struct_names;
177
4334

            
178
4334
        self
179
4334
    }
180

            
181
    /// Configures whether tuples are single- or multi-line.
182
    /// If set to `true`, tuples will have their fields indented and in new
183
    /// lines. If set to `false`, tuples will be serialized without any
184
    /// newlines or indentations.
185
    ///
186
    /// Default: `false`
187
    #[must_use]
188
1390
    pub fn separate_tuple_members(mut self, separate_tuple_members: bool) -> Self {
189
1390
        self.separate_tuple_members = separate_tuple_members;
190
1390

            
191
1390
        self
192
1390
    }
193

            
194
    /// Configures whether a comment shall be added to every array element,
195
    /// indicating the index.
196
    ///
197
    /// Default: `false`
198
    #[must_use]
199
1946
    pub fn enumerate_arrays(mut self, enumerate_arrays: bool) -> Self {
200
1946
        self.enumerate_arrays = enumerate_arrays;
201
1946

            
202
1946
        self
203
1946
    }
204

            
205
    /// Configures whether every array should be a single line (`true`)
206
    /// or a multi line one (`false`).
207
    ///
208
    /// When `false`, `["a","b"]` will serialize to
209
    /// ```
210
    /// [
211
    ///   "a",
212
    ///   "b",
213
    /// ]
214
    /// # ;
215
    /// ```
216
    /// When `true`, `["a","b"]` will instead serialize to
217
    /// ```
218
    /// ["a","b"]
219
    /// # ;
220
    /// ```
221
    ///
222
    /// Default: `false`
223
    #[must_use]
224
1112
    pub fn compact_arrays(mut self, compact_arrays: bool) -> Self {
225
1112
        self.compact_arrays = compact_arrays;
226
1112

            
227
1112
        self
228
1112
    }
229

            
230
    /// Configures extensions
231
    ///
232
    /// Default: [`Extensions::empty()`]
233
    #[must_use]
234
11954
    pub fn extensions(mut self, extensions: Extensions) -> Self {
235
11954
        self.extensions = extensions;
236
11954

            
237
11954
        self
238
11954
    }
239

            
240
    /// Configures whether strings should be serialized using escapes (true)
241
    /// or fall back to raw strings if the string contains a `"` (false).
242
    ///
243
    /// When `true`, `"a\nb"` will serialize to
244
    /// ```
245
    /// "a\nb"
246
    /// # ;
247
    /// ```
248
    /// When `false`, `"a\nb"` will instead serialize to
249
    /// ```
250
    /// "a
251
    /// b"
252
    /// # ;
253
    /// ```
254
    ///
255
    /// Default: `true`
256
    #[must_use]
257
4170
    pub fn escape_strings(mut self, escape_strings: bool) -> Self {
258
4170
        self.escape_strings = escape_strings;
259
4170

            
260
4170
        self
261
4170
    }
262

            
263
    /// Configures whether every struct should be a single line (`true`)
264
    /// or a multi line one (`false`).
265
    ///
266
    /// When `false`, `Struct { a: 4, b: 2 }` will serialize to
267
    /// ```ignore
268
    /// Struct(
269
    ///     a: 4,
270
    ///     b: 2,
271
    /// )
272
    /// # ;
273
    /// ```
274
    /// When `true`, `Struct { a: 4, b: 2 }` will instead serialize to
275
    /// ```ignore
276
    /// Struct(a: 4, b: 2)
277
    /// # ;
278
    /// ```
279
    ///
280
    /// Default: `false`
281
    #[must_use]
282
998
    pub fn compact_structs(mut self, compact_structs: bool) -> Self {
283
998
        self.compact_structs = compact_structs;
284
998

            
285
998
        self
286
998
    }
287

            
288
    /// Configures whether every map should be a single line (`true`)
289
    /// or a multi line one (`false`).
290
    ///
291
    /// When `false`, a map with entries `{ "a": 4, "b": 2 }` will serialize to
292
    /// ```ignore
293
    /// {
294
    ///     "a": 4,
295
    ///     "b": 2,
296
    /// }
297
    /// # ;
298
    /// ```
299
    /// When `true`, a map with entries `{ "a": 4, "b": 2 }` will instead
300
    /// serialize to
301
    /// ```ignore
302
    /// {"a": 4, "b": 2}
303
    /// # ;
304
    /// ```
305
    ///
306
    /// Default: `false`
307
    #[must_use]
308
278
    pub fn compact_maps(mut self, compact_maps: bool) -> Self {
309
278
        self.compact_maps = compact_maps;
310
278

            
311
278
        self
312
278
    }
313

            
314
    /// Configures whether numbers should be printed without (`false`) or
315
    /// with (`true`) their explicit type suffixes.
316
    ///
317
    /// When `false`, the integer `12345u16` will serialize to
318
    /// ```ignore
319
    /// 12345
320
    /// # ;
321
    /// ```
322
    /// and the float `12345.6789f64` will serialize to
323
    /// ```ignore
324
    /// 12345.6789
325
    /// # ;
326
    /// ```
327
    /// When `true`, the integer `12345u16` will serialize to
328
    /// ```ignore
329
    /// 12345u16
330
    /// # ;
331
    /// ```
332
    /// and the float `12345.6789f64` will serialize to
333
    /// ```ignore
334
    /// 12345.6789f64
335
    /// # ;
336
    /// ```
337
    ///
338
    /// Default: `false`
339
    #[must_use]
340
16680
    pub fn number_suffixes(mut self, number_suffixes: bool) -> Self {
341
16680
        self.number_suffixes = number_suffixes;
342
16680

            
343
16680
        self
344
16680
    }
345
}
346

            
347
impl Default for PrettyConfig {
348
69386
    fn default() -> Self {
349
69386
        PrettyConfig {
350
69386
            depth_limit: usize::MAX,
351
69386
            new_line: if cfg!(not(target_os = "windows")) {
352
69386
                Cow::Borrowed("\n")
353
            } else {
354
                Cow::Borrowed("\r\n") // GRCOV_EXCL_LINE
355
            },
356
69386
            indentor: Cow::Borrowed("    "),
357
69386
            separator: Cow::Borrowed(" "),
358
69386
            struct_names: false,
359
69386
            separate_tuple_members: false,
360
69386
            enumerate_arrays: false,
361
69386
            extensions: Extensions::empty(),
362
69386
            compact_arrays: false,
363
69386
            escape_strings: true,
364
69386
            compact_structs: false,
365
69386
            compact_maps: false,
366
69386
            number_suffixes: false,
367
69386
            path_meta: None,
368
69386
        }
369
69386
    }
370
}
371

            
372
/// The RON serializer.
373
///
374
/// You can just use [`to_string`] for deserializing a value.
375
/// If you want it pretty-printed, take a look at [`to_string_pretty`].
376
pub struct Serializer<W: fmt::Write> {
377
    output: W,
378
    pretty: Option<(PrettyConfig, Pretty)>,
379
    default_extensions: Extensions,
380
    is_empty: Option<bool>,
381
    newtype_variant: bool,
382
    recursion_limit: Option<usize>,
383
    // Tracks the number of opened implicit `Some`s, set to 0 on backtracking
384
    implicit_some_depth: usize,
385
}
386

            
387
2176
fn indent<W: fmt::Write>(output: &mut W, config: &PrettyConfig, pretty: &Pretty) -> fmt::Result {
388
2176
    if pretty.indent <= config.depth_limit {
389
2128
        for _ in 0..pretty.indent {
390
3024
            output.write_str(&config.indentor)?;
391
        }
392
48
    }
393
2176
    Ok(())
394
2176
}
395

            
396
impl<W: fmt::Write> Serializer<W> {
397
    /// Creates a new [`Serializer`].
398
    ///
399
    /// Most of the time you can just use [`to_string`] or
400
    /// [`to_string_pretty`].
401
12
    pub fn new(writer: W, config: Option<PrettyConfig>) -> Result<Self> {
402
12
        Self::with_options(writer, config, &Options::default())
403
12
    }
404

            
405
    /// Creates a new [`Serializer`].
406
    ///
407
    /// Most of the time you can just use [`to_string`] or
408
    /// [`to_string_pretty`].
409
3820
    pub fn with_options(
410
3820
        mut writer: W,
411
3820
        config: Option<PrettyConfig>,
412
3820
        options: &Options,
413
3820
    ) -> Result<Self> {
414
3820
        if let Some(conf) = &config {
415
1756
            if !conf.new_line.chars().all(is_whitespace_char) {
416
4
                return Err(Error::Message(String::from(
417
4
                    "Invalid non-whitespace `PrettyConfig::new_line`",
418
4
                )));
419
1752
            }
420
1752
            if !conf.indentor.chars().all(is_whitespace_char) {
421
4
                return Err(Error::Message(String::from(
422
4
                    "Invalid non-whitespace `PrettyConfig::indentor`",
423
4
                )));
424
1748
            }
425
1748
            if !conf.separator.chars().all(is_whitespace_char) {
426
4
                return Err(Error::Message(String::from(
427
4
                    "Invalid non-whitespace `PrettyConfig::separator`",
428
4
                )));
429
1744
            }
430
1744

            
431
1744
            let non_default_extensions = !options.default_extensions;
432

            
433
1756
            for (extension_name, _) in (non_default_extensions & conf.extensions).iter_names() {
434
184
                write!(writer, "#![enable({})]", extension_name.to_lowercase())?;
435
184
                writer.write_str(&conf.new_line)?;
436
            }
437
2064
        };
438
3808
        Ok(Serializer {
439
3808
            output: writer,
440
3808
            pretty: config.map(|conf| (conf, Pretty { indent: 0 })),
441
3808
            default_extensions: options.default_extensions,
442
3808
            is_empty: None,
443
3808
            newtype_variant: false,
444
3808
            recursion_limit: options.recursion_limit,
445
3808
            implicit_some_depth: 0,
446
3808
        })
447
3820
    }
448

            
449
2332
    fn separate_tuple_members(&self) -> bool {
450
2332
        self.pretty
451
2332
            .as_ref()
452
2332
            .map_or(false, |(ref config, _)| config.separate_tuple_members)
453
2332
    }
454

            
455
1088
    fn compact_arrays(&self) -> bool {
456
1088
        self.pretty
457
1088
            .as_ref()
458
1088
            .map_or(false, |(ref config, _)| config.compact_arrays)
459
1088
    }
460

            
461
3770
    fn compact_structs(&self) -> bool {
462
3770
        self.pretty
463
3770
            .as_ref()
464
3770
            .map_or(false, |(ref config, _)| config.compact_structs)
465
3770
    }
466

            
467
1596
    fn compact_maps(&self) -> bool {
468
1596
        self.pretty
469
1596
            .as_ref()
470
1596
            .map_or(false, |(ref config, _)| config.compact_maps)
471
1596
    }
472

            
473
3610
    fn number_suffixes(&self) -> bool {
474
3610
        self.pretty
475
3610
            .as_ref()
476
3610
            .map_or(false, |(ref config, _)| config.number_suffixes)
477
3610
    }
478

            
479
2948
    fn extensions(&self) -> Extensions {
480
2948
        self.default_extensions
481
2948
            | self
482
2948
                .pretty
483
2948
                .as_ref()
484
2948
                .map_or(Extensions::empty(), |(ref config, _)| config.extensions)
485
2948
    }
486

            
487
1328
    fn escape_strings(&self) -> bool {
488
1328
        self.pretty
489
1328
            .as_ref()
490
1328
            .map_or(true, |(ref config, _)| config.escape_strings)
491
1328
    }
492

            
493
1692
    fn start_indent(&mut self) -> Result<()> {
494
1692
        if let Some((ref config, ref mut pretty)) = self.pretty {
495
1032
            pretty.indent += 1;
496
1032
            if pretty.indent <= config.depth_limit {
497
1008
                let is_empty = self.is_empty.unwrap_or(false);
498
1008

            
499
1008
                if !is_empty {
500
960
                    self.output.write_str(&config.new_line)?;
501
48
                }
502
24
            }
503
660
        }
504
1692
        Ok(())
505
1692
    }
506

            
507
1452
    fn indent(&mut self) -> fmt::Result {
508
1452
        if let Some((ref config, ref pretty)) = self.pretty {
509
1124
            indent(&mut self.output, config, pretty)?;
510
328
        }
511
1452
        Ok(())
512
1452
    }
513

            
514
1402
    fn end_indent(&mut self) -> fmt::Result {
515
1402
        if let Some((ref config, ref mut pretty)) = self.pretty {
516
1010
            if pretty.indent <= config.depth_limit {
517
986
                let is_empty = self.is_empty.unwrap_or(false);
518
986

            
519
986
                if !is_empty {
520
938
                    for _ in 1..pretty.indent {
521
458
                        self.output.write_str(&config.indentor)?;
522
                    }
523
48
                }
524
24
            }
525
1010
            pretty.indent -= 1;
526
1010

            
527
1010
            self.is_empty = None;
528
392
        }
529
1402
        Ok(())
530
1402
    }
531

            
532
1136
    fn serialize_escaped_str(&mut self, value: &str) -> fmt::Result {
533
1136
        self.output.write_char('"')?;
534
1136
        let mut scalar = [0u8; 4];
535
7884
        for c in value.chars().flat_map(char::escape_debug) {
536
7872
            self.output.write_str(c.encode_utf8(&mut scalar))?;
537
        }
538
1136
        self.output.write_char('"')?;
539
1136
        Ok(())
540
1136
    }
541

            
542
32
    fn serialize_unescaped_or_raw_str(&mut self, value: &str) -> fmt::Result {
543
32
        if value.contains('"') || value.contains('\\') {
544
20
            let (_, num_consecutive_hashes) =
545
44
                value.chars().fold((0, 0), |(count, max), c| match c {
546
24
                    '#' => (count + 1, max.max(count + 1)),
547
20
                    _ => (0_usize, max),
548
44
                });
549
20
            let hashes: String = "#".repeat(num_consecutive_hashes + 1);
550
20
            self.output.write_char('r')?;
551
20
            self.output.write_str(&hashes)?;
552
20
            self.output.write_char('"')?;
553
20
            self.output.write_str(value)?;
554
20
            self.output.write_char('"')?;
555
20
            self.output.write_str(&hashes)?;
556
        } else {
557
12
            self.output.write_char('"')?;
558
12
            self.output.write_str(value)?;
559
12
            self.output.write_char('"')?;
560
        }
561
32
        Ok(())
562
32
    }
563

            
564
136
    fn serialize_escaped_byte_str(&mut self, value: &[u8]) -> fmt::Result {
565
136
        self.output.write_str("b\"")?;
566
5356
        for c in value.iter().flat_map(|c| core::ascii::escape_default(*c)) {
567
5356
            self.output.write_char(char::from(c))?;
568
        }
569
136
        self.output.write_char('"')?;
570
136
        Ok(())
571
136
    }
572

            
573
24
    fn serialize_unescaped_or_raw_byte_str(&mut self, value: &str) -> fmt::Result {
574
24
        if value.contains('"') || value.contains('\\') {
575
12
            let (_, num_consecutive_hashes) =
576
16
                value.chars().fold((0, 0), |(count, max), c| match c {
577
4
                    '#' => (count + 1, max.max(count + 1)),
578
12
                    _ => (0_usize, max),
579
16
                });
580
12
            let hashes: String = "#".repeat(num_consecutive_hashes + 1);
581
12
            self.output.write_str("br")?;
582
12
            self.output.write_str(&hashes)?;
583
12
            self.output.write_char('"')?;
584
12
            self.output.write_str(value)?;
585
12
            self.output.write_char('"')?;
586
12
            self.output.write_str(&hashes)?;
587
        } else {
588
12
            self.output.write_str("b\"")?;
589
12
            self.output.write_str(value)?;
590
12
            self.output.write_char('"')?;
591
        }
592
24
        Ok(())
593
24
    }
594

            
595
1584
    fn serialize_sint(&mut self, value: impl Into<LargeSInt>, suffix: &str) -> Result<()> {
596
1584
        // TODO optimize
597
1584
        write!(self.output, "{}", value.into())?;
598

            
599
1584
        if self.number_suffixes() {
600
72
            write!(self.output, "{}", suffix)?;
601
1512
        }
602

            
603
1584
        Ok(())
604
1584
    }
605

            
606
1310
    fn serialize_uint(&mut self, value: impl Into<LargeUInt>, suffix: &str) -> Result<()> {
607
1310
        // TODO optimize
608
1310
        write!(self.output, "{}", value.into())?;
609

            
610
1310
        if self.number_suffixes() {
611
72
            write!(self.output, "{}", suffix)?;
612
1238
        }
613

            
614
1310
        Ok(())
615
1310
    }
616

            
617
2772
    fn write_identifier(&mut self, name: &str) -> Result<()> {
618
2772
        self.validate_identifier(name)?;
619
2740
        let mut chars = name.chars();
620
2740
        if !chars.next().map_or(false, is_ident_first_char)
621
2720
            || !chars.all(is_xid_continue)
622
2676
            || [
623
2676
                "true", "false", "Some", "None", "inf", "inff32", "inff64", "NaN", "NaNf32",
624
2676
                "NaNf64",
625
2676
            ]
626
2676
            .contains(&name)
627
        {
628
104
            self.output.write_str("r#")?;
629
2636
        }
630
2740
        self.output.write_str(name)?;
631
2740
        Ok(())
632
2772
    }
633

            
634
    #[allow(clippy::unused_self)]
635
4896
    fn validate_identifier(&self, name: &str) -> Result<()> {
636
4896
        if name.is_empty() || !name.chars().all(is_ident_raw_char) {
637
60
            return Err(Error::InvalidIdentifier(name.into()));
638
4836
        }
639
4836
        Ok(())
640
4896
    }
641

            
642
    /// Checks if struct names should be emitted
643
    ///
644
    /// Note that when using the `explicit_struct_names` extension, this method will use an OR operation on the extension and the [`PrettyConfig::struct_names`] option. See also [`Extensions::EXPLICIT_STRUCT_NAMES`] for the extension equivalent.
645
1400
    fn struct_names(&self) -> bool {
646
1400
        self.extensions()
647
1400
            .contains(Extensions::EXPLICIT_STRUCT_NAMES)
648
1388
            || self
649
1388
                .pretty
650
1388
                .as_ref()
651
1400
                .map_or(false, |(pc, _)| pc.struct_names)
652
1400
    }
653
}
654

            
655
macro_rules! guard_recursion {
656
    ($self:expr => $expr:expr) => {{
657
        if let Some(limit) = &mut $self.recursion_limit {
658
            if let Some(new_limit) = limit.checked_sub(1) {
659
                *limit = new_limit;
660
            } else {
661
                return Err(Error::ExceededRecursionLimit);
662
            }
663
        }
664

            
665
        let result = $expr;
666

            
667
        if let Some(limit) = &mut $self.recursion_limit {
668
            *limit = limit.saturating_add(1);
669
        }
670

            
671
        result
672
    }};
673
}
674

            
675
impl<'a, W: fmt::Write> ser::Serializer for &'a mut Serializer<W> {
676
    type Error = Error;
677
    type Ok = ();
678
    type SerializeMap = Compound<'a, W>;
679
    type SerializeSeq = Compound<'a, W>;
680
    type SerializeStruct = Compound<'a, W>;
681
    type SerializeStructVariant = Compound<'a, W>;
682
    type SerializeTuple = Compound<'a, W>;
683
    type SerializeTupleStruct = Compound<'a, W>;
684
    type SerializeTupleVariant = Compound<'a, W>;
685

            
686
368
    fn serialize_bool(self, v: bool) -> Result<()> {
687
368
        self.output.write_str(if v { "true" } else { "false" })?;
688
368
        Ok(())
689
368
    }
690

            
691
136
    fn serialize_i8(self, v: i8) -> Result<()> {
692
136
        self.serialize_sint(v, "i8")
693
136
    }
694

            
695
84
    fn serialize_i16(self, v: i16) -> Result<()> {
696
84
        self.serialize_sint(v, "i16")
697
84
    }
698

            
699
1220
    fn serialize_i32(self, v: i32) -> Result<()> {
700
1220
        self.serialize_sint(v, "i32")
701
1220
    }
702

            
703
92
    fn serialize_i64(self, v: i64) -> Result<()> {
704
92
        self.serialize_sint(v, "i64")
705
92
    }
706

            
707
    #[cfg(feature = "integer128")]
708
52
    fn serialize_i128(self, v: i128) -> Result<()> {
709
52
        self.serialize_sint(v, "i128")
710
52
    }
711

            
712
612
    fn serialize_u8(self, v: u8) -> Result<()> {
713
612
        self.serialize_uint(v, "u8")
714
612
    }
715

            
716
84
    fn serialize_u16(self, v: u16) -> Result<()> {
717
84
        self.serialize_uint(v, "u16")
718
84
    }
719

            
720
444
    fn serialize_u32(self, v: u32) -> Result<()> {
721
444
        self.serialize_uint(v, "u32")
722
444
    }
723

            
724
120
    fn serialize_u64(self, v: u64) -> Result<()> {
725
120
        self.serialize_uint(v, "u64")
726
120
    }
727

            
728
    #[cfg(feature = "integer128")]
729
50
    fn serialize_u128(self, v: u128) -> Result<()> {
730
50
        self.serialize_uint(v, "u128")
731
50
    }
732

            
733
492
    fn serialize_f32(self, v: f32) -> Result<()> {
734
492
        if v.is_nan() && v.is_sign_negative() {
735
40
            write!(self.output, "-")?;
736
452
        }
737

            
738
492
        write!(self.output, "{}", v)?;
739

            
740
        // Equivalent to v.fract() == 0.0
741
        // See: https://docs.rs/num-traits/0.2.19/src/num_traits/float.rs.html#459-465
742
492
        if v % 1. == 0.0 {
743
260
            write!(self.output, ".0")?;
744
232
        }
745

            
746
492
        if self.number_suffixes() {
747
48
            write!(self.output, "f32")?;
748
444
        }
749

            
750
492
        Ok(())
751
492
    }
752

            
753
224
    fn serialize_f64(self, v: f64) -> Result<()> {
754
224
        if v.is_nan() && v.is_sign_negative() {
755
8
            write!(self.output, "-")?;
756
216
        }
757

            
758
224
        write!(self.output, "{}", v)?;
759

            
760
        // Equivalent to v.fract() == 0.0
761
        // See: https://docs.rs/num-traits/0.2.19/src/num_traits/float.rs.html#459-465
762
224
        if v % 1. == 0.0 {
763
124
            write!(self.output, ".0")?;
764
100
        }
765

            
766
224
        if self.number_suffixes() {
767
48
            write!(self.output, "f64")?;
768
176
        }
769

            
770
224
        Ok(())
771
224
    }
772

            
773
672
    fn serialize_char(self, v: char) -> Result<()> {
774
672
        self.output.write_char('\'')?;
775
672
        if v == '\\' || v == '\'' {
776
32
            self.output.write_char('\\')?;
777
640
        }
778
672
        write!(self.output, "{}", v)?;
779
672
        self.output.write_char('\'')?;
780
672
        Ok(())
781
672
    }
782

            
783
1168
    fn serialize_str(self, v: &str) -> Result<()> {
784
1168
        if self.escape_strings() {
785
1136
            self.serialize_escaped_str(v)?;
786
        } else {
787
32
            self.serialize_unescaped_or_raw_str(v)?;
788
        }
789

            
790
1168
        Ok(())
791
1168
    }
792

            
793
160
    fn serialize_bytes(self, v: &[u8]) -> Result<()> {
794
160
        // We need to fall back to escaping if the byte string would be invalid UTF-8
795
160
        if !self.escape_strings() {
796
28
            if let Ok(v) = core::str::from_utf8(v) {
797
24
                return self
798
24
                    .serialize_unescaped_or_raw_byte_str(v)
799
24
                    .map_err(Error::from);
800
4
            }
801
132
        }
802

            
803
136
        self.serialize_escaped_byte_str(v)?;
804

            
805
136
        Ok(())
806
160
    }
807

            
808
76
    fn serialize_none(self) -> Result<()> {
809
76
        // We no longer need to keep track of the depth
810
76
        let implicit_some_depth = self.implicit_some_depth;
811
76
        self.implicit_some_depth = 0;
812
76

            
813
76
        for _ in 0..implicit_some_depth {
814
12
            self.output.write_str("Some(")?;
815
        }
816
76
        self.output.write_str("None")?;
817
76
        for _ in 0..implicit_some_depth {
818
12
            self.output.write_char(')')?;
819
        }
820

            
821
76
        Ok(())
822
76
    }
823

            
824
532
    fn serialize_some<T>(self, value: &T) -> Result<()>
825
532
    where
826
532
        T: ?Sized + Serialize,
827
532
    {
828
532
        let implicit_some = self.extensions().contains(Extensions::IMPLICIT_SOME);
829
532
        if implicit_some {
830
120
            self.implicit_some_depth += 1;
831
120
        } else {
832
412
            self.newtype_variant = self
833
412
                .extensions()
834
412
                .contains(Extensions::UNWRAP_VARIANT_NEWTYPES);
835
412
            self.output.write_str("Some(")?;
836
        }
837
532
        guard_recursion! { self => value.serialize(&mut *self)? };
838
276
        if implicit_some {
839
120
            self.implicit_some_depth = 0;
840
120
        } else {
841
156
            self.output.write_char(')')?;
842
156
            self.newtype_variant = false;
843
        }
844

            
845
276
        Ok(())
846
532
    }
847

            
848
224
    fn serialize_unit(self) -> Result<()> {
849
224
        if !self.newtype_variant {
850
220
            self.output.write_str("()")?;
851
4
        }
852

            
853
224
        Ok(())
854
224
    }
855

            
856
88
    fn serialize_unit_struct(self, name: &'static str) -> Result<()> {
857
88
        if self.struct_names() && !self.newtype_variant {
858
16
            self.write_identifier(name)?;
859

            
860
8
            Ok(())
861
        } else {
862
72
            self.validate_identifier(name)?;
863
72
            self.serialize_unit()
864
        }
865
88
    }
866

            
867
240
    fn serialize_unit_variant(
868
240
        self,
869
240
        name: &'static str,
870
240
        _variant_index: u32,
871
240
        variant: &'static str,
872
240
    ) -> Result<()> {
873
240
        self.validate_identifier(name)?;
874
236
        self.write_identifier(variant)?;
875

            
876
232
        Ok(())
877
240
    }
878

            
879
444
    fn serialize_newtype_struct<T>(self, name: &'static str, value: &T) -> Result<()>
880
444
    where
881
444
        T: ?Sized + Serialize,
882
444
    {
883
444
        if name == crate::value::raw::RAW_VALUE_TOKEN {
884
196
            let implicit_some_depth = self.implicit_some_depth;
885
196
            self.implicit_some_depth = 0;
886
196

            
887
196
            for _ in 0..implicit_some_depth {
888
8
                self.output.write_str("Some(")?;
889
            }
890

            
891
196
            guard_recursion! { self => value.serialize(raw::Serializer::new(self)) }?;
892

            
893
84
            for _ in 0..implicit_some_depth {
894
8
                self.output.write_char(')')?;
895
            }
896

            
897
84
            return Ok(());
898
248
        }
899
248

            
900
248
        if self.extensions().contains(Extensions::UNWRAP_NEWTYPES) || self.newtype_variant {
901
40
            self.newtype_variant = false;
902
40

            
903
40
            self.validate_identifier(name)?;
904

            
905
40
            return guard_recursion! { self => value.serialize(&mut *self) };
906
208
        }
907
208

            
908
208
        if self.struct_names() {
909
12
            self.write_identifier(name)?;
910
        } else {
911
196
            self.validate_identifier(name)?;
912
        }
913

            
914
204
        self.implicit_some_depth = 0;
915
204

            
916
204
        self.output.write_char('(')?;
917
204
        guard_recursion! { self => value.serialize(&mut *self)? };
918
204
        self.output.write_char(')')?;
919

            
920
204
        Ok(())
921
444
    }
922

            
923
364
    fn serialize_newtype_variant<T>(
924
364
        self,
925
364
        name: &'static str,
926
364
        _variant_index: u32,
927
364
        variant: &'static str,
928
364
        value: &T,
929
364
    ) -> Result<()>
930
364
    where
931
364
        T: ?Sized + Serialize,
932
364
    {
933
364
        self.validate_identifier(name)?;
934
360
        self.write_identifier(variant)?;
935
356
        self.output.write_char('(')?;
936

            
937
356
        self.newtype_variant = self
938
356
            .extensions()
939
356
            .contains(Extensions::UNWRAP_VARIANT_NEWTYPES);
940
356
        self.implicit_some_depth = 0;
941
356

            
942
356
        guard_recursion! { self => value.serialize(&mut *self)? };
943

            
944
354
        self.newtype_variant = false;
945
354

            
946
354
        self.output.write_char(')')?;
947
354
        Ok(())
948
364
    }
949

            
950
240
    fn serialize_seq(self, len: Option<usize>) -> Result<Self::SerializeSeq> {
951
240
        self.newtype_variant = false;
952
240
        self.implicit_some_depth = 0;
953
240

            
954
240
        self.output.write_char('[')?;
955

            
956
240
        if !self.compact_arrays() {
957
212
            if let Some(len) = len {
958
212
                self.is_empty = Some(len == 0);
959
212
            }
960

            
961
212
            self.start_indent()?;
962
28
        }
963

            
964
240
        Ok(Compound::new(self, false))
965
240
    }
966

            
967
352
    fn serialize_tuple(self, len: usize) -> Result<Self::SerializeTuple> {
968
352
        let old_newtype_variant = self.newtype_variant;
969
352
        self.newtype_variant = false;
970
352
        self.implicit_some_depth = 0;
971
352

            
972
352
        if !old_newtype_variant {
973
324
            self.output.write_char('(')?;
974
28
        }
975

            
976
352
        if self.separate_tuple_members() {
977
32
            self.is_empty = Some(len == 0);
978
32

            
979
32
            self.start_indent()?;
980
320
        }
981

            
982
352
        Ok(Compound::new(self, old_newtype_variant))
983
352
    }
984

            
985
104
    fn serialize_tuple_struct(
986
104
        self,
987
104
        name: &'static str,
988
104
        len: usize,
989
104
    ) -> Result<Self::SerializeTupleStruct> {
990
104
        if self.struct_names() && !self.newtype_variant {
991
20
            self.write_identifier(name)?;
992
        } else {
993
84
            self.validate_identifier(name)?;
994
        }
995

            
996
100
        self.serialize_tuple(len)
997
104
    }
998

            
999
100
    fn serialize_tuple_variant(
100
        self,
100
        name: &'static str,
100
        _variant_index: u32,
100
        variant: &'static str,
100
        len: usize,
100
    ) -> Result<Self::SerializeTupleVariant> {
100
        self.newtype_variant = false;
100
        self.implicit_some_depth = 0;
100

            
100
        self.validate_identifier(name)?;
96
        self.write_identifier(variant)?;
92
        self.output.write_char('(')?;
92
        if self.separate_tuple_members() {
8
            self.is_empty = Some(len == 0);
8

            
8
            self.start_indent()?;
84
        }
92
        Ok(Compound::new(self, false))
100
    }
384
    fn serialize_map(self, len: Option<usize>) -> Result<Self::SerializeMap> {
384
        self.newtype_variant = false;
384
        self.implicit_some_depth = 0;
384

            
384
        self.output.write_char('{')?;
384
        if !self.compact_maps() {
380
            if let Some(len) = len {
120
                self.is_empty = Some(len == 0);
364
            }
380
            self.start_indent()?;
4
        }
384
        Ok(Compound::new(self, false))
384
    }
1016
    fn serialize_struct(self, name: &'static str, len: usize) -> Result<Self::SerializeStruct> {
1016
        let old_newtype_variant = self.newtype_variant;
1016
        self.newtype_variant = false;
1016
        self.implicit_some_depth = 0;
1016

            
1016
        if old_newtype_variant {
16
            self.validate_identifier(name)?;
        } else {
1000
            if self.struct_names() {
72
                self.write_identifier(name)?;
            } else {
928
                self.validate_identifier(name)?;
            }
996
            self.output.write_char('(')?;
        }
1012
        if !self.compact_structs() {
992
            self.is_empty = Some(len == 0);
992
            self.start_indent()?;
20
        }
1012
        Ok(Compound::new(self, old_newtype_variant))
1016
    }
84
    fn serialize_struct_variant(
84
        self,
84
        name: &'static str,
84
        _variant_index: u32,
84
        variant: &'static str,
84
        len: usize,
84
    ) -> Result<Self::SerializeStructVariant> {
84
        self.newtype_variant = false;
84
        self.implicit_some_depth = 0;
84

            
84
        self.validate_identifier(name)?;
80
        self.write_identifier(variant)?;
76
        self.output.write_char('(')?;
76
        if !self.compact_structs() {
68
            self.is_empty = Some(len == 0);
68
            self.start_indent()?;
8
        }
76
        Ok(Compound::new(self, false))
84
    }
}
enum State {
    First,
    Rest,
}
#[doc(hidden)]
pub struct Compound<'a, W: fmt::Write> {
    ser: &'a mut Serializer<W>,
    state: State,
    newtype_variant: bool,
    sequence_index: usize,
}
impl<'a, W: fmt::Write> Compound<'a, W> {
2156
    fn new(ser: &'a mut Serializer<W>, newtype_variant: bool) -> Self {
2156
        Compound {
2156
            ser,
2156
            state: State::First,
2156
            newtype_variant,
2156
            sequence_index: 0,
2156
        }
2156
    }
}
impl<'a, W: fmt::Write> Drop for Compound<'a, W> {
2156
    fn drop(&mut self) {
2156
        if let Some(limit) = &mut self.ser.recursion_limit {
2144
            *limit = limit.saturating_add(1);
2144
        }
2156
    }
}
impl<'a, W: fmt::Write> ser::SerializeSeq for Compound<'a, W> {
    type Error = Error;
    type Ok = ();
608
    fn serialize_element<T>(&mut self, value: &T) -> Result<()>
608
    where
608
        T: ?Sized + Serialize,
608
    {
608
        if let State::First = self.state {
204
            self.state = State::Rest;
204
        } else {
404
            self.ser.output.write_char(',')?;
404
            if let Some((ref config, ref mut pretty)) = self.ser.pretty {
224
                if pretty.indent <= config.depth_limit && !config.compact_arrays {
176
                    self.ser.output.write_str(&config.new_line)?;
                } else {
48
                    self.ser.output.write_str(&config.separator)?;
                }
180
            }
        }
608
        if !self.ser.compact_arrays() {
544
            self.ser.indent()?;
64
        }
608
        if let Some((ref mut config, ref mut pretty)) = self.ser.pretty {
348
            if pretty.indent <= config.depth_limit && config.enumerate_arrays {
72
                write!(self.ser.output, "/*[{}]*/ ", self.sequence_index)?;
72
                self.sequence_index += 1;
276
            }
260
        }
608
        guard_recursion! { self.ser => value.serialize(&mut *self.ser)? };
608
        Ok(())
608
    }
240
    fn end(self) -> Result<()> {
240
        if let State::Rest = self.state {
204
            if let Some((ref config, ref mut pretty)) = self.ser.pretty {
124
                if pretty.indent <= config.depth_limit && !config.compact_arrays {
96
                    self.ser.output.write_char(',')?;
96
                    self.ser.output.write_str(&config.new_line)?;
28
                }
80
            }
36
        }
240
        if !self.ser.compact_arrays() {
212
            self.ser.end_indent()?;
28
        }
        // seq always disables `self.newtype_variant`
240
        self.ser.output.write_char(']')?;
240
        Ok(())
240
    }
}
impl<'a, W: fmt::Write> ser::SerializeTuple for Compound<'a, W> {
    type Error = Error;
    type Ok = ();
952
    fn serialize_element<T>(&mut self, value: &T) -> Result<()>
952
    where
952
        T: ?Sized + Serialize,
952
    {
952
        if let State::First = self.state {
396
            self.state = State::Rest;
396
        } else {
556
            self.ser.output.write_char(',')?;
556
            if let Some((ref config, ref pretty)) = self.ser.pretty {
292
                if pretty.indent <= config.depth_limit && self.ser.separate_tuple_members() {
32
                    self.ser.output.write_str(&config.new_line)?;
                } else {
260
                    self.ser.output.write_str(&config.separator)?;
                }
264
            }
        }
952
        if self.ser.separate_tuple_members() {
84
            self.ser.indent()?;
868
        }
952
        guard_recursion! { self.ser => value.serialize(&mut *self.ser)? };
940
        Ok(())
952
    }
432
    fn end(self) -> Result<()> {
432
        if let State::Rest = self.state {
384
            if let Some((ref config, ref pretty)) = self.ser.pretty {
224
                if self.ser.separate_tuple_members() && pretty.indent <= config.depth_limit {
28
                    self.ser.output.write_char(',')?;
28
                    self.ser.output.write_str(&config.new_line)?;
196
                }
160
            }
48
        }
432
        if self.ser.separate_tuple_members() {
40
            self.ser.end_indent()?;
392
        }
432
        if !self.newtype_variant {
404
            self.ser.output.write_char(')')?;
28
        }
432
        Ok(())
432
    }
}
// Same thing but for tuple structs.
impl<'a, W: fmt::Write> ser::SerializeTupleStruct for Compound<'a, W> {
    type Error = Error;
    type Ok = ();
168
    fn serialize_field<T>(&mut self, value: &T) -> Result<()>
168
    where
168
        T: ?Sized + Serialize,
168
    {
168
        ser::SerializeTuple::serialize_element(self, value)
168
    }
100
    fn end(self) -> Result<()> {
100
        ser::SerializeTuple::end(self)
100
    }
}
impl<'a, W: fmt::Write> ser::SerializeTupleVariant for Compound<'a, W> {
    type Error = Error;
    type Ok = ();
156
    fn serialize_field<T>(&mut self, value: &T) -> Result<()>
156
    where
156
        T: ?Sized + Serialize,
156
    {
156
        ser::SerializeTuple::serialize_element(self, value)
156
    }
92
    fn end(self) -> Result<()> {
92
        ser::SerializeTuple::end(self)
92
    }
}
impl<'a, W: fmt::Write> ser::SerializeMap for Compound<'a, W> {
    type Error = Error;
    type Ok = ();
832
    fn serialize_key<T>(&mut self, key: &T) -> Result<()>
832
    where
832
        T: ?Sized + Serialize,
832
    {
832
        if let State::First = self.state {
360
            self.state = State::Rest;
360
        } else {
472
            self.ser.output.write_char(',')?;
472
            if let Some((ref config, ref pretty)) = self.ser.pretty {
432
                if pretty.indent <= config.depth_limit && !config.compact_maps {
428
                    self.ser.output.write_str(&config.new_line)?;
                } else {
4
                    self.ser.output.write_str(&config.separator)?;
                }
40
            }
        }
832
        if !self.ser.compact_maps() {
824
            self.ser.indent()?;
8
        }
832
        guard_recursion! { self.ser => key.serialize(&mut *self.ser) }
832
    }
832
    fn serialize_value<T>(&mut self, value: &T) -> Result<()>
832
    where
832
        T: ?Sized + Serialize,
832
    {
832
        self.ser.output.write_char(':')?;
832
        if let Some((ref config, _)) = self.ser.pretty {
764
            self.ser.output.write_str(&config.separator)?;
68
        }
832
        guard_recursion! { self.ser => value.serialize(&mut *self.ser)? };
828
        Ok(())
832
    }
380
    fn end(self) -> Result<()> {
380
        if let State::Rest = self.state {
356
            if let Some((ref config, ref pretty)) = self.ser.pretty {
328
                if pretty.indent <= config.depth_limit && !config.compact_maps {
320
                    self.ser.output.write_char(',')?;
320
                    self.ser.output.write_str(&config.new_line)?;
8
                }
28
            }
24
        }
380
        if !self.ser.compact_maps() {
376
            self.ser.end_indent()?;
4
        }
        // map always disables `self.newtype_variant`
380
        self.ser.output.write_char('}')?;
380
        Ok(())
380
    }
}
impl<'a, W: fmt::Write> ser::SerializeStruct for Compound<'a, W> {
    type Error = Error;
    type Ok = ();
1880
    fn serialize_field<T>(&mut self, key: &'static str, value: &T) -> Result<()>
1880
    where
1880
        T: ?Sized + Serialize,
1880
    {
1880
        let mut restore_field = self.ser.pretty.as_mut().and_then(|(config, _)| {
1028
            config.path_meta.take().map(|mut field| {
60
                if let Some(fields) = field.fields_mut() {
60
                    config.path_meta = fields.remove(key);
60
                }
60
                field
1028
            })
1880
        });
1880

            
1880
        if let State::First = self.state {
1060
            self.state = State::Rest;
1060
        } else {
820
            self.ser.output.write_char(',')?;
820
            if let Some((ref config, ref pretty)) = self.ser.pretty {
496
                if pretty.indent <= config.depth_limit && !config.compact_structs {
472
                    self.ser.output.write_str(&config.new_line)?;
                } else {
24
                    self.ser.output.write_str(&config.separator)?;
                }
324
            }
        }
1880
        if !self.ser.compact_structs() {
1840
            if let Some((ref config, ref pretty)) = self.ser.pretty {
988
                indent(&mut self.ser.output, config, pretty)?;
988
                if let Some(ref field) = config.path_meta {
64
                    for doc_line in field.doc().lines() {
64
                        self.ser.output.write_str("/// ")?;
64
                        self.ser.output.write_str(doc_line)?;
64
                        self.ser.output.write_char('\n')?;
64
                        indent(&mut self.ser.output, config, pretty)?;
                    }
944
                }
852
            }
40
        }
1880
        self.ser.write_identifier(key)?;
1872
        self.ser.output.write_char(':')?;
1872
        if let Some((ref config, _)) = self.ser.pretty {
1028
            self.ser.output.write_str(&config.separator)?;
844
        }
1872
        guard_recursion! { self.ser => value.serialize(&mut *self.ser)? };
1594
        if let Some((ref mut config, _)) = self.ser.pretty {
1010
            core::mem::swap(&mut config.path_meta, &mut restore_field);
1010
            if let Some(ref mut field) = config.path_meta {
60
                if let Some(fields) = field.fields_mut() {
60
                    if let Some(restore_field) = restore_field {
44
                        fields.insert(key, restore_field);
44
                    }
                }
950
            }
584
        };
1594
        Ok(())
1880
    }
802
    fn end(self) -> Result<()> {
802
        if let State::Rest = self.state {
774
            if let Some((ref config, ref pretty)) = self.ser.pretty {
514
                if pretty.indent <= config.depth_limit && !config.compact_structs {
490
                    self.ser.output.write_char(',')?;
490
                    self.ser.output.write_str(&config.new_line)?;
24
                }
260
            }
28
        }
802
        if !self.ser.compact_structs() {
774
            self.ser.end_indent()?;
28
        }
802
        if !self.newtype_variant {
786
            self.ser.output.write_char(')')?;
16
        }
802
        Ok(())
802
    }
}
impl<'a, W: fmt::Write> ser::SerializeStructVariant for Compound<'a, W> {
    type Error = Error;
    type Ok = ();
152
    fn serialize_field<T>(&mut self, key: &'static str, value: &T) -> Result<()>
152
    where
152
        T: ?Sized + Serialize,
152
    {
152
        ser::SerializeStruct::serialize_field(self, key, value)
152
    }
72
    fn end(self) -> Result<()> {
72
        ser::SerializeStruct::end(self)
72
    }
}