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
///
27
/// `writer` is required to implement [`core::fmt::Write`]. To use [`std::io::Write`] instead,
28
/// see [`Options::to_io_writer`](crate::options::Options::to_io_writer).
29
360
pub fn to_writer<W, T>(writer: W, value: &T) -> Result<()>
30
360
where
31
360
    W: fmt::Write,
32
360
    T: ?Sized + Serialize,
33
{
34
360
    Options::default().to_writer(writer, value)
35
360
}
36

            
37
/// Serializes `value` into `writer` in a pretty way.
38
///
39
/// `writer` is required to implement [`core::fmt::Write`]. To use [`std::io::Write`] instead,
40
/// see [`Options::to_io_writer_pretty`](crate::options::Options::to_io_writer_pretty).
41
360
pub fn to_writer_pretty<W, T>(writer: W, value: &T, config: PrettyConfig) -> Result<()>
42
360
where
43
360
    W: fmt::Write,
44
360
    T: ?Sized + Serialize,
45
{
46
360
    Options::default().to_writer_pretty(writer, value, config)
47
360
}
48

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

            
60
/// Serializes `value` in the recommended RON layout in a pretty way.
61
1392
pub fn to_string_pretty<T>(value: &T, config: PrettyConfig) -> Result<String>
62
1392
where
63
1392
    T: ?Sized + Serialize,
64
{
65
1392
    Options::default().to_string_pretty(value, config)
66
1392
}
67

            
68
/// Pretty serializer state
69
struct Pretty {
70
    indent: usize,
71
}
72

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

            
125
impl PrettyConfig {
126
    /// Creates a default [`PrettyConfig`].
127
    #[must_use]
128
4170
    pub fn new() -> Self {
129
4170
        Self::default()
130
4170
    }
131

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

            
142
834
        self
143
834
    }
144

            
145
    /// Configures the newlines used for serialization.
146
    ///
147
    /// Default: `\r\n` on Windows, `\n` otherwise
148
    #[must_use]
149
36
    pub fn new_line(mut self, new_line: impl Into<Cow<'static, str>>) -> Self {
150
36
        self.new_line = new_line.into();
151

            
152
36
        self
153
36
    }
154

            
155
    /// Configures the string sequence used for indentation.
156
    ///
157
    /// Default: 4 spaces
158
    #[must_use]
159
4
    pub fn indentor(mut self, indentor: impl Into<Cow<'static, str>>) -> Self {
160
4
        self.indentor = indentor.into();
161

            
162
4
        self
163
4
    }
164

            
165
    /// Configures the string sequence used to separate items inline.
166
    ///
167
    /// Default: 1 space
168
    #[must_use]
169
8
    pub fn separator(mut self, separator: impl Into<Cow<'static, str>>) -> Self {
170
8
        self.separator = separator.into();
171

            
172
8
        self
173
8
    }
174

            
175
    /// Configures whether to emit struct names.
176
    ///
177
    /// See also [`Extensions::EXPLICIT_STRUCT_NAMES`] for the extension equivalent.
178
    ///
179
    /// Default: `false`
180
    #[must_use]
181
4334
    pub fn struct_names(mut self, struct_names: bool) -> Self {
182
4334
        self.struct_names = struct_names;
183

            
184
4334
        self
185
4334
    }
186

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

            
197
1390
        self
198
1390
    }
199

            
200
    /// Configures whether a comment shall be added to every array element,
201
    /// indicating the index.
202
    ///
203
    /// Default: `false`
204
    #[must_use]
205
1946
    pub fn enumerate_arrays(mut self, enumerate_arrays: bool) -> Self {
206
1946
        self.enumerate_arrays = enumerate_arrays;
207

            
208
1946
        self
209
1946
    }
210

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

            
233
1112
        self
234
1112
    }
235

            
236
    /// Configures extensions
237
    ///
238
    /// Default: [`Extensions::empty()`]
239
    #[must_use]
240
11954
    pub fn extensions(mut self, extensions: Extensions) -> Self {
241
11954
        self.extensions = extensions;
242

            
243
11954
        self
244
11954
    }
245

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

            
266
4170
        self
267
4170
    }
268

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

            
291
998
        self
292
998
    }
293

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

            
317
278
        self
318
278
    }
319

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

            
349
16680
        self
350
16680
    }
351
}
352

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

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

            
393
2176
fn indent<W: fmt::Write>(output: &mut W, config: &PrettyConfig, pretty: &Pretty) -> fmt::Result {
394
2176
    if pretty.indent <= config.depth_limit {
395
2128
        for _ in 0..pretty.indent {
396
3024
            output.write_str(&config.indentor)?;
397
        }
398
48
    }
399
2176
    Ok(())
400
2176
}
401

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

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

            
437
1744
            let non_default_extensions = !options.default_extensions;
438

            
439
1756
            for (extension_name, _) in (non_default_extensions & conf.extensions).iter_names() {
440
184
                write!(writer, "#![enable({})]", extension_name.to_lowercase())?;
441
184
                writer.write_str(&conf.new_line)?;
442
            }
443
2068
        };
444
        Ok(Serializer {
445
3812
            output: writer,
446
3812
            pretty: config.map(|conf| (conf, Pretty { indent: 0 })),
447
3812
            default_extensions: options.default_extensions,
448
3812
            is_empty: None,
449
            newtype_variant: false,
450
3812
            recursion_limit: options.recursion_limit,
451
            implicit_some_depth: 0,
452
        })
453
3824
    }
454

            
455
    /// Unwrap the `Writer` from the `Serializer`.
456
    #[inline]
457
    pub fn into_inner(self) -> W {
458
        self.output
459
    }
460

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

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

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

            
479
1596
    fn compact_maps(&self) -> bool {
480
1596
        self.pretty
481
1596
            .as_ref()
482
1596
            .map_or(false, |(ref config, _)| config.compact_maps)
483
1596
    }
484

            
485
3614
    fn number_suffixes(&self) -> bool {
486
3614
        self.pretty
487
3614
            .as_ref()
488
3614
            .map_or(false, |(ref config, _)| config.number_suffixes)
489
3614
    }
490

            
491
2952
    fn extensions(&self) -> Extensions {
492
2952
        self.default_extensions
493
2952
            | self
494
2952
                .pretty
495
2952
                .as_ref()
496
2952
                .map_or(Extensions::empty(), |(ref config, _)| config.extensions)
497
2952
    }
498

            
499
1336
    fn escape_strings(&self) -> bool {
500
1336
        self.pretty
501
1336
            .as_ref()
502
1336
            .map_or(true, |(ref config, _)| config.escape_strings)
503
1336
    }
504

            
505
1696
    fn start_indent(&mut self) -> Result<()> {
506
1696
        if let Some((ref config, ref mut pretty)) = self.pretty {
507
1032
            pretty.indent += 1;
508
1032
            if pretty.indent <= config.depth_limit {
509
1008
                let is_empty = self.is_empty.unwrap_or(false);
510

            
511
1008
                if !is_empty {
512
960
                    self.output.write_str(&config.new_line)?;
513
48
                }
514
24
            }
515
664
        }
516
1696
        Ok(())
517
1696
    }
518

            
519
1452
    fn indent(&mut self) -> fmt::Result {
520
1452
        if let Some((ref config, ref pretty)) = self.pretty {
521
1124
            indent(&mut self.output, config, pretty)?;
522
328
        }
523
1452
        Ok(())
524
1452
    }
525

            
526
1406
    fn end_indent(&mut self) -> fmt::Result {
527
1406
        if let Some((ref config, ref mut pretty)) = self.pretty {
528
1010
            if pretty.indent <= config.depth_limit {
529
986
                let is_empty = self.is_empty.unwrap_or(false);
530

            
531
986
                if !is_empty {
532
938
                    for _ in 1..pretty.indent {
533
458
                        self.output.write_str(&config.indentor)?;
534
                    }
535
48
                }
536
24
            }
537
1010
            pretty.indent -= 1;
538

            
539
1010
            self.is_empty = None;
540
396
        }
541
1406
        Ok(())
542
1406
    }
543

            
544
1144
    fn serialize_escaped_str(&mut self, value: &str) -> fmt::Result {
545
1144
        self.output.write_char('"')?;
546
1144
        let mut scalar = [0u8; 4];
547
7940
        for c in value.chars().flat_map(char::escape_debug) {
548
7928
            self.output.write_str(c.encode_utf8(&mut scalar))?;
549
        }
550
1144
        self.output.write_char('"')?;
551
1144
        Ok(())
552
1144
    }
553

            
554
32
    fn serialize_unescaped_or_raw_str(&mut self, value: &str) -> fmt::Result {
555
32
        if value.contains('"') || value.contains('\\') {
556
20
            let (_, num_consecutive_hashes) =
557
44
                value.chars().fold((0, 0), |(count, max), c| match c {
558
24
                    '#' => (count + 1, max.max(count + 1)),
559
20
                    _ => (0_usize, max),
560
44
                });
561
20
            let hashes: String = "#".repeat(num_consecutive_hashes + 1);
562
20
            self.output.write_char('r')?;
563
20
            self.output.write_str(&hashes)?;
564
20
            self.output.write_char('"')?;
565
20
            self.output.write_str(value)?;
566
20
            self.output.write_char('"')?;
567
20
            self.output.write_str(&hashes)?;
568
        } else {
569
12
            self.output.write_char('"')?;
570
12
            self.output.write_str(value)?;
571
12
            self.output.write_char('"')?;
572
        }
573
32
        Ok(())
574
32
    }
575

            
576
136
    fn serialize_escaped_byte_str(&mut self, value: &[u8]) -> fmt::Result {
577
136
        self.output.write_str("b\"")?;
578
5356
        for c in value.iter().flat_map(|c| core::ascii::escape_default(*c)) {
579
5356
            self.output.write_char(char::from(c))?;
580
        }
581
136
        self.output.write_char('"')?;
582
136
        Ok(())
583
136
    }
584

            
585
24
    fn serialize_unescaped_or_raw_byte_str(&mut self, value: &str) -> fmt::Result {
586
24
        if value.contains('"') || value.contains('\\') {
587
12
            let (_, num_consecutive_hashes) =
588
16
                value.chars().fold((0, 0), |(count, max), c| match c {
589
4
                    '#' => (count + 1, max.max(count + 1)),
590
12
                    _ => (0_usize, max),
591
16
                });
592
12
            let hashes: String = "#".repeat(num_consecutive_hashes + 1);
593
12
            self.output.write_str("br")?;
594
12
            self.output.write_str(&hashes)?;
595
12
            self.output.write_char('"')?;
596
12
            self.output.write_str(value)?;
597
12
            self.output.write_char('"')?;
598
12
            self.output.write_str(&hashes)?;
599
        } else {
600
12
            self.output.write_str("b\"")?;
601
12
            self.output.write_str(value)?;
602
12
            self.output.write_char('"')?;
603
        }
604
24
        Ok(())
605
24
    }
606

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

            
611
1584
        if self.number_suffixes() {
612
72
            write!(self.output, "{}", suffix)?;
613
1512
        }
614

            
615
1584
        Ok(())
616
1584
    }
617

            
618
1314
    fn serialize_uint(&mut self, value: impl Into<LargeUInt>, suffix: &str) -> Result<()> {
619
        // TODO optimize
620
1314
        write!(self.output, "{}", value.into())?;
621

            
622
1314
        if self.number_suffixes() {
623
72
            write!(self.output, "{}", suffix)?;
624
1242
        }
625

            
626
1314
        Ok(())
627
1314
    }
628

            
629
2784
    fn write_identifier(&mut self, name: &str) -> Result<()> {
630
2784
        self.validate_identifier(name)?;
631
2752
        let mut chars = name.chars();
632
2752
        if !chars.next().map_or(false, is_ident_first_char)
633
2732
            || !chars.all(is_xid_continue)
634
2688
            || [
635
2688
                "true", "false", "Some", "None", "inf", "inff32", "inff64", "NaN", "NaNf32",
636
2688
                "NaNf64",
637
2688
            ]
638
2688
            .contains(&name)
639
        {
640
104
            self.output.write_str("r#")?;
641
2648
        }
642
2752
        self.output.write_str(name)?;
643
2752
        Ok(())
644
2784
    }
645

            
646
    #[allow(clippy::unused_self)]
647
4912
    fn validate_identifier(&self, name: &str) -> Result<()> {
648
4912
        if name.is_empty() || !name.chars().all(is_ident_raw_char) {
649
60
            return Err(Error::InvalidIdentifier(name.into()));
650
4852
        }
651
4852
        Ok(())
652
4912
    }
653

            
654
    /// Checks if struct names should be emitted
655
    ///
656
    /// 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.
657
1404
    fn struct_names(&self) -> bool {
658
1404
        self.extensions()
659
1404
            .contains(Extensions::EXPLICIT_STRUCT_NAMES)
660
1392
            || self
661
1392
                .pretty
662
1392
                .as_ref()
663
1392
                .map_or(false, |(pc, _)| pc.struct_names)
664
1404
    }
665
}
666

            
667
macro_rules! guard_recursion {
668
    ($self:expr => $expr:expr) => {{
669
        if let Some(limit) = &mut $self.recursion_limit {
670
            if let Some(new_limit) = limit.checked_sub(1) {
671
                *limit = new_limit;
672
            } else {
673
                return Err(Error::ExceededRecursionLimit);
674
            }
675
        }
676

            
677
        let result = $expr;
678

            
679
        if let Some(limit) = &mut $self.recursion_limit {
680
            *limit = limit.saturating_add(1);
681
        }
682

            
683
        result
684
    }};
685
}
686

            
687
impl<'a, W: fmt::Write> ser::Serializer for &'a mut Serializer<W> {
688
    type Error = Error;
689
    type Ok = ();
690
    type SerializeMap = Compound<'a, W>;
691
    type SerializeSeq = Compound<'a, W>;
692
    type SerializeStruct = Compound<'a, W>;
693
    type SerializeStructVariant = Compound<'a, W>;
694
    type SerializeTuple = Compound<'a, W>;
695
    type SerializeTupleStruct = Compound<'a, W>;
696
    type SerializeTupleVariant = Compound<'a, W>;
697

            
698
368
    fn serialize_bool(self, v: bool) -> Result<()> {
699
368
        self.output.write_str(if v { "true" } else { "false" })?;
700
368
        Ok(())
701
368
    }
702

            
703
136
    fn serialize_i8(self, v: i8) -> Result<()> {
704
136
        self.serialize_sint(v, "i8")
705
136
    }
706

            
707
84
    fn serialize_i16(self, v: i16) -> Result<()> {
708
84
        self.serialize_sint(v, "i16")
709
84
    }
710

            
711
1220
    fn serialize_i32(self, v: i32) -> Result<()> {
712
1220
        self.serialize_sint(v, "i32")
713
1220
    }
714

            
715
92
    fn serialize_i64(self, v: i64) -> Result<()> {
716
92
        self.serialize_sint(v, "i64")
717
92
    }
718

            
719
    #[cfg(feature = "integer128")]
720
52
    fn serialize_i128(self, v: i128) -> Result<()> {
721
52
        self.serialize_sint(v, "i128")
722
52
    }
723

            
724
612
    fn serialize_u8(self, v: u8) -> Result<()> {
725
612
        self.serialize_uint(v, "u8")
726
612
    }
727

            
728
84
    fn serialize_u16(self, v: u16) -> Result<()> {
729
84
        self.serialize_uint(v, "u16")
730
84
    }
731

            
732
448
    fn serialize_u32(self, v: u32) -> Result<()> {
733
448
        self.serialize_uint(v, "u32")
734
448
    }
735

            
736
120
    fn serialize_u64(self, v: u64) -> Result<()> {
737
120
        self.serialize_uint(v, "u64")
738
120
    }
739

            
740
    #[cfg(feature = "integer128")]
741
50
    fn serialize_u128(self, v: u128) -> Result<()> {
742
50
        self.serialize_uint(v, "u128")
743
50
    }
744

            
745
492
    fn serialize_f32(self, v: f32) -> Result<()> {
746
492
        if v.is_nan() && v.is_sign_negative() {
747
40
            write!(self.output, "-")?;
748
452
        }
749

            
750
492
        write!(self.output, "{}", v)?;
751

            
752
        // Equivalent to v.fract() == 0.0
753
        // See: https://docs.rs/num-traits/0.2.19/src/num_traits/float.rs.html#459-465
754
492
        if v % 1. == 0.0 {
755
260
            write!(self.output, ".0")?;
756
232
        }
757

            
758
492
        if self.number_suffixes() {
759
48
            write!(self.output, "f32")?;
760
444
        }
761

            
762
492
        Ok(())
763
492
    }
764

            
765
224
    fn serialize_f64(self, v: f64) -> Result<()> {
766
224
        if v.is_nan() && v.is_sign_negative() {
767
8
            write!(self.output, "-")?;
768
216
        }
769

            
770
224
        write!(self.output, "{}", v)?;
771

            
772
        // Equivalent to v.fract() == 0.0
773
        // See: https://docs.rs/num-traits/0.2.19/src/num_traits/float.rs.html#459-465
774
224
        if v % 1. == 0.0 {
775
124
            write!(self.output, ".0")?;
776
100
        }
777

            
778
224
        if self.number_suffixes() {
779
48
            write!(self.output, "f64")?;
780
176
        }
781

            
782
224
        Ok(())
783
224
    }
784

            
785
672
    fn serialize_char(self, v: char) -> Result<()> {
786
672
        self.output.write_char('\'')?;
787
672
        if v == '\\' || v == '\'' {
788
32
            self.output.write_char('\\')?;
789
640
        }
790
672
        write!(self.output, "{}", v)?;
791
672
        self.output.write_char('\'')?;
792
672
        Ok(())
793
672
    }
794

            
795
1176
    fn serialize_str(self, v: &str) -> Result<()> {
796
1176
        if self.escape_strings() {
797
1144
            self.serialize_escaped_str(v)?;
798
        } else {
799
32
            self.serialize_unescaped_or_raw_str(v)?;
800
        }
801

            
802
1176
        Ok(())
803
1176
    }
804

            
805
160
    fn serialize_bytes(self, v: &[u8]) -> Result<()> {
806
        // We need to fall back to escaping if the byte string would be invalid UTF-8
807
160
        if !self.escape_strings() {
808
28
            if let Ok(v) = core::str::from_utf8(v) {
809
24
                return self
810
24
                    .serialize_unescaped_or_raw_byte_str(v)
811
24
                    .map_err(Error::from);
812
4
            }
813
132
        }
814

            
815
136
        self.serialize_escaped_byte_str(v)?;
816

            
817
136
        Ok(())
818
160
    }
819

            
820
76
    fn serialize_none(self) -> Result<()> {
821
        // We no longer need to keep track of the depth
822
76
        let implicit_some_depth = self.implicit_some_depth;
823
76
        self.implicit_some_depth = 0;
824

            
825
76
        for _ in 0..implicit_some_depth {
826
12
            self.output.write_str("Some(")?;
827
        }
828
76
        self.output.write_str("None")?;
829
76
        for _ in 0..implicit_some_depth {
830
12
            self.output.write_char(')')?;
831
        }
832

            
833
76
        Ok(())
834
76
    }
835

            
836
532
    fn serialize_some<T>(self, value: &T) -> Result<()>
837
532
    where
838
532
        T: ?Sized + Serialize,
839
    {
840
532
        let implicit_some = self.extensions().contains(Extensions::IMPLICIT_SOME);
841
532
        if implicit_some {
842
120
            self.implicit_some_depth += 1;
843
120
        } else {
844
412
            self.newtype_variant = self
845
412
                .extensions()
846
412
                .contains(Extensions::UNWRAP_VARIANT_NEWTYPES);
847
412
            self.output.write_str("Some(")?;
848
        }
849
532
        guard_recursion! { self => value.serialize(&mut *self)? };
850
276
        if implicit_some {
851
120
            self.implicit_some_depth = 0;
852
120
        } else {
853
156
            self.output.write_char(')')?;
854
156
            self.newtype_variant = false;
855
        }
856

            
857
276
        Ok(())
858
532
    }
859

            
860
224
    fn serialize_unit(self) -> Result<()> {
861
224
        if !self.newtype_variant {
862
220
            self.output.write_str("()")?;
863
4
        }
864

            
865
224
        Ok(())
866
224
    }
867

            
868
88
    fn serialize_unit_struct(self, name: &'static str) -> Result<()> {
869
88
        if self.struct_names() && !self.newtype_variant {
870
16
            self.write_identifier(name)?;
871

            
872
8
            Ok(())
873
        } else {
874
72
            self.validate_identifier(name)?;
875
72
            self.serialize_unit()
876
        }
877
88
    }
878

            
879
240
    fn serialize_unit_variant(
880
240
        self,
881
240
        name: &'static str,
882
240
        _variant_index: u32,
883
240
        variant: &'static str,
884
240
    ) -> Result<()> {
885
240
        self.validate_identifier(name)?;
886
236
        self.write_identifier(variant)?;
887

            
888
232
        Ok(())
889
240
    }
890

            
891
444
    fn serialize_newtype_struct<T>(self, name: &'static str, value: &T) -> Result<()>
892
444
    where
893
444
        T: ?Sized + Serialize,
894
    {
895
444
        if name == crate::value::raw::RAW_VALUE_TOKEN {
896
196
            let implicit_some_depth = self.implicit_some_depth;
897
196
            self.implicit_some_depth = 0;
898

            
899
196
            for _ in 0..implicit_some_depth {
900
8
                self.output.write_str("Some(")?;
901
            }
902

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

            
905
84
            for _ in 0..implicit_some_depth {
906
8
                self.output.write_char(')')?;
907
            }
908

            
909
84
            return Ok(());
910
248
        }
911

            
912
248
        if self.extensions().contains(Extensions::UNWRAP_NEWTYPES) || self.newtype_variant {
913
40
            self.newtype_variant = false;
914

            
915
40
            self.validate_identifier(name)?;
916

            
917
40
            return guard_recursion! { self => value.serialize(&mut *self) };
918
208
        }
919

            
920
208
        if self.struct_names() {
921
12
            self.write_identifier(name)?;
922
        } else {
923
196
            self.validate_identifier(name)?;
924
        }
925

            
926
204
        self.implicit_some_depth = 0;
927

            
928
204
        self.output.write_char('(')?;
929
204
        guard_recursion! { self => value.serialize(&mut *self)? };
930
204
        self.output.write_char(')')?;
931

            
932
204
        Ok(())
933
444
    }
934

            
935
364
    fn serialize_newtype_variant<T>(
936
364
        self,
937
364
        name: &'static str,
938
364
        _variant_index: u32,
939
364
        variant: &'static str,
940
364
        value: &T,
941
364
    ) -> Result<()>
942
364
    where
943
364
        T: ?Sized + Serialize,
944
    {
945
364
        self.validate_identifier(name)?;
946
360
        self.write_identifier(variant)?;
947
356
        self.output.write_char('(')?;
948

            
949
356
        self.newtype_variant = self
950
356
            .extensions()
951
356
            .contains(Extensions::UNWRAP_VARIANT_NEWTYPES);
952
356
        self.implicit_some_depth = 0;
953

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

            
956
354
        self.newtype_variant = false;
957

            
958
354
        self.output.write_char(')')?;
959
354
        Ok(())
960
364
    }
961

            
962
240
    fn serialize_seq(self, len: Option<usize>) -> Result<Self::SerializeSeq> {
963
240
        self.newtype_variant = false;
964
240
        self.implicit_some_depth = 0;
965

            
966
240
        self.output.write_char('[')?;
967

            
968
240
        if !self.compact_arrays() {
969
212
            if let Some(len) = len {
970
212
                self.is_empty = Some(len == 0);
971
212
            }
972

            
973
212
            self.start_indent()?;
974
28
        }
975

            
976
240
        Ok(Compound::new(self, false))
977
240
    }
978

            
979
352
    fn serialize_tuple(self, len: usize) -> Result<Self::SerializeTuple> {
980
352
        let old_newtype_variant = self.newtype_variant;
981
352
        self.newtype_variant = false;
982
352
        self.implicit_some_depth = 0;
983

            
984
352
        if !old_newtype_variant {
985
324
            self.output.write_char('(')?;
986
28
        }
987

            
988
352
        if self.separate_tuple_members() {
989
32
            self.is_empty = Some(len == 0);
990

            
991
32
            self.start_indent()?;
992
320
        }
993

            
994
352
        Ok(Compound::new(self, old_newtype_variant))
995
352
    }
996

            
997
104
    fn serialize_tuple_struct(
998
104
        self,
999
104
        name: &'static str,
104
        len: usize,
104
    ) -> Result<Self::SerializeTupleStruct> {
104
        if self.struct_names() && !self.newtype_variant {
20
            self.write_identifier(name)?;
        } else {
84
            self.validate_identifier(name)?;
        }
100
        self.serialize_tuple(len)
104
    }
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
        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
            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
        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
    }
1020
    fn serialize_struct(self, name: &'static str, len: usize) -> Result<Self::SerializeStruct> {
1020
        let old_newtype_variant = self.newtype_variant;
1020
        self.newtype_variant = false;
1020
        self.implicit_some_depth = 0;
1020
        if old_newtype_variant {
16
            self.validate_identifier(name)?;
        } else {
1004
            if self.struct_names() {
72
                self.write_identifier(name)?;
            } else {
932
                self.validate_identifier(name)?;
            }
1000
            self.output.write_char('(')?;
        }
1016
        if !self.compact_structs() {
996
            self.is_empty = Some(len == 0);
996
            self.start_indent()?;
20
        }
1016
        Ok(Compound::new(self, old_newtype_variant))
1020
    }
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
        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> {
2160
    fn new(ser: &'a mut Serializer<W>, newtype_variant: bool) -> Self {
2160
        Compound {
2160
            ser,
2160
            state: State::First,
2160
            newtype_variant,
2160
            sequence_index: 0,
2160
        }
2160
    }
}
impl<'a, W: fmt::Write> Drop for Compound<'a, W> {
2160
    fn drop(&mut self) {
2160
        if let Some(limit) = &mut self.ser.recursion_limit {
2148
            *limit = limit.saturating_add(1);
2148
        }
2160
    }
}
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
        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
        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
        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
        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
        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
        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 = ();
1892
    fn serialize_field<T>(&mut self, key: &'static str, value: &T) -> Result<()>
1892
    where
1892
        T: ?Sized + Serialize,
    {
1892
        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
60
            })
1028
        });
1892
        if let State::First = self.state {
1064
            self.state = State::Rest;
1064
        } else {
828
            self.ser.output.write_char(',')?;
828
            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)?;
                }
332
            }
        }
1892
        if !self.ser.compact_structs() {
1852
            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
                }
864
            }
40
        }
1892
        self.ser.write_identifier(key)?;
1884
        self.ser.output.write_char(':')?;
1884
        if let Some((ref config, _)) = self.ser.pretty {
1028
            self.ser.output.write_str(&config.separator)?;
856
        }
1884
        guard_recursion! { self.ser => value.serialize(&mut *self.ser)? };
1606
        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
            }
596
        };
1606
        Ok(())
1892
    }
806
    fn end(self) -> Result<()> {
806
        if let State::Rest = self.state {
778
            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
                }
264
            }
28
        }
806
        if !self.ser.compact_structs() {
778
            self.ser.end_indent()?;
28
        }
806
        if !self.newtype_variant {
790
            self.ser.output.write_char(')')?;
16
        }
806
        Ok(())
806
    }
}
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
        ser::SerializeStruct::serialize_field(self, key, value)
152
    }
72
    fn end(self) -> Result<()> {
72
        ser::SerializeStruct::end(self)
72
    }
}