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
{
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
{
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
1616
pub fn to_string<T>(value: &T) -> Result<String>
48
1616
where
49
1616
    T: ?Sized + Serialize,
50
{
51
1616
    Options::default().to_string(value)
52
1616
}
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
{
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

            
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

            
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

            
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

            
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

            
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

            
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

            
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

            
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

            
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

            
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

            
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

            
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

            
343
16680
        self
344
16680
    }
345
}
346

            
347
impl Default for PrettyConfig {
348
69386
    fn default() -> Self {
349
        PrettyConfig {
350
            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
            struct_names: false,
359
            separate_tuple_members: false,
360
            enumerate_arrays: false,
361
69386
            extensions: Extensions::empty(),
362
            compact_arrays: false,
363
            escape_strings: true,
364
            compact_structs: false,
365
            compact_maps: false,
366
            number_suffixes: false,
367
69386
            path_meta: None,
368
        }
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
3824
    pub fn with_options(
410
3824
        mut writer: W,
411
3824
        config: Option<PrettyConfig>,
412
3824
        options: &Options,
413
3824
    ) -> Result<Self> {
414
3824
        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

            
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
2068
        };
438
        Ok(Serializer {
439
3812
            output: writer,
440
3812
            pretty: config.map(|conf| (conf, Pretty { indent: 0 })),
441
3812
            default_extensions: options.default_extensions,
442
3812
            is_empty: None,
443
            newtype_variant: false,
444
3812
            recursion_limit: options.recursion_limit,
445
            implicit_some_depth: 0,
446
        })
447
3824
    }
448

            
449
    /// Unwrap the `Writer` from the `Serializer`.
450
    #[inline]
451
    pub fn into_inner(self) -> W {
452
        self.output
453
    }
454

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

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

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

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

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

            
485
2952
    fn extensions(&self) -> Extensions {
486
2952
        self.default_extensions
487
2952
            | self
488
2952
                .pretty
489
2952
                .as_ref()
490
2952
                .map_or(Extensions::empty(), |(ref config, _)| config.extensions)
491
2952
    }
492

            
493
1336
    fn escape_strings(&self) -> bool {
494
1336
        self.pretty
495
1336
            .as_ref()
496
1336
            .map_or(true, |(ref config, _)| config.escape_strings)
497
1336
    }
498

            
499
1696
    fn start_indent(&mut self) -> Result<()> {
500
1696
        if let Some((ref config, ref mut pretty)) = self.pretty {
501
1032
            pretty.indent += 1;
502
1032
            if pretty.indent <= config.depth_limit {
503
1008
                let is_empty = self.is_empty.unwrap_or(false);
504

            
505
1008
                if !is_empty {
506
960
                    self.output.write_str(&config.new_line)?;
507
48
                }
508
24
            }
509
664
        }
510
1696
        Ok(())
511
1696
    }
512

            
513
1452
    fn indent(&mut self) -> fmt::Result {
514
1452
        if let Some((ref config, ref pretty)) = self.pretty {
515
1124
            indent(&mut self.output, config, pretty)?;
516
328
        }
517
1452
        Ok(())
518
1452
    }
519

            
520
1406
    fn end_indent(&mut self) -> fmt::Result {
521
1406
        if let Some((ref config, ref mut pretty)) = self.pretty {
522
1010
            if pretty.indent <= config.depth_limit {
523
986
                let is_empty = self.is_empty.unwrap_or(false);
524

            
525
986
                if !is_empty {
526
938
                    for _ in 1..pretty.indent {
527
458
                        self.output.write_str(&config.indentor)?;
528
                    }
529
48
                }
530
24
            }
531
1010
            pretty.indent -= 1;
532

            
533
1010
            self.is_empty = None;
534
396
        }
535
1406
        Ok(())
536
1406
    }
537

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

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

            
570
136
    fn serialize_escaped_byte_str(&mut self, value: &[u8]) -> fmt::Result {
571
136
        self.output.write_str("b\"")?;
572
5356
        for c in value.iter().flat_map(|c| core::ascii::escape_default(*c)) {
573
5356
            self.output.write_char(char::from(c))?;
574
        }
575
136
        self.output.write_char('"')?;
576
136
        Ok(())
577
136
    }
578

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

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

            
605
1584
        if self.number_suffixes() {
606
72
            write!(self.output, "{}", suffix)?;
607
1512
        }
608

            
609
1584
        Ok(())
610
1584
    }
611

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

            
616
1314
        if self.number_suffixes() {
617
72
            write!(self.output, "{}", suffix)?;
618
1242
        }
619

            
620
1314
        Ok(())
621
1314
    }
622

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

            
640
    #[allow(clippy::unused_self)]
641
4912
    fn validate_identifier(&self, name: &str) -> Result<()> {
642
4912
        if name.is_empty() || !name.chars().all(is_ident_raw_char) {
643
60
            return Err(Error::InvalidIdentifier(name.into()));
644
4852
        }
645
4852
        Ok(())
646
4912
    }
647

            
648
    /// Checks if struct names should be emitted
649
    ///
650
    /// 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.
651
1404
    fn struct_names(&self) -> bool {
652
1404
        self.extensions()
653
1404
            .contains(Extensions::EXPLICIT_STRUCT_NAMES)
654
1392
            || self
655
1392
                .pretty
656
1392
                .as_ref()
657
1392
                .map_or(false, |(pc, _)| pc.struct_names)
658
1404
    }
659
}
660

            
661
macro_rules! guard_recursion {
662
    ($self:expr => $expr:expr) => {{
663
        if let Some(limit) = &mut $self.recursion_limit {
664
            if let Some(new_limit) = limit.checked_sub(1) {
665
                *limit = new_limit;
666
            } else {
667
                return Err(Error::ExceededRecursionLimit);
668
            }
669
        }
670

            
671
        let result = $expr;
672

            
673
        if let Some(limit) = &mut $self.recursion_limit {
674
            *limit = limit.saturating_add(1);
675
        }
676

            
677
        result
678
    }};
679
}
680

            
681
impl<'a, W: fmt::Write> ser::Serializer for &'a mut Serializer<W> {
682
    type Error = Error;
683
    type Ok = ();
684
    type SerializeMap = Compound<'a, W>;
685
    type SerializeSeq = Compound<'a, W>;
686
    type SerializeStruct = Compound<'a, W>;
687
    type SerializeStructVariant = Compound<'a, W>;
688
    type SerializeTuple = Compound<'a, W>;
689
    type SerializeTupleStruct = Compound<'a, W>;
690
    type SerializeTupleVariant = Compound<'a, W>;
691

            
692
368
    fn serialize_bool(self, v: bool) -> Result<()> {
693
368
        self.output.write_str(if v { "true" } else { "false" })?;
694
368
        Ok(())
695
368
    }
696

            
697
136
    fn serialize_i8(self, v: i8) -> Result<()> {
698
136
        self.serialize_sint(v, "i8")
699
136
    }
700

            
701
84
    fn serialize_i16(self, v: i16) -> Result<()> {
702
84
        self.serialize_sint(v, "i16")
703
84
    }
704

            
705
1220
    fn serialize_i32(self, v: i32) -> Result<()> {
706
1220
        self.serialize_sint(v, "i32")
707
1220
    }
708

            
709
92
    fn serialize_i64(self, v: i64) -> Result<()> {
710
92
        self.serialize_sint(v, "i64")
711
92
    }
712

            
713
    #[cfg(feature = "integer128")]
714
52
    fn serialize_i128(self, v: i128) -> Result<()> {
715
52
        self.serialize_sint(v, "i128")
716
52
    }
717

            
718
612
    fn serialize_u8(self, v: u8) -> Result<()> {
719
612
        self.serialize_uint(v, "u8")
720
612
    }
721

            
722
84
    fn serialize_u16(self, v: u16) -> Result<()> {
723
84
        self.serialize_uint(v, "u16")
724
84
    }
725

            
726
448
    fn serialize_u32(self, v: u32) -> Result<()> {
727
448
        self.serialize_uint(v, "u32")
728
448
    }
729

            
730
120
    fn serialize_u64(self, v: u64) -> Result<()> {
731
120
        self.serialize_uint(v, "u64")
732
120
    }
733

            
734
    #[cfg(feature = "integer128")]
735
50
    fn serialize_u128(self, v: u128) -> Result<()> {
736
50
        self.serialize_uint(v, "u128")
737
50
    }
738

            
739
492
    fn serialize_f32(self, v: f32) -> Result<()> {
740
492
        if v.is_nan() && v.is_sign_negative() {
741
40
            write!(self.output, "-")?;
742
452
        }
743

            
744
492
        write!(self.output, "{}", v)?;
745

            
746
        // Equivalent to v.fract() == 0.0
747
        // See: https://docs.rs/num-traits/0.2.19/src/num_traits/float.rs.html#459-465
748
492
        if v % 1. == 0.0 {
749
260
            write!(self.output, ".0")?;
750
232
        }
751

            
752
492
        if self.number_suffixes() {
753
48
            write!(self.output, "f32")?;
754
444
        }
755

            
756
492
        Ok(())
757
492
    }
758

            
759
224
    fn serialize_f64(self, v: f64) -> Result<()> {
760
224
        if v.is_nan() && v.is_sign_negative() {
761
8
            write!(self.output, "-")?;
762
216
        }
763

            
764
224
        write!(self.output, "{}", v)?;
765

            
766
        // Equivalent to v.fract() == 0.0
767
        // See: https://docs.rs/num-traits/0.2.19/src/num_traits/float.rs.html#459-465
768
224
        if v % 1. == 0.0 {
769
124
            write!(self.output, ".0")?;
770
100
        }
771

            
772
224
        if self.number_suffixes() {
773
48
            write!(self.output, "f64")?;
774
176
        }
775

            
776
224
        Ok(())
777
224
    }
778

            
779
672
    fn serialize_char(self, v: char) -> Result<()> {
780
672
        self.output.write_char('\'')?;
781
672
        if v == '\\' || v == '\'' {
782
32
            self.output.write_char('\\')?;
783
640
        }
784
672
        write!(self.output, "{}", v)?;
785
672
        self.output.write_char('\'')?;
786
672
        Ok(())
787
672
    }
788

            
789
1176
    fn serialize_str(self, v: &str) -> Result<()> {
790
1176
        if self.escape_strings() {
791
1144
            self.serialize_escaped_str(v)?;
792
        } else {
793
32
            self.serialize_unescaped_or_raw_str(v)?;
794
        }
795

            
796
1176
        Ok(())
797
1176
    }
798

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

            
809
136
        self.serialize_escaped_byte_str(v)?;
810

            
811
136
        Ok(())
812
160
    }
813

            
814
76
    fn serialize_none(self) -> Result<()> {
815
        // We no longer need to keep track of the depth
816
76
        let implicit_some_depth = self.implicit_some_depth;
817
76
        self.implicit_some_depth = 0;
818

            
819
76
        for _ in 0..implicit_some_depth {
820
12
            self.output.write_str("Some(")?;
821
        }
822
76
        self.output.write_str("None")?;
823
76
        for _ in 0..implicit_some_depth {
824
12
            self.output.write_char(')')?;
825
        }
826

            
827
76
        Ok(())
828
76
    }
829

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

            
851
276
        Ok(())
852
532
    }
853

            
854
224
    fn serialize_unit(self) -> Result<()> {
855
224
        if !self.newtype_variant {
856
220
            self.output.write_str("()")?;
857
4
        }
858

            
859
224
        Ok(())
860
224
    }
861

            
862
88
    fn serialize_unit_struct(self, name: &'static str) -> Result<()> {
863
88
        if self.struct_names() && !self.newtype_variant {
864
16
            self.write_identifier(name)?;
865

            
866
8
            Ok(())
867
        } else {
868
72
            self.validate_identifier(name)?;
869
72
            self.serialize_unit()
870
        }
871
88
    }
872

            
873
240
    fn serialize_unit_variant(
874
240
        self,
875
240
        name: &'static str,
876
240
        _variant_index: u32,
877
240
        variant: &'static str,
878
240
    ) -> Result<()> {
879
240
        self.validate_identifier(name)?;
880
236
        self.write_identifier(variant)?;
881

            
882
232
        Ok(())
883
240
    }
884

            
885
444
    fn serialize_newtype_struct<T>(self, name: &'static str, value: &T) -> Result<()>
886
444
    where
887
444
        T: ?Sized + Serialize,
888
    {
889
444
        if name == crate::value::raw::RAW_VALUE_TOKEN {
890
196
            let implicit_some_depth = self.implicit_some_depth;
891
196
            self.implicit_some_depth = 0;
892

            
893
196
            for _ in 0..implicit_some_depth {
894
8
                self.output.write_str("Some(")?;
895
            }
896

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

            
899
84
            for _ in 0..implicit_some_depth {
900
8
                self.output.write_char(')')?;
901
            }
902

            
903
84
            return Ok(());
904
248
        }
905

            
906
248
        if self.extensions().contains(Extensions::UNWRAP_NEWTYPES) || self.newtype_variant {
907
40
            self.newtype_variant = false;
908

            
909
40
            self.validate_identifier(name)?;
910

            
911
40
            return guard_recursion! { self => value.serialize(&mut *self) };
912
208
        }
913

            
914
208
        if self.struct_names() {
915
12
            self.write_identifier(name)?;
916
        } else {
917
196
            self.validate_identifier(name)?;
918
        }
919

            
920
204
        self.implicit_some_depth = 0;
921

            
922
204
        self.output.write_char('(')?;
923
204
        guard_recursion! { self => value.serialize(&mut *self)? };
924
204
        self.output.write_char(')')?;
925

            
926
204
        Ok(())
927
444
    }
928

            
929
364
    fn serialize_newtype_variant<T>(
930
364
        self,
931
364
        name: &'static str,
932
364
        _variant_index: u32,
933
364
        variant: &'static str,
934
364
        value: &T,
935
364
    ) -> Result<()>
936
364
    where
937
364
        T: ?Sized + Serialize,
938
    {
939
364
        self.validate_identifier(name)?;
940
360
        self.write_identifier(variant)?;
941
356
        self.output.write_char('(')?;
942

            
943
356
        self.newtype_variant = self
944
356
            .extensions()
945
356
            .contains(Extensions::UNWRAP_VARIANT_NEWTYPES);
946
356
        self.implicit_some_depth = 0;
947

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

            
950
354
        self.newtype_variant = false;
951

            
952
354
        self.output.write_char(')')?;
953
354
        Ok(())
954
364
    }
955

            
956
240
    fn serialize_seq(self, len: Option<usize>) -> Result<Self::SerializeSeq> {
957
240
        self.newtype_variant = false;
958
240
        self.implicit_some_depth = 0;
959

            
960
240
        self.output.write_char('[')?;
961

            
962
240
        if !self.compact_arrays() {
963
212
            if let Some(len) = len {
964
212
                self.is_empty = Some(len == 0);
965
212
            }
966

            
967
212
            self.start_indent()?;
968
28
        }
969

            
970
240
        Ok(Compound::new(self, false))
971
240
    }
972

            
973
352
    fn serialize_tuple(self, len: usize) -> Result<Self::SerializeTuple> {
974
352
        let old_newtype_variant = self.newtype_variant;
975
352
        self.newtype_variant = false;
976
352
        self.implicit_some_depth = 0;
977

            
978
352
        if !old_newtype_variant {
979
324
            self.output.write_char('(')?;
980
28
        }
981

            
982
352
        if self.separate_tuple_members() {
983
32
            self.is_empty = Some(len == 0);
984

            
985
32
            self.start_indent()?;
986
320
        }
987

            
988
352
        Ok(Compound::new(self, old_newtype_variant))
989
352
    }
990

            
991
104
    fn serialize_tuple_struct(
992
104
        self,
993
104
        name: &'static str,
994
104
        len: usize,
995
104
    ) -> Result<Self::SerializeTupleStruct> {
996
104
        if self.struct_names() && !self.newtype_variant {
997
20
            self.write_identifier(name)?;
998
        } else {
999
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
    }
}