config-disassembler 0.11.11

Disassemble config files into smaller files and reassemble on demand.
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
//! XML parser that preserves CDATA sections.
//! Uses quick-xml directly to distinguish CDATA from regular text.
//!
//! In quick-xml 0.38+, entity references (", ", etc.) are emitted as
//! Event::GeneralRef. We accumulate raw text + entity refs, then unescape once
//! to preserve whitespace between entities (quick-xml can drop spaces when
//! emitting Text/GeneralRef separately).

use quick_xml::escape::unescape;
use quick_xml::events::Event;
use quick_xml::Reader;
use quick_xml::XmlVersion;
use serde_json::{Map, Value};

/// Append raw entity reference to buffer (e.g. "quot" -> """).
fn append_entity_to_raw(ref_: &quick_xml::events::BytesRef<'_>, raw: &mut String) {
    raw.push('&');
    raw.push_str(ref_.as_ref());
    raw.push(';');
}

/// Append CDATA content to the current element's "#cdata" buffer. Silently noops when the
/// stack is empty; quick-xml rejects CDATA outside an element before reaching this point.
fn append_cdata_to_current(stack: &mut [(String, Map<String, Value>)], content: &str) {
    if let Some((_, elem)) = stack.last_mut() {
        let merged = match elem.get("#cdata").and_then(|v| v.as_str()) {
            Some(prev) => format!("{}{}", prev, content),
            None => content.to_string(),
        };
        elem.insert("#cdata".to_string(), Value::String(merged));
    }
}

/// Append comment content to the current element's "#comment" buffer. Mirrors
/// `append_cdata_to_current`: multiple sibling `<!--...-->` comments under the same
/// element accumulate into one string rather than the second overwriting the first
/// (the previous behavior via a plain `insert`), the same way multiple adjacent CDATA
/// sections and multiple text runs between comments (`#text-tail`) already concatenate
/// rather than clobber. Silently noops when the stack is empty; quick-xml rejects a
/// comment outside an element before reaching this point.
fn append_comment_to_current(stack: &mut [(String, Map<String, Value>)], content: &str) {
    if let Some((_, elem)) = stack.last_mut() {
        let merged = match elem.get("#comment").and_then(|v| v.as_str()) {
            Some(prev) => format!("{}{}", prev, content),
            None => content.to_string(),
        };
        elem.insert("#comment".to_string(), Value::String(merged));
    }
}

/// Attach a finished child element (from Event::End or Event::Empty) to its parent -
/// or record it as the root when the stack is empty.
fn attach_child_to_parent(
    stack: &mut [(String, Map<String, Value>)],
    name: String,
    value: Value,
    root_name: &mut Option<String>,
    root_value: &mut Option<Value>,
) {
    let Some((_, parent)) = stack.last_mut() else {
        *root_name = Some(name);
        *root_value = Some(value);
        return;
    };
    match parent.get_mut(&name) {
        Some(Value::Array(arr)) => arr.push(value),
        Some(_) => {
            let prev = parent.remove(&name).expect("key checked above");
            parent.insert(name, Value::Array(vec![prev, value]));
        }
        None => {
            parent.insert(name, value);
        }
    }
}

/// Flush accumulated raw text buffer: unescape entities and add to current element.
///
/// Runs on every text run between tags, most of them indentation, so it avoids
/// allocating where the outcome does not need it: a whitespace-only run onto text
/// the element already has is dropped before unescaping, and appends/replacements
/// edit the stored string in place instead of copying it out and re-inserting it.
fn flush_text_buffer(
    raw: &mut String,
    stack: &mut [(String, Map<String, Value>)],
    is_after_comment: bool,
) {
    if raw.is_empty() {
        return;
    }
    let Some((_, elem)) = stack.last_mut() else {
        raw.clear();
        return;
    };
    // Text after a comment accumulates separately, as #text-tail; the rules for
    // appending to it are the same as for #text.
    let key = if is_after_comment {
        "#text-tail"
    } else {
        "#text"
    };

    // A text run that is entirely whitespace, appended onto content #text/#text-tail
    // already accumulated for this element, is pure inter-tag formatting (e.g. the
    // indentation the writer itself inserted between two shard-level tags) - it must
    // not grow the stored value, or every subsequent parse of the writer's own output
    // re-absorbs and re-emits it, growing without bound. A whitespace-only *first* run
    // (the insert at the bottom) is still stored as-is: that's the existing, accepted
    // behavior for e.g. leading indentation before a child element captured as an
    // element's own #text (see the CDATA/comment-adjacent tests elsewhere in this file).
    //
    // That drop is decided here, on the raw run, before unescaping: a run that is
    // whitespace has no entity references, so it unescapes to itself.
    let has_text = matches!(elem.get(key), Some(Value::String(_)));
    if has_text && raw.trim().is_empty() {
        raw.clear();
        return;
    }

    let text = unescape(raw.as_str()).unwrap_or_default().into_owned();
    raw.clear();
    if text.is_empty() {
        return;
    }
    let is_whitespace_only_run = text.trim().is_empty();

    match elem.get_mut(key) {
        Some(Value::String(prev)) => {
            // This branch also covers what used to be a separate `elem.contains_key
            // ("#cdata")` case that unconditionally overwrote #text - e.g. for
            // `<a>real<![CDATA[x]]>tail</a>`, "real" is flushed into #text as the first
            // run *before* the CDATA event runs (#cdata isn't set yet), so the old
            // dedicated branch's blind `insert` on the trailing "tail" flush silently
            // discarded "real" the moment #cdata became present. Falling through to this
            // append-or-replace logic uniformly (whether or not #cdata is set) handles
            // both orderings correctly: cdata-then-trailing-whitespace still lands in
            // #text exactly as before (no prior #text to preserve), and
            // text-then-cdata-then-trailing-whitespace now keeps the earlier real text.
            //
            // Was `val_parsed.as_str()`: parse_text_value() trims before type-inferring, so
            // e.g. a second text run "( " (real trailing space) got silently trimmed to "("
            // when appended onto an earlier whitespace-only run (typical: leading indent
            // before a child tag, flushed into #text first). Worse, a purely-numeric/bool
            // second run (e.g. "42") would infer to a non-string Value, `.as_str()` would
            // return None, and the whole append would silently no-op, losing it entirely.
            // The untrimmed `text` is appended as-is, guarded by
            // `is_whitespace_only_run` (see above).
            //
            // Additionally: if `prev` (the #text accumulated so far) is itself pure
            // whitespace - typically indentation flushed before a child element, which on
            // its own would have been stripped later as insignificant (strip_whitespace.rs)
            // - concatenating real content onto it permanently bakes that whitespace into
            // the merged value, where the later stripping pass can no longer tell it apart
            // from real content and never removes it. On the next disassemble/reassemble
            // cycle the writer regenerates its own equivalent separator whitespace *in
            // addition* to this now-permanent prefix, so the file gains one more copy of
            // it every round trip. Replacing rather than concatenating in this case
            // (identically for #text-tail) drops the meaningless prefix instead of
            // durably fusing it to the data.
            //
            // The replacement itself is also trimmed on its *leading* edge only (trailing
            // whitespace is real - see the "( " test above): this run reached the parser
            // as a single, unbroken slice of character data with no intervening tag (that's
            // exactly why it's here, in the "already have a #text" branch, rather than
            // being its own separate flush), so any leading whitespace on it is exactly as
            // indistinguishable from formatting as `prev` was. Left untrimmed, the writer's
            // own unconditional separator after the child-elements block collides with this
            // run's baked-in leading whitespace and doubles up on every subsequent
            // disassemble/reassemble cycle - the same unbounded-growth failure mode as
            // `prev` itself, just one write/read cycle later.
            //
            // Both edits happen in place on the stored string, keeping the key's
            // position (as re-inserting an existing key did).
            if !is_whitespace_only_run {
                if prev.trim().is_empty() {
                    prev.clear();
                    prev.push_str(text.trim_start());
                } else {
                    prev.push_str(&text);
                }
            }
        }
        _ => {
            elem.insert(key.to_string(), Value::String(text));
        }
    }
}

/// Parse XML string to JSON Value, preserving CDATA as #cdata key.
/// Produces the same structure as quickxml_to_serde but with #cdata for CDATA content.
pub fn parse_xml_with_cdata(xml: &str) -> Result<Value, quick_xml::Error> {
    let mut reader = Reader::from_str(xml);
    reader.config_mut().trim_text(false);

    let mut stack: Vec<(String, Map<String, Value>)> = Vec::new();
    let mut root_name: Option<String> = None;
    let mut root_value: Option<Value> = None;
    let mut text_buffer = String::new();
    let mut text_buffer_after_comment = false;

    let mut buf = Vec::new();
    loop {
        match reader.read_event_into(&mut buf) {
            Ok(Event::Start(e)) => {
                flush_text_buffer(&mut text_buffer, &mut stack, text_buffer_after_comment);
                text_buffer_after_comment = false;
                let name = e.name().as_ref().to_string();
                let mut attrs = Map::new();
                for a in e.attributes().flatten() {
                    let key = format!("@{}", a.key.as_ref());
                    let val = a
                        .normalized_value(XmlVersion::Implicit1_0)
                        .unwrap_or_default();
                    attrs.insert(key, Value::String(val.to_string()));
                }
                stack.push((name, attrs));
            }
            Ok(Event::End(_e)) => {
                flush_text_buffer(&mut text_buffer, &mut stack, text_buffer_after_comment);
                text_buffer_after_comment = false;
                // `stack.pop()` only returns None on malformed XML, which quick-xml rejects
                // before reaching here; silently skip when it does.
                if let Some((popped_name, elem)) = stack.pop() {
                    attach_child_to_parent(
                        &mut stack,
                        popped_name,
                        Value::Object(elem),
                        &mut root_name,
                        &mut root_value,
                    );
                }
            }
            Ok(Event::Empty(e)) => {
                flush_text_buffer(&mut text_buffer, &mut stack, text_buffer_after_comment);
                text_buffer_after_comment = false;
                let name = e.name().as_ref().to_string();
                let mut attrs = Map::new();
                for a in e.attributes().flatten() {
                    let key = format!("@{}", a.key.as_ref());
                    let val = a
                        .normalized_value(XmlVersion::Implicit1_0)
                        .unwrap_or_default();
                    attrs.insert(key, Value::String(val.to_string()));
                }
                attach_child_to_parent(
                    &mut stack,
                    name,
                    Value::Object(attrs),
                    &mut root_name,
                    &mut root_value,
                );
            }
            Ok(Event::Text(e)) => {
                // Deliberately does NOT touch `text_buffer_after_comment` here. It used
                // to be re-derived on every Text event as `elem.contains_key("#comment")`,
                // which is a stale, persistent check (the key is never removed) rather
                // than "did a comment immediately precede this text". That misrouted
                // trailing whitespace after `<!--c--><![CDATA[x]]>` into `#text-tail`
                // (comment-shaped) instead of `#text` (cdata-shaped), even though the
                // CDATA handler below had already reset the flag to false - re-parsing
                // the disassembled output then re-triggered the same misroute, growing
                // an extra blank #text-tail line on every successive round trip. The
                // flag is now a proper transient signal: Comment sets it true, every
                // other event that can intervene (Start/End/Empty/CData) resets it false.
                text_buffer.push_str(e.as_ref());
            }
            Ok(Event::Comment(e)) => {
                flush_text_buffer(&mut text_buffer, &mut stack, text_buffer_after_comment);
                let content = e.as_ref().to_string();
                append_comment_to_current(&mut stack, &content);
                text_buffer_after_comment = true;
            }
            Ok(Event::GeneralRef(ref_)) => {
                append_entity_to_raw(&ref_, &mut text_buffer);
            }
            Ok(Event::CData(e)) => {
                flush_text_buffer(&mut text_buffer, &mut stack, text_buffer_after_comment);
                text_buffer_after_comment = false;
                append_cdata_to_current(&mut stack, e.as_ref());
            }
            Ok(Event::Eof) => break,
            Ok(_) => {}
            Err(e) => return Err(e),
        }
        buf.clear();
    }

    if let (Some(name), Some(value)) = (root_name, root_value) {
        let mut root = Map::new();
        root.insert(name, value);
        Ok(Value::Object(root))
    } else {
        Ok(Value::Object(Map::new()))
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn append_cdata_to_current_noops_on_empty_stack() {
        // Defensive path: CDATA emitted with no open element (unreachable via quick-xml but
        // the helper still handles it gracefully without panicking).
        let mut stack: Vec<(String, Map<String, Value>)> = Vec::new();
        append_cdata_to_current(&mut stack, "ignored");
        assert!(stack.is_empty());
    }

    #[test]
    fn append_cdata_to_current_sets_and_appends() {
        // First call sets `#cdata`; second call appends (covers both match arms).
        let mut stack: Vec<(String, Map<String, Value>)> = vec![("r".to_string(), Map::new())];
        append_cdata_to_current(&mut stack, "one");
        append_cdata_to_current(&mut stack, "two");
        let (_, elem) = stack.last().unwrap();
        assert_eq!(elem.get("#cdata").and_then(|v| v.as_str()), Some("onetwo"));
    }

    #[test]
    fn append_comment_to_current_noops_on_empty_stack() {
        // Defensive path: a comment emitted with no open element (unreachable via
        // quick-xml but the helper still handles it gracefully without panicking).
        let mut stack: Vec<(String, Map<String, Value>)> = Vec::new();
        append_comment_to_current(&mut stack, "ignored");
        assert!(stack.is_empty());
    }

    #[test]
    fn append_comment_to_current_sets_and_appends() {
        // First call sets `#comment`; second call appends (covers both match arms).
        let mut stack: Vec<(String, Map<String, Value>)> = vec![("r".to_string(), Map::new())];
        append_comment_to_current(&mut stack, "first");
        append_comment_to_current(&mut stack, "second");
        let (_, elem) = stack.last().unwrap();
        assert_eq!(
            elem.get("#comment").and_then(|v| v.as_str()),
            Some("firstsecond")
        );
    }

    #[test]
    fn parse_xml_with_cdata_simple_element() {
        let xml = r#"<root><a>hello</a></root>"#;
        let v = parse_xml_with_cdata(xml).unwrap();
        let root = v.get("root").and_then(|r| r.as_object()).unwrap();
        let a = root.get("a").and_then(|a| a.as_object()).unwrap();
        assert_eq!(a.get("#text").and_then(|t| t.as_str()), Some("hello"));
    }

    #[test]
    fn parse_xml_with_cdata_preserves_cdata() {
        let xml = r#"<root><x><![CDATA[<escaped>]]></x></root>"#;
        let v = parse_xml_with_cdata(xml).unwrap();
        let root = v.get("root").and_then(|r| r.as_object()).unwrap();
        let x = root.get("x").and_then(|x| x.as_object()).unwrap();
        assert_eq!(x.get("#cdata").and_then(|c| c.as_str()), Some("<escaped>"));
    }

    #[test]
    fn parse_xml_with_cdata_empty_element() {
        let xml = r#"<root><empty/></root>"#;
        let v = parse_xml_with_cdata(xml).unwrap();
        let root = v.get("root").and_then(|r| r.as_object()).unwrap();
        assert!(root.get("empty").is_some());
    }

    #[test]
    fn parse_xml_with_cdata_comment() {
        let xml = r#"<root><!-- comment --><a>1</a></root>"#;
        let v = parse_xml_with_cdata(xml).unwrap();
        let root = v.get("root").and_then(|r| r.as_object()).unwrap();
        assert!(root.get("#comment").or(root.get("a")).is_some());
    }

    #[test]
    fn parse_xml_with_cdata_attributes() {
        let xml = r#"<root id="x"><a>1</a></root>"#;
        let v = parse_xml_with_cdata(xml).unwrap();
        let root = v.get("root").and_then(|r| r.as_object()).unwrap();
        assert_eq!(root.get("@id").and_then(|v| v.as_str()), Some("x"));
    }

    #[test]
    fn parse_xml_with_cdata_multiple_children() {
        let xml = r#"<r><n>42</n><b>true</b></r>"#;
        let v = parse_xml_with_cdata(xml).unwrap();
        let r = v.get("r").and_then(|r| r.as_object()).unwrap();
        assert!(r.get("n").is_some());
        assert!(r.get("b").is_some());
    }

    #[test]
    fn parse_xml_with_cdata_text_tail_after_comment() {
        let xml = r#"<r><!-- comment -->tail</r>"#;
        let v = parse_xml_with_cdata(xml).unwrap();
        let r = v.get("r").and_then(|r| r.as_object()).unwrap();
        assert_eq!(
            r.get("#comment").and_then(|c| c.as_str()),
            Some(" comment ")
        );
        assert_eq!(r.get("#text-tail").and_then(|t| t.as_str()), Some("tail"));
    }

    #[test]
    fn parse_xml_with_cdata_empty_root_returns_empty_object() {
        let xml = r#"<root></root>"#;
        let v = parse_xml_with_cdata(xml).unwrap();
        let root = v.get("root").and_then(|r| r.as_object()).unwrap();
        assert!(root.is_empty());
    }

    #[test]
    fn parse_xml_with_cdata_mixed_content_appends_text() {
        // Two text nodes in same element (e.g. <a>hello</a><b/> then text "world" in same parent)
        let xml = r#"<r><a>hello<x/>world</a></r>"#;
        let v = parse_xml_with_cdata(xml).unwrap();
        let r = v.get("r").and_then(|r| r.as_object()).unwrap();
        let a = r.get("a").and_then(|a| a.as_object()).unwrap();
        // First text "hello", then after <x/>, text "world" appends to #text
        assert!(a.get("#text").is_some());
        let t = a.get("#text").and_then(|t| t.as_str()).unwrap();
        assert!(t.contains("hello") && t.contains("world"));
    }

    #[test]
    fn parse_xml_with_cdata_appends_multiple_cdata_sections() {
        let xml = r#"<r><x><![CDATA[a]]><![CDATA[b]]></x></r>"#;
        let v = parse_xml_with_cdata(xml).unwrap();
        let x = v
            .get("r")
            .and_then(|r| r.get("x"))
            .and_then(|x| x.as_object())
            .unwrap();
        assert_eq!(x.get("#cdata").and_then(|c| c.as_str()), Some("ab"));
    }

    #[test]
    fn parse_xml_with_cdata_invalid_returns_err() {
        let result = parse_xml_with_cdata("<<");
        assert!(result.is_err());
    }

    #[test]
    fn parse_xml_with_cdata_duplicate_sibling_elements_become_array() {
        let xml = r#"<r><item>a</item><item>b</item></r>"#;
        let v = parse_xml_with_cdata(xml).unwrap();
        let r = v.get("r").and_then(|r| r.as_object()).unwrap();
        let items = r.get("item").and_then(|i| i.as_array()).unwrap();
        assert_eq!(items.len(), 2);
        assert_eq!(items[0].get("#text").and_then(|t| t.as_str()), Some("a"));
        assert_eq!(items[1].get("#text").and_then(|t| t.as_str()), Some("b"));
    }

    #[test]
    fn parse_xml_with_cdata_empty_element_with_attributes() {
        let xml = r#"<r><empty id="x"/></r>"#;
        let v = parse_xml_with_cdata(xml).unwrap();
        let empty = v
            .get("r")
            .and_then(|r| r.get("empty"))
            .and_then(|e| e.as_object())
            .unwrap();
        assert_eq!(empty.get("@id").and_then(|v| v.as_str()), Some("x"));
    }

    #[test]
    fn parse_xml_with_cdata_duplicate_empty_siblings_become_array() {
        // Two empty elements with same name: second triggers remove+insert Array (Event::End path)
        let xml = r#"<r><a/><a/></r>"#;
        let v = parse_xml_with_cdata(xml).unwrap();
        let r = v.get("r").and_then(|r| r.as_object()).unwrap();
        let arr = r.get("a").and_then(|a| a.as_array()).unwrap();
        assert_eq!(arr.len(), 2);
    }

    #[test]
    fn parse_xml_with_cdata_malformed_entity_between_tags_is_dropped() {
        // A bare `&;` unescapes to an empty string - second empty-check returns without insert.
        let v = parse_xml_with_cdata(r#"<r>&;</r>"#).unwrap();
        let r = v.get("r").and_then(|r| r.as_object()).unwrap();
        // Text collapses to nothing - no #text key
        assert!(r.get("#text").is_none());
    }

    #[test]
    fn parse_xml_with_cdata_empty_root_element() {
        // Self-closing root: Event::Empty at the top level (no parent on stack).
        let v = parse_xml_with_cdata("<root/>").unwrap();
        let root = v.get("root").and_then(|r| r.as_object()).unwrap();
        assert!(root.is_empty());
    }

    #[test]
    fn parse_xml_with_cdata_three_empty_siblings_extend_array() {
        // Third duplicate empty sibling extends the existing array.
        let v = parse_xml_with_cdata("<r><a/><a/><a/></r>").unwrap();
        let arr = v
            .get("r")
            .and_then(|r| r.get("a"))
            .and_then(|a| a.as_array())
            .unwrap();
        assert_eq!(arr.len(), 3);
    }

    #[test]
    fn parse_xml_with_cdata_text_tail_appended_after_second_comment() {
        // Comment then text (#text-tail), then comment then text -> append to #text-tail
        let xml = r#"<r><!--c1-->t1<!--c2-->t2</r>"#;
        let v = parse_xml_with_cdata(xml).unwrap();
        let r = v.get("r").and_then(|r| r.as_object()).unwrap();
        assert_eq!(r.get("#text-tail").and_then(|t| t.as_str()), Some("t1t2"));
    }

    #[test]
    fn parse_xml_with_cdata_empty_document_returns_empty_object() {
        // Eof with no root (e.g. empty or only whitespace) -> empty object
        let xml = r#""#;
        let v = parse_xml_with_cdata(xml).unwrap();
        assert!(v.as_object().unwrap().is_empty());
    }

    #[test]
    fn parse_xml_with_cdata_text_after_cdata_stored_as_text() {
        // CDATA followed by regular text in the same element hits the
        // `elem.contains_key("#cdata")` branch in flush_text_buffer (line 126 path).
        let xml = r#"<root><item><![CDATA[raw content]]>extra text</item></root>"#;
        let v = parse_xml_with_cdata(xml).unwrap();
        let item = v
            .get("root")
            .and_then(|r| r.get("item"))
            .and_then(|i| i.as_object())
            .unwrap();
        assert_eq!(
            item.get("#cdata").and_then(|c| c.as_str()),
            Some("raw content")
        );
        // The text after CDATA is stored under #text (raw string value)
        assert!(
            item.get("#text").is_some(),
            "text after CDATA must be stored as #text"
        );
    }

    #[test]
    fn parse_xml_with_cdata_text_after_comment_then_cdata_stored_as_text_not_tail() {
        // A comment immediately followed by CDATA, then trailing whitespace/text before
        // the closing tag: the CDATA event resets `text_buffer_after_comment` to false,
        // so the trailing text must land in `#text` (cdata-shaped), not `#text-tail`
        // (comment-shaped) - `elem.contains_key("#comment")` staying true forever
        // (the key is never removed) used to re-derive the flag as true on the Text
        // event regardless, misrouting it and causing an extra #text-tail line to
        // reappear (and grow) on every subsequent disassemble/reassemble cycle.
        let xml = r#"<root><item><!--c--><![CDATA[x]]>tail</item></root>"#;
        let v = parse_xml_with_cdata(xml).unwrap();
        let item = v
            .get("root")
            .and_then(|r| r.get("item"))
            .and_then(|i| i.as_object())
            .unwrap();
        assert_eq!(item.get("#comment").and_then(|c| c.as_str()), Some("c"));
        assert_eq!(item.get("#cdata").and_then(|c| c.as_str()), Some("x"));
        assert_eq!(item.get("#text").and_then(|t| t.as_str()), Some("tail"));
        assert!(
            item.get("#text-tail").is_none(),
            "trailing text after comment+CDATA must not be misrouted to #text-tail"
        );
    }

    #[test]
    fn parse_xml_with_cdata_unescapes_entities_in_text() {
        // quick-xml 0.38+ emits entities as Event::GeneralRef; we resolve and append.
        let xml = r#"<r><expr>IF(x, &quot;created&quot;, &quot;updated&quot;)</expr></r>"#;
        let v = parse_xml_with_cdata(xml).unwrap();
        let r = v.get("r").and_then(|r| r.as_object()).unwrap();
        let expr = r.get("expr").and_then(|e| e.as_object()).unwrap();
        let text = expr.get("#text").and_then(|t| t.as_str()).unwrap();
        // Must have actual quote chars so round-trip produces &quot; in output
        assert!(text.contains(r#""created""#) && text.contains(r#""updated""#));
    }

    #[test]
    fn parse_xml_with_cdata_preserves_space_after_comma_in_entities() {
        // Fixture format: comma space before second entity - must preserve for round-trip
        let xml = r#"<e>IF(a, &quot;x&quot;, &quot;y&quot;)</e>"#;
        let v = parse_xml_with_cdata(xml).unwrap();
        let e = v.get("e").and_then(|e| e.as_object()).unwrap();
        let text = e.get("#text").and_then(|t| t.as_str()).unwrap();
        assert_eq!(
            text, r#"IF(a, "x", "y")"#,
            "space after comma must be preserved"
        );
    }

    // ---- flush_text_buffer vs the original implementation ---------------------

    /// The original allocation-heavy `flush_text_buffer`, kept as the oracle for
    /// the in-place version above.
    fn reference_flush_text_buffer(
        raw: &mut String,
        stack: &mut [(String, Map<String, Value>)],
        is_after_comment: bool,
    ) {
        if raw.is_empty() {
            return;
        }
        let text = unescape(raw.as_str()).unwrap_or_default().into_owned();
        raw.clear();
        if text.is_empty() {
            return;
        }
        let val_raw = Value::String(text.clone());
        let Some((_, elem)) = stack.last_mut() else {
            return;
        };
        let is_whitespace_only_run = text.trim().is_empty();
        if is_after_comment {
            match elem
                .get_mut("#text-tail")
                .and_then(|v| v.as_str())
                .map(str::to_string)
            {
                Some(prev) => {
                    if !is_whitespace_only_run {
                        if prev.trim().is_empty() {
                            elem.insert(
                                "#text-tail".to_string(),
                                Value::String(text.trim_start().to_string()),
                            );
                        } else if let Some(b) = val_raw.as_str() {
                            elem.insert(
                                "#text-tail".to_string(),
                                Value::String(format!("{}{}", prev, b)),
                            );
                        }
                    }
                }
                None => {
                    elem.insert("#text-tail".to_string(), val_raw);
                }
            }
        } else if let Some(prev) = elem
            .get("#text")
            .and_then(|v| v.as_str())
            .map(str::to_string)
        {
            if !is_whitespace_only_run {
                if prev.trim().is_empty() {
                    elem.insert(
                        "#text".to_string(),
                        Value::String(text.trim_start().to_string()),
                    );
                } else if let Some(b) = val_raw.as_str() {
                    elem.insert("#text".to_string(), Value::String(format!("{}{}", prev, b)));
                }
            }
        } else {
            elem.insert("#text".to_string(), val_raw);
        }
    }

    /// Serialize a map with its key order, so the comparison covers order too.
    fn ordered(map: &Map<String, Value>) -> Vec<(String, Value)> {
        map.iter().map(|(k, v)| (k.clone(), v.clone())).collect()
    }

    #[test]
    fn flush_text_buffer_matches_reference_on_run_sequences() {
        let runs: &[&str] = &[
            "",
            "   ",
            "\n        ",
            "\u{a0}",
            "abc",
            "  abc",
            "abc  ",
            "( ",
            "42",
            "&amp;",
            " &amp; ",
            "&#32;",
            "&bogus;",
            "a&lt;b",
        ];
        let starts: Vec<Map<String, Value>> = vec![
            Map::new(),
            serde_json::from_str(r##"{"@a":"1"}"##).unwrap(),
            serde_json::from_str(r##"{"#text":"  ","child":"x"}"##).unwrap(),
            serde_json::from_str(r##"{"#text":"keep","#cdata":"c"}"##).unwrap(),
            serde_json::from_str(r##"{"#text-tail":"\n  ","#comment":"c"}"##).unwrap(),
            serde_json::from_str(r##"{"#text-tail":"tail"}"##).unwrap(),
            serde_json::from_str(r##"{"#text":5,"#text-tail":true}"##).unwrap(),
        ];
        for start in &starts {
            for first in runs {
                for second in runs {
                    for (after_first, after_second) in
                        [(false, false), (true, true), (false, true), (true, false)]
                    {
                        let mut new_stack = vec![("e".to_string(), start.clone())];
                        let mut ref_stack = vec![("e".to_string(), start.clone())];
                        for (run, after) in [(first, after_first), (second, after_second)] {
                            let mut new_raw = run.to_string();
                            let mut ref_raw = run.to_string();
                            flush_text_buffer(&mut new_raw, &mut new_stack, after);
                            reference_flush_text_buffer(&mut ref_raw, &mut ref_stack, after);
                            assert_eq!(new_raw, ref_raw, "raw buffer must be cleared alike");
                        }
                        assert_eq!(
                            ordered(&new_stack[0].1),
                            ordered(&ref_stack[0].1),
                            "start={start:?} runs=({first:?},{after_first}) then ({second:?},{after_second})"
                        );
                    }
                }
            }
        }
    }

    #[test]
    fn flush_text_buffer_empty_stack_clears_raw() {
        let mut stack: Vec<(String, Map<String, Value>)> = Vec::new();
        let mut raw = "text".to_string();
        flush_text_buffer(&mut raw, &mut stack, false);
        assert!(raw.is_empty());
        assert!(stack.is_empty());
    }
}