serde-structprop 0.3.0

Serde serializer and deserializer for the structprop config file format
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
//! Serde [`Serializer`](serde::Serializer) for the structprop format.
//!
//! The public entry point is [`to_string`].  Internally a `Serializer` walks
//! the serde data model and writes structprop text directly into an output
//! [`String`].
//!
//! # Type mapping
//!
//! | Rust / serde | Structprop output |
//! |---|---|
//! | `bool` | `true` or `false` scalar |
//! | `i8`–`i64`, `u8`–`u64` | bare integer scalar (e.g. `42`, `-7`) |
//! | `f32`, `f64` | bare float scalar (e.g. `3.14`) |
//! | `char` | bare single-character scalar (quoted if the character is special) |
//! | `String` / `&str` | bare scalar, or `"quoted"` if it contains spaces, tabs, newlines, carriage returns, `#`, `{`, `}`, or `=`, or is empty; yields `Error::UnsupportedType` if the value requires quoting and contains `"`, or if the value starts with `"` |
//! | `None` / `()` / unit struct | `null` scalar |
//! | newtype struct | transparent — serializes as the inner value |
//! | struct / map | `key { … }` block at the current indentation level |
//! | `Vec<T>` / sequence / tuple / tuple struct | `= { … }` inline list |
//! | unit enum variant | bare variant name scalar |
//! | newtype enum variant | `variant_name = <scalar or list>` |
//! | tuple enum variant | `variant_name = { … }` list |
//! | struct enum variant | `variant_name { … }` block |

use std::fmt::Write as FmtWrite;

use crate::error::{Error, Result};
use serde::ser::{self, Serialize};

// ---------------------------------------------------------------------------
// Public entry point
// ---------------------------------------------------------------------------

/// Serialize `value` into a structprop-formatted [`String`].
///
/// Top-level structs and maps produce a flat sequence of `key = value` /
/// `key { … }` entries with no enclosing braces.  Sequences produce a bare
/// `{\n … \n}` block.
///
/// # Errors
///
/// Returns [`Error::UnsupportedType`] if `T` contains raw byte slices, or
/// [`Error::Message`] for any other serde-level serialization error.
///
/// # Examples
///
/// ```
/// use serde::Serialize;
/// use serde_structprop::to_string;
///
/// #[derive(Serialize)]
/// struct Cfg { host: String, port: u16 }
///
/// let s = to_string(&Cfg { host: "localhost".into(), port: 8080 }).unwrap();
/// assert!(s.contains("host = localhost"));
/// assert!(s.contains("port = 8080"));
/// ```
pub fn to_string<T: Serialize>(value: &T) -> Result<String> {
    let mut ser = Serializer::new(0);
    value.serialize(&mut ser)?;
    Ok(ser.output)
}

// ---------------------------------------------------------------------------
// Serializer
// ---------------------------------------------------------------------------

/// Core serializer that accumulates structprop text in `output`.
///
/// `indent` is the current nesting depth; each level adds two spaces of
/// leading whitespace to each emitted line.
pub struct Serializer {
    /// The accumulated output string.
    pub(crate) output: String,
    /// Current indentation level in spaces.
    indent: usize,
    /// Set to `true` when the top-level call was `serialize_struct` or
    /// `serialize_map`.  Used by [`SeqSerializer`] to distinguish object
    /// items (which must be wrapped in inner `{ … }` braces) from scalars.
    is_object: bool,
}

impl Serializer {
    /// Create a new [`Serializer`] starting at `indent` spaces of indentation.
    fn new(indent: usize) -> Self {
        Serializer {
            output: String::new(),
            indent,
            is_object: false,
        }
    }

    /// Return a string of `self.indent` spaces.
    fn pad(&self) -> String {
        " ".repeat(self.indent)
    }
}

// ---------------------------------------------------------------------------
// Helpers
// ---------------------------------------------------------------------------

/// Wrap `s` in double quotes if it is empty or contains any of the following
/// characters: space (` `), tab (`\t`), newline (`\n`), carriage return
/// (`\r`), `#`, `{`, `}`, or `=`.  Otherwise return it unchanged.
///
/// Empty strings are always quoted so that they survive a round-trip: a bare
/// empty value would produce `key = ` with no token after `=`, which the
/// parser cannot recover from.
///
/// The structprop format has no escape sequences.  A `"` character that
/// appears in the interior of a value (not as the first character) can
/// survive as part of a bare (unquoted) term.  However two cases are
/// unrepresentable and return [`Error::UnsupportedType`]:
///
/// * A value that **requires quoting** (contains a special character or is
///   empty) **and also contains `"`** — there is no way to embed `"` inside
///   a quoted term.
/// * A value whose **first character is `"`** — the lexer always interprets
///   a leading `"` as the start of a quoted term, so the value would be
///   mis-parsed.
///
/// # Errors
///
/// Returns [`Error::UnsupportedType`] if `s` requires quoting and also
/// contains a `"` character.
fn escape(s: &str) -> Result<String> {
    let needs_quoting = s.is_empty()
        || s.starts_with('"')
        || s.chars()
            .any(|c| matches!(c, ' ' | '\t' | '\n' | '\r' | '#' | '{' | '}' | '='));

    if needs_quoting && s.contains('"') {
        return Err(Error::UnsupportedType(
            "string containing '\"' cannot be represented in quoted form (format has no escape sequences)",
        ));
    }

    if needs_quoting {
        Ok(format!("\"{s}\""))
    } else {
        Ok(s.to_owned())
    }
}

// ---------------------------------------------------------------------------
// serde::Serializer impl
// ---------------------------------------------------------------------------

impl<'a> ser::Serializer for &'a mut Serializer {
    type Ok = ();
    type Error = Error;

    /// Compound serializer types.
    type SerializeSeq = SeqSerializer<'a>;
    /// Compound serializer types.
    type SerializeTuple = SeqSerializer<'a>;
    /// Compound serializer types.
    type SerializeTupleStruct = SeqSerializer<'a>;
    /// Compound serializer types.
    type SerializeTupleVariant = SeqSerializer<'a>;
    /// Compound serializer types.
    type SerializeMap = MapSerializer<'a>;
    /// Compound serializer types.
    type SerializeStruct = MapSerializer<'a>;
    /// Compound serializer types.
    type SerializeStructVariant = MapSerializer<'a>;

    fn serialize_bool(self, v: bool) -> Result<()> {
        self.output.push_str(if v { "true" } else { "false" });
        Ok(())
    }

    fn serialize_i8(self, v: i8) -> Result<()> {
        write!(self.output, "{v}").map_err(|e| Error::Message(e.to_string()))
    }

    fn serialize_i16(self, v: i16) -> Result<()> {
        write!(self.output, "{v}").map_err(|e| Error::Message(e.to_string()))
    }

    fn serialize_i32(self, v: i32) -> Result<()> {
        write!(self.output, "{v}").map_err(|e| Error::Message(e.to_string()))
    }

    fn serialize_i64(self, v: i64) -> Result<()> {
        write!(self.output, "{v}").map_err(|e| Error::Message(e.to_string()))
    }

    fn serialize_u8(self, v: u8) -> Result<()> {
        write!(self.output, "{v}").map_err(|e| Error::Message(e.to_string()))
    }

    fn serialize_u16(self, v: u16) -> Result<()> {
        write!(self.output, "{v}").map_err(|e| Error::Message(e.to_string()))
    }

    fn serialize_u32(self, v: u32) -> Result<()> {
        write!(self.output, "{v}").map_err(|e| Error::Message(e.to_string()))
    }

    fn serialize_u64(self, v: u64) -> Result<()> {
        write!(self.output, "{v}").map_err(|e| Error::Message(e.to_string()))
    }

    fn serialize_f32(self, v: f32) -> Result<()> {
        write!(self.output, "{v}").map_err(|e| Error::Message(e.to_string()))
    }

    fn serialize_f64(self, v: f64) -> Result<()> {
        write!(self.output, "{v}").map_err(|e| Error::Message(e.to_string()))
    }

    fn serialize_char(self, v: char) -> Result<()> {
        // Route through escape() so special characters are quoted.
        self.output.push_str(&escape(&v.to_string())?);
        Ok(())
    }

    fn serialize_str(self, v: &str) -> Result<()> {
        self.output.push_str(&escape(v)?);
        Ok(())
    }

    fn serialize_bytes(self, _v: &[u8]) -> Result<()> {
        Err(Error::UnsupportedType("bytes"))
    }

    fn serialize_none(self) -> Result<()> {
        self.output.push_str("null");
        Ok(())
    }

    fn serialize_some<T: Serialize + ?Sized>(self, value: &T) -> Result<()> {
        value.serialize(self)
    }

    fn serialize_unit(self) -> Result<()> {
        self.output.push_str("null");
        Ok(())
    }

    fn serialize_unit_struct(self, _name: &'static str) -> Result<()> {
        self.serialize_unit()
    }

    fn serialize_unit_variant(
        self,
        _name: &'static str,
        _index: u32,
        variant: &'static str,
    ) -> Result<()> {
        self.serialize_str(variant)
    }

    fn serialize_newtype_struct<T: Serialize + ?Sized>(
        self,
        _name: &'static str,
        value: &T,
    ) -> Result<()> {
        value.serialize(self)
    }

    fn serialize_newtype_variant<T: Serialize + ?Sized>(
        self,
        _name: &'static str,
        _index: u32,
        variant: &'static str,
        value: &T,
    ) -> Result<()> {
        // Encode as `variant = <payload>` (scalar) or `variant { … }` (object block)
        // so the parser produces Object({"variant": payload}), which is exactly what
        // deserialize_enum expects for newtype variants.
        let start_pos = self.output.len();
        let mut ms = MapSerializer {
            ser: self,
            current_key: None,
            variant_name: None,
            start_pos,
        };
        ms.write_kv(variant, value)
    }

    fn serialize_seq(self, _len: Option<usize>) -> Result<Self::SerializeSeq> {
        Ok(SeqSerializer {
            parent: self,
            items: Vec::new(),
            variant: None,
        })
    }

    fn serialize_tuple(self, len: usize) -> Result<Self::SerializeTuple> {
        self.serialize_seq(Some(len))
    }

    fn serialize_tuple_struct(
        self,
        _name: &'static str,
        len: usize,
    ) -> Result<Self::SerializeTupleStruct> {
        self.serialize_seq(Some(len))
    }

    fn serialize_tuple_variant(
        self,
        _name: &'static str,
        _index: u32,
        variant: &'static str,
        _len: usize,
    ) -> Result<Self::SerializeTupleVariant> {
        Ok(SeqSerializer {
            parent: self,
            items: Vec::new(),
            variant: Some(variant.to_owned()),
        })
    }

    fn serialize_map(self, _len: Option<usize>) -> Result<Self::SerializeMap> {
        self.is_object = true;
        let start_pos = self.output.len();
        Ok(MapSerializer {
            ser: self,
            current_key: None,
            variant_name: None,
            start_pos,
        })
    }

    fn serialize_struct(self, _name: &'static str, len: usize) -> Result<Self::SerializeStruct> {
        self.serialize_map(Some(len))
    }

    fn serialize_struct_variant(
        self,
        _name: &'static str,
        _index: u32,
        variant: &'static str,
        _len: usize,
    ) -> Result<Self::SerializeStructVariant> {
        let start_pos = self.output.len();
        // Fields inside the variant wrapper must sit two levels deeper than the
        // wrapper header itself, so bump indent before handing `self` over to
        // the MapSerializer.  `end()` will derive the header/footer pad from
        // `ser.indent.saturating_sub(2)`, which then equals the original indent.
        self.indent += 2;
        Ok(MapSerializer {
            ser: self,
            current_key: None,
            variant_name: Some(variant.to_owned()),
            start_pos,
        })
    }
}

// ---------------------------------------------------------------------------
// SeqSerializer – handles sequences / arrays
// ---------------------------------------------------------------------------

/// [`ser::SerializeSeq`] (and related tuple impls) that collects rendered items
/// then emits them as a `{ … }` block.
pub struct SeqSerializer<'a> {
    parent: &'a mut Serializer,
    /// Each element serialized to a string plus a flag indicating whether it
    /// is a struct/map (object) that needs wrapping in inner `{ … }` braces.
    items: Vec<(bool, String)>,
    /// Set for tuple variants: the variant name to wrap the array under.
    variant: Option<String>,
}

impl ser::SerializeSeq for SeqSerializer<'_> {
    type Ok = ();
    type Error = Error;

    fn serialize_element<T: Serialize + ?Sized>(&mut self, value: &T) -> Result<()> {
        let mut inner = Serializer::new(0);
        value.serialize(&mut inner)?;
        self.items.push((inner.is_object, inner.output));
        Ok(())
    }

    fn end(self) -> Result<()> {
        let pad = self.parent.pad();
        let inner_pad = " ".repeat(self.parent.indent + 2);
        let deep_pad = " ".repeat(self.parent.indent + 4);
        writeln!(self.parent.output, "{{").map_err(|e| Error::Message(e.to_string()))?;
        for (is_object, item) in &self.items {
            let trimmed = item.trim_end();
            if *is_object {
                // Struct/map item: wrap in inner `{ … }` braces, indenting each
                // field line by an extra two spaces (matching the Python reference).
                writeln!(self.parent.output, "{inner_pad}{{")
                    .map_err(|e| Error::Message(e.to_string()))?;
                for line in trimmed.lines() {
                    writeln!(self.parent.output, "{deep_pad}{line}")
                        .map_err(|e| Error::Message(e.to_string()))?;
                }
                writeln!(self.parent.output, "{inner_pad}}}")
                    .map_err(|e| Error::Message(e.to_string()))?;
            } else {
                // Scalar item: emit on a single indented line.
                writeln!(self.parent.output, "{inner_pad}{trimmed}")
                    .map_err(|e| Error::Message(e.to_string()))?;
            }
        }
        writeln!(self.parent.output, "{pad}}}").map_err(|e| Error::Message(e.to_string()))
    }
}

impl ser::SerializeTuple for SeqSerializer<'_> {
    type Ok = ();
    type Error = Error;

    fn serialize_element<T: Serialize + ?Sized>(&mut self, value: &T) -> Result<()> {
        ser::SerializeSeq::serialize_element(self, value)
    }

    fn end(self) -> Result<()> {
        ser::SerializeSeq::end(self)
    }
}

impl ser::SerializeTupleStruct for SeqSerializer<'_> {
    type Ok = ();
    type Error = Error;

    fn serialize_field<T: Serialize + ?Sized>(&mut self, value: &T) -> Result<()> {
        ser::SerializeSeq::serialize_element(self, value)
    }

    fn end(self) -> Result<()> {
        ser::SerializeSeq::end(self)
    }
}

impl ser::SerializeTupleVariant for SeqSerializer<'_> {
    type Ok = ();
    type Error = Error;

    fn serialize_field<T: Serialize + ?Sized>(&mut self, value: &T) -> Result<()> {
        ser::SerializeSeq::serialize_element(self, value)
    }

    fn end(self) -> Result<()> {
        // Emit as `variant = { item1\n  item2\n … }` so the parser produces
        // Object({"variant": Array([…])}), matching what deserialize_enum expects.
        let variant = self.variant.ok_or_else(|| {
            Error::Message("variant name missing in SerializeTupleVariant::end".into())
        })?;
        let pad = self.parent.pad();
        let inner_pad = " ".repeat(self.parent.indent + 2);
        let deep_pad = " ".repeat(self.parent.indent + 4);
        writeln!(self.parent.output, "{pad}{} = {{", escape(&variant)?)
            .map_err(|e| Error::Message(e.to_string()))?;
        for (is_object, item) in &self.items {
            let trimmed = item.trim_end();
            if *is_object {
                writeln!(self.parent.output, "{inner_pad}{{")
                    .map_err(|e| Error::Message(e.to_string()))?;
                for line in trimmed.lines() {
                    writeln!(self.parent.output, "{deep_pad}{line}")
                        .map_err(|e| Error::Message(e.to_string()))?;
                }
                writeln!(self.parent.output, "{inner_pad}}}")
                    .map_err(|e| Error::Message(e.to_string()))?;
            } else {
                writeln!(self.parent.output, "{inner_pad}{trimmed}")
                    .map_err(|e| Error::Message(e.to_string()))?;
            }
        }
        writeln!(self.parent.output, "{pad}}}").map_err(|e| Error::Message(e.to_string()))
    }
}

// ---------------------------------------------------------------------------
// KeySerializer – accepts only string keys; rejects everything else
// ---------------------------------------------------------------------------

/// A minimal serializer that collects a `str`/`String` map key and returns
/// [`Error::KeyMustBeString`] for every other type, including `char` and
/// unit-enum variants.  Only `serialize_str` (and `serialize_newtype_struct`
/// delegating to it) succeed.
struct KeySerializer(String);

impl ser::Serializer for &mut KeySerializer {
    type Ok = ();
    type Error = Error;
    type SerializeSeq = ser::Impossible<(), Error>;
    type SerializeTuple = ser::Impossible<(), Error>;
    type SerializeTupleStruct = ser::Impossible<(), Error>;
    type SerializeTupleVariant = ser::Impossible<(), Error>;
    type SerializeMap = ser::Impossible<(), Error>;
    type SerializeStruct = ser::Impossible<(), Error>;
    type SerializeStructVariant = ser::Impossible<(), Error>;

    fn serialize_str(self, v: &str) -> Result<()> {
        v.clone_into(&mut self.0);
        Ok(())
    }

    fn serialize_bool(self, _v: bool) -> Result<()> {
        Err(Error::KeyMustBeString)
    }
    fn serialize_i8(self, _v: i8) -> Result<()> {
        Err(Error::KeyMustBeString)
    }
    fn serialize_i16(self, _v: i16) -> Result<()> {
        Err(Error::KeyMustBeString)
    }
    fn serialize_i32(self, _v: i32) -> Result<()> {
        Err(Error::KeyMustBeString)
    }
    fn serialize_i64(self, _v: i64) -> Result<()> {
        Err(Error::KeyMustBeString)
    }
    fn serialize_u8(self, _v: u8) -> Result<()> {
        Err(Error::KeyMustBeString)
    }
    fn serialize_u16(self, _v: u16) -> Result<()> {
        Err(Error::KeyMustBeString)
    }
    fn serialize_u32(self, _v: u32) -> Result<()> {
        Err(Error::KeyMustBeString)
    }
    fn serialize_u64(self, _v: u64) -> Result<()> {
        Err(Error::KeyMustBeString)
    }
    fn serialize_f32(self, _v: f32) -> Result<()> {
        Err(Error::KeyMustBeString)
    }
    fn serialize_f64(self, _v: f64) -> Result<()> {
        Err(Error::KeyMustBeString)
    }
    fn serialize_char(self, _v: char) -> Result<()> {
        Err(Error::KeyMustBeString)
    }
    fn serialize_bytes(self, _v: &[u8]) -> Result<()> {
        Err(Error::KeyMustBeString)
    }
    fn serialize_none(self) -> Result<()> {
        Err(Error::KeyMustBeString)
    }
    fn serialize_some<T: Serialize + ?Sized>(self, _v: &T) -> Result<()> {
        Err(Error::KeyMustBeString)
    }
    fn serialize_unit(self) -> Result<()> {
        Err(Error::KeyMustBeString)
    }
    fn serialize_unit_struct(self, _name: &'static str) -> Result<()> {
        Err(Error::KeyMustBeString)
    }
    fn serialize_unit_variant(
        self,
        _name: &'static str,
        _idx: u32,
        _variant: &'static str,
    ) -> Result<()> {
        Err(Error::KeyMustBeString)
    }
    fn serialize_newtype_struct<T: Serialize + ?Sized>(
        self,
        _name: &'static str,
        value: &T,
    ) -> Result<()> {
        value.serialize(self)
    }
    fn serialize_newtype_variant<T: Serialize + ?Sized>(
        self,
        _name: &'static str,
        _idx: u32,
        _variant: &'static str,
        _value: &T,
    ) -> Result<()> {
        Err(Error::KeyMustBeString)
    }
    fn serialize_seq(self, _len: Option<usize>) -> Result<Self::SerializeSeq> {
        Err(Error::KeyMustBeString)
    }
    fn serialize_tuple(self, _len: usize) -> Result<Self::SerializeTuple> {
        Err(Error::KeyMustBeString)
    }
    fn serialize_tuple_struct(
        self,
        _name: &'static str,
        _len: usize,
    ) -> Result<Self::SerializeTupleStruct> {
        Err(Error::KeyMustBeString)
    }
    fn serialize_tuple_variant(
        self,
        _name: &'static str,
        _idx: u32,
        _variant: &'static str,
        _len: usize,
    ) -> Result<Self::SerializeTupleVariant> {
        Err(Error::KeyMustBeString)
    }
    fn serialize_map(self, _len: Option<usize>) -> Result<Self::SerializeMap> {
        Err(Error::KeyMustBeString)
    }
    fn serialize_struct(self, _name: &'static str, _len: usize) -> Result<Self::SerializeStruct> {
        Err(Error::KeyMustBeString)
    }
    fn serialize_struct_variant(
        self,
        _name: &'static str,
        _idx: u32,
        _variant: &'static str,
        _len: usize,
    ) -> Result<Self::SerializeStructVariant> {
        Err(Error::KeyMustBeString)
    }
}

// ---------------------------------------------------------------------------
// MapSerializer – handles maps and structs
// ---------------------------------------------------------------------------

/// [`ser::SerializeMap`] (and struct impls) that writes `key = value` /
/// `key { … }` entries one at a time.
pub struct MapSerializer<'a> {
    ser: &'a mut Serializer,
    /// The most recently serialized key, waiting for its value.
    current_key: Option<String>,
    /// If `Some`, wrap all emitted content in a `variant_name { … }` block.
    variant_name: Option<String>,
    /// Byte offset into `ser.output` at which this value began being written.
    /// Used by struct-variant serialization to insert the header at the correct
    /// position rather than at the start of the entire output buffer.
    start_pos: usize,
}

impl MapSerializer<'_> {
    /// Serialize a single `key = value` or `key { … }` entry into `self.ser`.
    fn write_kv<T: Serialize + ?Sized>(&mut self, key: &str, value: &T) -> Result<()> {
        let indent = self.ser.indent;
        let pad = " ".repeat(indent);

        // Serialize the value at the *current* indentation level.  This single
        // call is sufficient for scalars and for array blocks, whose output is
        // already formatted correctly:
        //
        //   scalar  →  no newlines, used directly as the RHS of `key = value`
        //   array   →  `{\n<items at indent+2>\n<indent>}\n`, written inline
        //               as `key = {…}` by `writeln!` below
        //
        // Only struct/map (multi-line, not starting with `{` or `"`) needs the
        // content indented two levels deeper than the current key, so we
        // re-serialize those at `indent+2`.  This is the only case where
        // `Serialize` is invoked twice.
        let mut first = Serializer::new(indent);
        value.serialize(&mut first)?;
        let rendered = first.output;

        if rendered.contains('\n')
            && !rendered.trim_start().starts_with('{')
            && !rendered.trim_start().starts_with('"')
        {
            // Multi-line object block → `key {\n  <fields at indent+2>\n}\n`
            // Re-serialize at the correct child indentation so nested fields
            // sit two levels deeper than the enclosing key.  We must not
            // blindly re-indent the first-pass output line-by-line because
            // doing so would corrupt any quoted scalar whose value contains a
            // literal newline (the continuation line is not a separate field).
            writeln!(self.ser.output, "{pad}{} {{", escape(key)?)
                .map_err(|e| Error::Message(e.to_string()))?;
            let mut inner = Serializer::new(indent + 2);
            value.serialize(&mut inner)?;
            self.ser.output.push_str(&inner.output);
            writeln!(self.ser.output, "{pad}}}").map_err(|e| Error::Message(e.to_string()))?;
        } else if rendered.contains('\n') {
            // Multi-line array block starting with `{`.
            // The first-pass output is already at the right indentation
            // (`{` inline, items at `indent+2`, `}` at `indent`), so we
            // reuse it without a second `serialize` call.
            writeln!(
                self.ser.output,
                "{pad}{} = {}",
                escape(key)?,
                rendered.trim_end()
            )
            .map_err(|e| Error::Message(e.to_string()))?;
        } else {
            // Scalar (no newlines, or a quoted scalar — both fit on one line).
            let rendered = rendered.trim_end_matches('\n');
            writeln!(self.ser.output, "{pad}{} = {rendered}", escape(key)?)
                .map_err(|e| Error::Message(e.to_string()))?;
        }
        Ok(())
    }
}

impl ser::SerializeMap for MapSerializer<'_> {
    type Ok = ();
    type Error = Error;

    fn serialize_key<T: Serialize + ?Sized>(&mut self, key: &T) -> Result<()> {
        let mut ks = KeySerializer(String::new());
        key.serialize(&mut ks)?;
        self.current_key = Some(ks.0);
        Ok(())
    }

    fn serialize_value<T: Serialize + ?Sized>(&mut self, value: &T) -> Result<()> {
        let key = self
            .current_key
            .take()
            .ok_or_else(|| Error::Parse("serialize_value called before serialize_key".into()))?;
        self.write_kv(&key, value)
    }

    fn end(self) -> Result<()> {
        if let Some(variant) = self.variant_name {
            // Wrap the content we already wrote in `variant { … }`.
            let pad = " ".repeat(self.ser.indent.saturating_sub(2));
            let header = format!("{pad}{} {{\n", escape(&variant)?);
            let footer = format!("{pad}}}\n");
            self.ser.output.insert_str(self.start_pos, &header);
            self.ser.output.push_str(&footer);
        }
        Ok(())
    }
}

impl ser::SerializeStruct for MapSerializer<'_> {
    type Ok = ();
    type Error = Error;

    fn serialize_field<T: Serialize + ?Sized>(
        &mut self,
        key: &'static str,
        value: &T,
    ) -> Result<()> {
        self.write_kv(key, value)
    }

    fn end(self) -> Result<()> {
        ser::SerializeMap::end(self)
    }
}

impl ser::SerializeStructVariant for MapSerializer<'_> {
    type Ok = ();
    type Error = Error;

    fn serialize_field<T: Serialize + ?Sized>(
        &mut self,
        key: &'static str,
        value: &T,
    ) -> Result<()> {
        self.write_kv(key, value)
    }

    fn end(self) -> Result<()> {
        ser::SerializeMap::end(self)
    }
}