1
use std::{borrow::Cow, fmt};
2

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

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

            
14
pub mod path_meta;
15

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

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

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

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

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

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

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

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

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

            
135
822
        self
136
822
    }
137

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

            
145
36
        self
146
36
    }
147

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

            
155
4
        self
156
4
    }
157

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

            
165
8
        self
166
8
    }
167

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

            
177
4282
        self
178
4282
    }
179

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

            
190
1370
        self
191
1370
    }
192

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

            
201
1918
        self
202
1918
    }
203

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

            
226
1096
        self
227
1096
    }
228

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

            
236
11782
        self
237
11782
    }
238

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

            
259
4110
        self
260
4110
    }
261

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

            
284
994
        self
285
994
    }
286

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

            
310
274
        self
311
274
    }
312

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

            
342
16440
        self
343
16440
    }
344
}
345

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

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

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

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

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

            
430
1744
            let non_default_extensions = !options.default_extensions;
431

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

            
602
1584
        Ok(())
603
1584
    }
604

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

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

            
613
1310
        Ok(())
614
1310
    }
615

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

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

            
641
    /// Checks if struct names should be emitted
642
    ///
643
    /// 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.
644
1400
    fn struct_names(&self) -> bool {
645
1400
        self.extensions()
646
1400
            .contains(Extensions::EXPLICIT_STRUCT_NAMES)
647
1388
            || self
648
1388
                .pretty
649
1388
                .as_ref()
650
1400
                .map_or(false, |(pc, _)| pc.struct_names)
651
1400
    }
652
}
653

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

            
664
        let result = $expr;
665

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

            
670
        result
671
    }};
672
}
673

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

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

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

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

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

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

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

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

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

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

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

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

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

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

            
739
492
        if v.fract() == 0.0 {
740
260
            write!(self.output, ".0")?;
741
232
        }
742

            
743
492
        if self.number_suffixes() {
744
48
            write!(self.output, "f32")?;
745
444
        }
746

            
747
492
        Ok(())
748
492
    }
749

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

            
755
224
        write!(self.output, "{}", v)?;
756

            
757
224
        if v.fract() == 0.0 {
758
124
            write!(self.output, ".0")?;
759
100
        }
760

            
761
224
        if self.number_suffixes() {
762
48
            write!(self.output, "f64")?;
763
176
        }
764

            
765
224
        Ok(())
766
224
    }
767

            
768
672
    fn serialize_char(self, v: char) -> Result<()> {
769
672
        self.output.write_char('\'')?;
770
672
        if v == '\\' || v == '\'' {
771
32
            self.output.write_char('\\')?;
772
640
        }
773
672
        write!(self.output, "{}", v)?;
774
672
        self.output.write_char('\'')?;
775
672
        Ok(())
776
672
    }
777

            
778
1168
    fn serialize_str(self, v: &str) -> Result<()> {
779
1168
        if self.escape_strings() {
780
1136
            self.serialize_escaped_str(v)?;
781
        } else {
782
32
            self.serialize_unescaped_or_raw_str(v)?;
783
        }
784

            
785
1168
        Ok(())
786
1168
    }
787

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

            
798
136
        self.serialize_escaped_byte_str(v)?;
799

            
800
136
        Ok(())
801
160
    }
802

            
803
76
    fn serialize_none(self) -> Result<()> {
804
76
        // We no longer need to keep track of the depth
805
76
        let implicit_some_depth = self.implicit_some_depth;
806
76
        self.implicit_some_depth = 0;
807
76

            
808
76
        for _ in 0..implicit_some_depth {
809
12
            self.output.write_str("Some(")?;
810
        }
811
76
        self.output.write_str("None")?;
812
76
        for _ in 0..implicit_some_depth {
813
12
            self.output.write_char(')')?;
814
        }
815

            
816
76
        Ok(())
817
76
    }
818

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

            
840
276
        Ok(())
841
532
    }
842

            
843
224
    fn serialize_unit(self) -> Result<()> {
844
224
        if !self.newtype_variant {
845
220
            self.output.write_str("()")?;
846
4
        }
847

            
848
224
        Ok(())
849
224
    }
850

            
851
88
    fn serialize_unit_struct(self, name: &'static str) -> Result<()> {
852
88
        if self.struct_names() && !self.newtype_variant {
853
16
            self.write_identifier(name)?;
854

            
855
8
            Ok(())
856
        } else {
857
72
            self.validate_identifier(name)?;
858
72
            self.serialize_unit()
859
        }
860
88
    }
861

            
862
240
    fn serialize_unit_variant(
863
240
        self,
864
240
        name: &'static str,
865
240
        _variant_index: u32,
866
240
        variant: &'static str,
867
240
    ) -> Result<()> {
868
240
        self.validate_identifier(name)?;
869
236
        self.write_identifier(variant)?;
870

            
871
232
        Ok(())
872
240
    }
873

            
874
444
    fn serialize_newtype_struct<T>(self, name: &'static str, value: &T) -> Result<()>
875
444
    where
876
444
        T: ?Sized + Serialize,
877
444
    {
878
444
        if name == crate::value::raw::RAW_VALUE_TOKEN {
879
196
            let implicit_some_depth = self.implicit_some_depth;
880
196
            self.implicit_some_depth = 0;
881
196

            
882
196
            for _ in 0..implicit_some_depth {
883
8
                self.output.write_str("Some(")?;
884
            }
885

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

            
888
84
            for _ in 0..implicit_some_depth {
889
8
                self.output.write_char(')')?;
890
            }
891

            
892
84
            return Ok(());
893
248
        }
894
248

            
895
248
        if self.extensions().contains(Extensions::UNWRAP_NEWTYPES) || self.newtype_variant {
896
40
            self.newtype_variant = false;
897
40

            
898
40
            self.validate_identifier(name)?;
899

            
900
40
            return guard_recursion! { self => value.serialize(&mut *self) };
901
208
        }
902
208

            
903
208
        if self.struct_names() {
904
12
            self.write_identifier(name)?;
905
        } else {
906
196
            self.validate_identifier(name)?;
907
        }
908

            
909
204
        self.implicit_some_depth = 0;
910
204

            
911
204
        self.output.write_char('(')?;
912
204
        guard_recursion! { self => value.serialize(&mut *self)? };
913
204
        self.output.write_char(')')?;
914

            
915
204
        Ok(())
916
444
    }
917

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

            
932
356
        self.newtype_variant = self
933
356
            .extensions()
934
356
            .contains(Extensions::UNWRAP_VARIANT_NEWTYPES);
935
356
        self.implicit_some_depth = 0;
936
356

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

            
939
354
        self.newtype_variant = false;
940
354

            
941
354
        self.output.write_char(')')?;
942
354
        Ok(())
943
364
    }
944

            
945
240
    fn serialize_seq(self, len: Option<usize>) -> Result<Self::SerializeSeq> {
946
240
        self.newtype_variant = false;
947
240
        self.implicit_some_depth = 0;
948
240

            
949
240
        self.output.write_char('[')?;
950

            
951
240
        if !self.compact_arrays() {
952
212
            if let Some(len) = len {
953
212
                self.is_empty = Some(len == 0);
954
212
            }
955

            
956
212
            self.start_indent()?;
957
28
        }
958

            
959
240
        Ok(Compound::new(self, false))
960
240
    }
961

            
962
352
    fn serialize_tuple(self, len: usize) -> Result<Self::SerializeTuple> {
963
352
        let old_newtype_variant = self.newtype_variant;
964
352
        self.newtype_variant = false;
965
352
        self.implicit_some_depth = 0;
966
352

            
967
352
        if !old_newtype_variant {
968
324
            self.output.write_char('(')?;
969
28
        }
970

            
971
352
        if self.separate_tuple_members() {
972
32
            self.is_empty = Some(len == 0);
973
32

            
974
32
            self.start_indent()?;
975
320
        }
976

            
977
352
        Ok(Compound::new(self, old_newtype_variant))
978
352
    }
979

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

            
991
100
        self.serialize_tuple(len)
992
104
    }
993

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

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

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

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

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

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

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