1
use alloc::borrow::Cow;
2
use alloc::string::String;
3
use core::fmt::Write;
4

            
5
use serde::ser::{
6
    SerializeMap, SerializeSeq, SerializeStruct, SerializeStructVariant, SerializeTuple,
7
    SerializeTupleStruct, SerializeTupleVariant,
8
};
9
use serde::Serialize;
10

            
11
use crate::writer::{self, Writer};
12

            
13
/// A Serde serializer that generates Rsn.
14
#[derive(Debug)]
15
pub struct Serializer<'config, Output> {
16
    writer: Writer<'config, Output>,
17
    implicit_map_at_root: bool,
18
    anonymous_structs: bool,
19
}
20

            
21
impl Default for Serializer<'static, String> {
22
    fn default() -> Self {
23
        Self {
24
            writer: Writer::default(),
25
            implicit_map_at_root: false,
26
            anonymous_structs: false,
27
        }
28
    }
29
}
30

            
31
impl<'config, Output> Serializer<'config, Output>
32
where
33
    Output: Write,
34
{
35
    /// Returns a new serializer that writes to `output` using `configuration`.
36
16
    pub fn new(output: Output, configuration: &'config Config) -> Self {
37
16
        Self {
38
16
            writer: Writer::new(output, &configuration.writer),
39
16
            implicit_map_at_root: configuration.implicit_map_at_root,
40
16
            anonymous_structs: configuration.anonymous_structs,
41
16
        }
42
16
    }
43

            
44
    /// Finishes writing to the output and returns the output.
45
16
    pub fn finish(self) -> Output {
46
16
        self.writer.finish()
47
16
    }
48

            
49
242
    fn mark_value_seen(&mut self) {
50
242
        self.implicit_map_at_root = false;
51
242
    }
52
}
53

            
54
impl<'a, 'config, Output> serde::Serializer for &'a mut Serializer<'config, Output>
55
where
56
    Output: Write,
57
{
58
    type Error = core::fmt::Error;
59
    type Ok = ();
60
    type SerializeMap = sealed::MapSerializer<'a, 'config, Output>;
61
    type SerializeSeq = Self;
62
    type SerializeStruct = sealed::MapSerializer<'a, 'config, Output>;
63
    type SerializeStructVariant = Self;
64
    type SerializeTuple = Self;
65
    type SerializeTupleStruct = Self;
66
    type SerializeTupleVariant = Self;
67

            
68
12
    fn serialize_bool(self, v: bool) -> Result<Self::Ok, Self::Error> {
69
12
        self.mark_value_seen();
70
12
        self.writer.write_primitive(&v)
71
12
    }
72

            
73
12
    fn serialize_i8(self, v: i8) -> Result<Self::Ok, Self::Error> {
74
12
        self.mark_value_seen();
75
12
        self.writer.write_primitive(&v)
76
12
    }
77

            
78
12
    fn serialize_i16(self, v: i16) -> Result<Self::Ok, Self::Error> {
79
12
        self.mark_value_seen();
80
12
        self.writer.write_primitive(&v)
81
12
    }
82

            
83
15
    fn serialize_i32(self, v: i32) -> Result<Self::Ok, Self::Error> {
84
15
        self.mark_value_seen();
85
15
        self.writer.write_primitive(&v)
86
15
    }
87

            
88
24
    fn serialize_i64(self, v: i64) -> Result<Self::Ok, Self::Error> {
89
24
        self.mark_value_seen();
90
24
        self.writer.write_primitive(&v)
91
24
    }
92

            
93
12
    fn serialize_i128(self, v: i128) -> Result<Self::Ok, Self::Error> {
94
12
        self.mark_value_seen();
95
12
        self.writer.write_primitive(&v)
96
12
    }
97

            
98
12
    fn serialize_u8(self, v: u8) -> Result<Self::Ok, Self::Error> {
99
12
        self.mark_value_seen();
100
12
        self.writer.write_primitive(&v)
101
12
    }
102

            
103
12
    fn serialize_u16(self, v: u16) -> Result<Self::Ok, Self::Error> {
104
12
        self.mark_value_seen();
105
12
        self.writer.write_primitive(&v)
106
12
    }
107

            
108
13
    fn serialize_u32(self, v: u32) -> Result<Self::Ok, Self::Error> {
109
13
        self.mark_value_seen();
110
13
        self.writer.write_primitive(&v)
111
13
    }
112

            
113
30
    fn serialize_u64(self, v: u64) -> Result<Self::Ok, Self::Error> {
114
30
        self.mark_value_seen();
115
30
        self.writer.write_primitive(&v)
116
30
    }
117

            
118
12
    fn serialize_u128(self, v: u128) -> Result<Self::Ok, Self::Error> {
119
12
        self.mark_value_seen();
120
12
        self.writer.write_primitive(&v)
121
12
    }
122

            
123
    fn serialize_f32(self, v: f32) -> Result<Self::Ok, Self::Error> {
124
        self.mark_value_seen();
125
        self.writer.write_primitive(&v)
126
    }
127

            
128
    fn serialize_f64(self, v: f64) -> Result<Self::Ok, Self::Error> {
129
        self.mark_value_seen();
130
        self.writer.write_primitive(&v)
131
    }
132

            
133
12
    fn serialize_char(self, v: char) -> Result<Self::Ok, Self::Error> {
134
12
        self.mark_value_seen();
135
12
        self.writer.write_primitive(&v)
136
12
    }
137

            
138
24
    fn serialize_str(self, v: &str) -> Result<Self::Ok, Self::Error> {
139
24
        self.mark_value_seen();
140
24
        self.writer.write_primitive(v)
141
24
    }
142

            
143
12
    fn serialize_bytes(self, v: &[u8]) -> Result<Self::Ok, Self::Error> {
144
12
        self.mark_value_seen();
145
12
        self.writer.write_primitive(v)
146
12
    }
147

            
148
2
    fn serialize_none(self) -> Result<Self::Ok, Self::Error> {
149
2
        self.mark_value_seen();
150
2
        self.writer.write_raw_value("None")
151
2
    }
152

            
153
2
    fn serialize_some<T>(self, value: &T) -> Result<Self::Ok, Self::Error>
154
2
    where
155
2
        T: serde::Serialize + ?Sized,
156
2
    {
157
2
        self.mark_value_seen();
158
2
        self.writer.begin_named_tuple("Some")?;
159
2
        value.serialize(&mut *self)?;
160
2
        self.writer.finish_nested()?;
161
2
        Ok(())
162
2
    }
163

            
164
    fn serialize_unit(self) -> Result<Self::Ok, Self::Error> {
165
        self.mark_value_seen();
166
        self.writer.write_raw_value("()")
167
    }
168

            
169
    fn serialize_unit_struct(self, name: &'static str) -> Result<Self::Ok, Self::Error> {
170
        self.mark_value_seen();
171
        self.writer.write_raw_value(name)
172
    }
173

            
174
2
    fn serialize_unit_variant(
175
2
        self,
176
2
        _name: &'static str,
177
2
        _variant_index: u32,
178
2
        variant: &'static str,
179
2
    ) -> Result<Self::Ok, Self::Error> {
180
2
        self.mark_value_seen();
181
2
        self.writer.write_raw_value(variant)
182
2
    }
183

            
184
    fn serialize_newtype_struct<T>(
185
        self,
186
        name: &'static str,
187
        value: &T,
188
    ) -> Result<Self::Ok, Self::Error>
189
    where
190
        T: serde::Serialize + ?Sized,
191
    {
192
        self.mark_value_seen();
193
        self.writer.begin_named_tuple(name)?;
194
        value.serialize(&mut *self)?;
195
        self.writer.finish_nested()
196
    }
197

            
198
2
    fn serialize_newtype_variant<T>(
199
2
        self,
200
2
        _name: &'static str,
201
2
        _variant_index: u32,
202
2
        variant: &'static str,
203
2
        value: &T,
204
2
    ) -> Result<Self::Ok, Self::Error>
205
2
    where
206
2
        T: serde::Serialize + ?Sized,
207
2
    {
208
2
        self.mark_value_seen();
209
2
        self.writer.begin_named_tuple(variant)?;
210
2
        value.serialize(&mut *self)?;
211
2
        self.writer.finish_nested()
212
2
    }
213

            
214
2
    fn serialize_seq(self, _len: Option<usize>) -> Result<Self::SerializeSeq, Self::Error> {
215
2
        self.mark_value_seen();
216
2
        self.writer.begin_list()?;
217
2
        Ok(self)
218
2
    }
219

            
220
    fn serialize_tuple(self, _len: usize) -> Result<Self::SerializeTuple, Self::Error> {
221
        self.mark_value_seen();
222
        self.writer.begin_tuple()?;
223
        Ok(self)
224
    }
225

            
226
    fn serialize_tuple_struct(
227
        self,
228
        name: &'static str,
229
        _len: usize,
230
    ) -> Result<Self::SerializeTupleStruct, Self::Error> {
231
        self.mark_value_seen();
232
        self.writer.begin_named_tuple(name)?;
233
        Ok(self)
234
    }
235

            
236
    fn serialize_tuple_variant(
237
        self,
238
        _name: &'static str,
239
        _variant_index: u32,
240
        variant: &'static str,
241
        _len: usize,
242
    ) -> Result<Self::SerializeTupleVariant, Self::Error> {
243
        self.mark_value_seen();
244
        self.writer.begin_named_tuple(variant)?;
245
        Ok(self)
246
    }
247

            
248
1
    fn serialize_map(self, _len: Option<usize>) -> Result<Self::SerializeMap, Self::Error> {
249
1
        let is_implicit_map = self.implicit_map_at_root;
250
1
        self.mark_value_seen();
251
1
        if !is_implicit_map {
252
            self.writer.begin_map()?;
253
1
        }
254
1
        Ok(sealed::MapSerializer {
255
1
            serializer: self,
256
1
            is_implicit_map,
257
1
        })
258
1
    }
259

            
260
17
    fn serialize_struct(
261
17
        self,
262
17
        name: &'static str,
263
17
        _len: usize,
264
17
    ) -> Result<Self::SerializeStruct, Self::Error> {
265
17
        let is_implicit_map = self.implicit_map_at_root;
266
17
        self.mark_value_seen();
267
17

            
268
17
        if !is_implicit_map {
269
14
            if self.anonymous_structs {
270
3
                self.writer.begin_map()?;
271
            } else {
272
11
                self.writer.begin_named_map(name)?;
273
            }
274
3
        }
275

            
276
17
        Ok(sealed::MapSerializer {
277
17
            serializer: self,
278
17
            is_implicit_map,
279
17
        })
280
17
    }
281

            
282
    fn serialize_struct_variant(
283
        self,
284
        _name: &'static str,
285
        _variant_index: u32,
286
        variant: &'static str,
287
        _len: usize,
288
    ) -> Result<Self::SerializeStructVariant, Self::Error> {
289
        self.writer.begin_named_map(variant)?;
290
        Ok(self)
291
    }
292
}
293

            
294
impl<'a, 'config, Output> SerializeSeq for &'a mut Serializer<'config, Output>
295
where
296
    Output: Write,
297
{
298
    type Error = core::fmt::Error;
299
    type Ok = ();
300

            
301
4
    fn serialize_element<T>(&mut self, value: &T) -> Result<(), Self::Error>
302
4
    where
303
4
        T: serde::Serialize + ?Sized,
304
4
    {
305
4
        value.serialize(&mut **self)
306
4
    }
307

            
308
2
    fn end(self) -> Result<Self::Ok, Self::Error> {
309
2
        self.writer.finish_nested()
310
2
    }
311
}
312

            
313
impl<'a, 'config, Output> SerializeTuple for &'a mut Serializer<'config, Output>
314
where
315
    Output: Write,
316
{
317
    type Error = core::fmt::Error;
318
    type Ok = ();
319

            
320
    fn serialize_element<T>(&mut self, value: &T) -> Result<(), Self::Error>
321
    where
322
        T: serde::Serialize + ?Sized,
323
    {
324
        value.serialize(&mut **self)
325
    }
326

            
327
    fn end(self) -> Result<Self::Ok, Self::Error> {
328
        self.writer.finish_nested()
329
    }
330
}
331

            
332
impl<'a, 'config, Output> SerializeTupleStruct for &'a mut Serializer<'config, Output>
333
where
334
    Output: Write,
335
{
336
    type Error = core::fmt::Error;
337
    type Ok = ();
338

            
339
    fn serialize_field<T>(&mut self, value: &T) -> Result<(), Self::Error>
340
    where
341
        T: serde::Serialize + ?Sized,
342
    {
343
        value.serialize(&mut **self)
344
    }
345

            
346
    fn end(self) -> Result<Self::Ok, Self::Error> {
347
        self.writer.finish_nested()
348
    }
349
}
350

            
351
impl<'a, 'config, Output> SerializeTupleVariant for &'a mut Serializer<'config, Output>
352
where
353
    Output: Write,
354
{
355
    type Error = core::fmt::Error;
356
    type Ok = ();
357

            
358
    fn serialize_field<T>(&mut self, value: &T) -> Result<(), Self::Error>
359
    where
360
        T: serde::Serialize + ?Sized,
361
    {
362
        value.serialize(&mut **self)
363
    }
364

            
365
    fn end(self) -> Result<Self::Ok, Self::Error> {
366
        self.writer.finish_nested()
367
    }
368
}
369

            
370
mod sealed {
371
    use super::{SerializeMap, SerializeStruct, SerializeStructVariant, Serializer, Write};
372

            
373
    pub struct MapSerializer<'a, 'config, Output> {
374
        pub serializer: &'a mut Serializer<'config, Output>,
375
        pub is_implicit_map: bool,
376
    }
377

            
378
    impl<'a, 'config, Output> SerializeStruct for MapSerializer<'a, 'config, Output>
379
    where
380
        Output: Write,
381
    {
382
        type Error = core::fmt::Error;
383
        type Ok = ();
384

            
385
214
        fn serialize_field<T>(&mut self, key: &'static str, value: &T) -> Result<(), Self::Error>
386
214
        where
387
214
            T: serde::Serialize + ?Sized,
388
214
        {
389
214
            if self.is_implicit_map {
390
48
                self.serializer.writer.write_raw_value(key)?;
391
48
                self.serializer.writer.write_raw_value(": ")?;
392
48
                value.serialize(&mut *self.serializer)?;
393
48
                self.serializer.writer.insert_newline()?;
394
            } else {
395
166
                self.serializer.writer.write_raw_value(key)?;
396
166
                value.serialize(&mut *self.serializer)?;
397
            }
398
214
            Ok(())
399
214
        }
400

            
401
17
        fn end(self) -> Result<Self::Ok, Self::Error> {
402
17
            if !self.is_implicit_map {
403
14
                self.serializer.writer.finish_nested()?;
404
3
            }
405
17
            Ok(())
406
17
        }
407
    }
408

            
409
    impl<'a, 'config, Output> SerializeStructVariant for &'a mut Serializer<'config, Output>
410
    where
411
        Output: Write,
412
    {
413
        type Error = core::fmt::Error;
414
        type Ok = ();
415

            
416
        fn serialize_field<T>(&mut self, key: &'static str, value: &T) -> Result<(), Self::Error>
417
        where
418
            T: serde::Serialize + ?Sized,
419
        {
420
            self.writer.write_raw_value(key)?;
421
            value.serialize(&mut **self)
422
        }
423

            
424
        fn end(self) -> Result<Self::Ok, Self::Error> {
425
            self.writer.finish_nested()
426
        }
427
    }
428

            
429
    impl<'a, 'config, Output> SerializeMap for MapSerializer<'a, 'config, Output>
430
    where
431
        Output: Write,
432
    {
433
        type Error = core::fmt::Error;
434
        type Ok = ();
435

            
436
2
        fn serialize_key<T>(&mut self, key: &T) -> Result<(), Self::Error>
437
2
        where
438
2
            T: serde::Serialize + ?Sized,
439
2
        {
440
2
            key.serialize(&mut *self.serializer)
441
2
        }
442

            
443
2
        fn serialize_value<T>(&mut self, value: &T) -> Result<(), Self::Error>
444
2
        where
445
2
            T: serde::Serialize + ?Sized,
446
2
        {
447
2
            if self.is_implicit_map {
448
2
                self.serializer.writer.write_raw_value(": ")?;
449
2
                value.serialize(&mut *self.serializer)?;
450
2
                self.serializer.writer.insert_newline()
451
            } else {
452
                value.serialize(&mut *self.serializer)
453
            }
454
2
        }
455

            
456
1
        fn end(self) -> Result<Self::Ok, Self::Error> {
457
1
            if !self.is_implicit_map {
458
                self.serializer.writer.finish_nested()?;
459
1
            }
460
1
            Ok(())
461
1
        }
462
    }
463
}
464

            
465
/// The configuration for a [`Serializer`].
466
#[derive(Default, Debug, Clone)]
467
#[non_exhaustive]
468
pub struct Config {
469
    /// The writer configuration.
470
    pub writer: writer::Config,
471
    /// Whether a map-like type at the root of the document should use the
472
    /// implicit map syntax.
473
    pub implicit_map_at_root: bool,
474
    /// Whether to include the names of structures in.
475
    pub anonymous_structs: bool,
476
}
477

            
478
impl Config {
479
    /// Returns the default configuration.
480
    ///
481
    /// The default configuration uses:
482
    ///
483
    /// - `writer`: [`writer::Config::Compact`]
484
    /// - `implicit_map_at_root`: `false`
485
    /// - `anonymous_structs`: `false`
486
    ///
487
    /// ```rust
488
    /// use std::collections::HashMap;
489
    ///
490
    /// let serialized = rsn::ser::Config::new()
491
    ///     .serialize(&HashMap::from([("hello", "world")]))
492
    ///     .unwrap();
493
    /// assert_eq!(serialized, r#"{"hello":"world"}"#)
494
    /// ```
495
    #[must_use]
496
3
    pub const fn new() -> Self {
497
3
        Self {
498
3
            writer: writer::Config::Compact,
499
3
            implicit_map_at_root: false,
500
3
            anonymous_structs: false,
501
3
        }
502
3
    }
503

            
504
    /// Returns the default configuration with nested indentation and newlines.
505
    ///
506
    /// ```rust
507
    /// use std::collections::HashMap;
508
    ///
509
    /// let serialized = rsn::ser::Config::pretty()
510
    ///     .serialize(&HashMap::from([("hello", "world")]))
511
    ///     .unwrap();
512
    /// assert_eq!(
513
    ///     serialized,
514
    ///     r#"{
515
    ///   "hello": "world"
516
    /// }"#
517
    /// );
518
    /// ```
519
    #[must_use]
520
9
    pub fn pretty() -> Self {
521
9
        Self {
522
9
            writer: writer::Config::Pretty {
523
9
                indentation: Cow::Borrowed("  "),
524
9
                newline: Cow::Borrowed("\n"),
525
9
            },
526
9
            ..Default::default()
527
9
        }
528
9
    }
529

            
530
    /// Sets [`Config::implicit_map_at_root`] and returns self.
531
    ///
532
    /// ```rust
533
    /// use std::collections::HashMap;
534
    ///
535
    /// let serialized = rsn::ser::Config::pretty()
536
    ///     .implicit_map_at_root(true)
537
    ///     .serialize(&HashMap::from([("hello", "world")]))
538
    ///     .unwrap();
539
    /// assert_eq!(serialized, "\"hello\": \"world\"\n");
540
    /// ```
541
    #[must_use]
542
4
    pub const fn implicit_map_at_root(mut self, implicit_map_at_root: bool) -> Self {
543
4
        self.implicit_map_at_root = implicit_map_at_root;
544
4
        self
545
4
    }
546

            
547
    /// Sets [`Config::anonymous_structs`] and returns self.
548
    ///
549
    /// ```rust
550
    /// use serde::Serialize;
551
    ///
552
    /// #[derive(Serialize)]
553
    /// struct Person {
554
    ///     name: &'static str,
555
    /// }
556
    ///
557
    /// // With anonymous structures enabled
558
    /// let anonymous_structs = rsn::ser::Config::new()
559
    ///     .anonymous_structs(true)
560
    ///     .serialize(&Person { name: "Bob" })
561
    ///     .unwrap();
562
    /// assert_eq!(anonymous_structs, r#"{name:"Bob"}"#);
563
    ///
564
    /// // The default configuration
565
    /// let default_config = rsn::ser::Config::new()
566
    ///     .serialize(&Person { name: "Bob" })
567
    ///     .unwrap();
568
    /// assert_eq!(default_config, r#"Person{name:"Bob"}"#);
569
    /// ```
570
    #[must_use]
571
3
    pub const fn anonymous_structs(mut self, anonymous_structs: bool) -> Self {
572
3
        self.anonymous_structs = anonymous_structs;
573
3
        self
574
3
    }
575

            
576
    /// Returns `value` serialized as Rsn with this configuration.
577
    ///
578
    /// ```rust
579
    /// let serialized = rsn::ser::Config::new().serialize(&vec![1, 2, 3]).unwrap();
580
    /// assert_eq!(serialized, "[1,2,3]");
581
    /// ```
582
    ///
583
    /// # Errors
584
    ///
585
    /// Rsn itself does not produce any errors while serializing values. This
586
    /// function will return errors that arise within `Serialize` implementations
587
    /// encountered while serializing `value`.
588
16
    pub fn serialize<S: Serialize>(&self, value: &S) -> Result<String, core::fmt::Error> {
589
16
        let mut serializer = Serializer::new(String::new(), self);
590
16
        value.serialize(&mut serializer)?;
591
16
        Ok(serializer.finish())
592
16
    }
593

            
594
    /// Returns `value` serialized as Rsn with this configuration.
595
    ///
596
    /// ```rust
597
    /// let serialized = rsn::ser::Config::new()
598
    ///     .serialize_to_vec(&vec![1, 2, 3])
599
    ///     .unwrap();
600
    /// assert_eq!(serialized, b"[1,2,3]");
601
    /// ```
602
    ///
603
    /// # Errors
604
    ///
605
    /// Rsn itself does not produce any errors while serializing values. This
606
    /// function will return errors that arise within `Serialize` implementations
607
    /// encountered while serializing `value`.
608
    pub fn serialize_to_vec<S: Serialize>(
609
        &self,
610
        value: &S,
611
    ) -> Result<alloc::vec::Vec<u8>, core::fmt::Error> {
612
        self.serialize(value).map(String::into_bytes)
613
    }
614
}
615

            
616
#[cfg(feature = "std")]
617
mod serialize_writer {
618
    use super::{Config, Serialize, Serializer, Write};
619

            
620
    struct Writer<T> {
621
        inner: T,
622
        written: usize,
623
        error: Option<std::io::Error>,
624
    }
625
    impl<T: std::io::Write> Write for Writer<T> {
626
        fn write_str(&mut self, s: &str) -> core::fmt::Result {
627
            match self.inner.write(s.as_bytes()) {
628
                Ok(written) => {
629
                    self.written += written;
630
                    Ok(())
631
                }
632
                Err(error) => {
633
                    assert!(
634
                        self.error.is_none(),
635
                        "should not have continued on write error"
636
                    );
637
                    self.error = Some(error);
638
                    Err(core::fmt::Error)
639
                }
640
            }
641
        }
642
    }
643
    impl Config {
644
        /// Serializes `value` into `writer` using this configuration.
645
        ///
646
        /// ```rust
647
        /// let mut serialized = Vec::new();
648
        /// rsn::ser::Config::new()
649
        ///     .serialize_to_writer(&vec![1, 2, 3], &mut serialized)
650
        ///     .unwrap();
651
        /// assert_eq!(serialized, b"[1,2,3]");
652
        /// ```
653
        ///
654
        /// # Errors
655
        ///
656
        /// Returns any errors occurring while serializing `value` or while
657
        /// writing to `writer`.
658
        #[allow(clippy::missing_panics_doc)]
659
        pub fn serialize_to_writer<S: Serialize, W: std::io::Write>(
660
            &self,
661
            value: &S,
662
            writer: W,
663
        ) -> std::io::Result<usize> {
664
            let mut writer = Writer {
665
                inner: writer,
666
                written: 0,
667
                error: None,
668
            };
669
            let mut serializer = Serializer::new(&mut writer, self);
670
            value
671
                .serialize(&mut serializer)
672
                .map_err(|_| writer.error.expect("should store error on error"))?;
673
            Ok(writer.written)
674
        }
675
    }
676
}
677

            
678
#[test]
679
1
fn serialization_test() {
680
    #[derive(Debug, serde::Serialize, serde::Deserialize, Eq, PartialEq)]
681
    struct BasicNamed {
682
        a: u32,
683
        b: i32,
684
    }
685

            
686
1
    let rendered = crate::to_string(&BasicNamed { a: 1, b: -1 }).expect("no errors");
687
1
    assert_eq!(rendered, "BasicNamed{a:1,b:-1}");
688
1
}