config-disassembler 0.11.10

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
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
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
//! Build XML string from XmlElement structure.

use quick_xml::escape::partial_escape;
use quick_xml::events::{BytesCData, BytesDecl, BytesEnd, BytesStart, BytesText, Event};
use quick_xml::Writer;
use serde_json::{Map, Value};
use std::io::{BufWriter, Write};
use std::path::Path;

use super::fragments::{Entry, Fragments, Item};
use crate::xml::types::XmlElement;

pub(super) fn value_to_string(v: &Value) -> String {
    match v {
        Value::String(s) => s.clone(),
        Value::Number(n) => n.to_string(),
        Value::Bool(b) => b.to_string(),
        Value::Null => String::new(),
        _ => serde_json::to_string(v).unwrap_or_default(),
    }
}

/// Keys of an element's map that are not child elements: its own text, CDATA,
/// comment and formatting markers. (Keys starting with `@` are attributes.)
pub(super) const CONTENT_KEYS: [&str; 6] = [
    "#text",
    "#raw-text",
    "#comment",
    "#text-tail",
    "#cdata",
    "#compact",
];

/// Whether `key` names a child element rather than an attribute or content key.
pub(super) fn is_child_key(key: &str) -> bool {
    !key.starts_with('@') && !CONTENT_KEYS.contains(&key)
}

/// One field of an element being written: a plain value, or a merged entry from
/// fragment reassembly (see `fragments.rs`), whose items may be pre-serialized.
#[derive(Clone, Copy)]
pub(super) enum Field<'a> {
    Value(&'a Value),
    Entry(&'a Entry, &'a Fragments<'a>),
}

impl<'a> Field<'a> {
    /// The plain value this field holds, when it holds exactly one.
    fn as_value(self) -> Option<&'a Value> {
        match self {
            Field::Value(v) => Some(v),
            Field::Entry(Entry::One(Item::Val(v)), _) => Some(v),
            Field::Entry(..) => None,
        }
    }

    /// Text of an attribute or content field. Those keys are never fragmented, so
    /// an entry's items are all plain values; a multi-item entry is written as the
    /// array value the tree merge would have built.
    fn to_text(self) -> String {
        match self {
            Field::Value(v) => value_to_string(v),
            Field::Entry(entry, _) => match self.as_value() {
                Some(v) => value_to_string(v),
                None => value_to_string(&entry.to_value()),
            },
        }
    }
}

pub(super) fn write_element<W: std::io::Write>(
    writer: &mut Writer<W>,
    name: &str,
    content: &Value,
    indent_level: usize,
) -> Result<(), Box<dyn std::error::Error + Send + Sync>> {
    match content {
        Value::Object(obj) => write_object(
            writer,
            name,
            obj.iter().map(|(k, v)| (k.as_str(), Field::Value(v))),
            indent_level,
        )?,
        Value::Array(arr) => {
            for item in arr {
                write_element(writer, name, item, indent_level)?;
            }
        }
        _ => {
            writer.write_event(Event::Start(BytesStart::new(name)))?;
            writer.write_event(Event::Text(BytesText::new(
                value_to_string(content).as_str(),
            )))?;
            writer.write_event(Event::End(BytesEnd::new(name)))?;
        }
    }

    Ok(())
}

/// Write one item of a merged child entry at `indent_level` (the child's level).
fn write_item<W: std::io::Write>(
    writer: &mut Writer<W>,
    name: &str,
    item: &Item,
    fragments: &Fragments<'_>,
    indent_level: usize,
) -> Result<(), Box<dyn std::error::Error + Send + Sync>> {
    match item {
        // Already serialized, by `write_element(name, item, indent_level)`.
        Item::Frag(frag) => writer.get_mut().write_all(fragments.bytes(frag))?,
        Item::Val(v) => write_element(writer, name, v, indent_level)?,
    }
    Ok(())
}

/// Write an element whose content is the map `fields` (attributes, content keys
/// and child elements, in order).
pub(super) fn write_object<'a, W: std::io::Write>(
    writer: &mut Writer<W>,
    name: &str,
    fields: impl Iterator<Item = (&'a str, Field<'a>)>,
    indent_level: usize,
) -> Result<(), Box<dyn std::error::Error + Send + Sync>> {
    let indent = "    ".repeat(indent_level);
    let child_indent = "    ".repeat(indent_level + 1);

    let mut attrs: Vec<(&str, String)> = Vec::new();
    let mut text_content = String::new();
    let mut raw_text_content = String::new();
    let mut comment_content = String::new();
    let mut text_tail_content = String::new();
    let mut cdata_content = String::new();
    let mut is_compact = false;
    let mut child_elements: Vec<(&str, Field<'a>)> = Vec::new();
    for (k, field) in fields {
        if k.starts_with('@') {
            attrs.push((k.trim_start_matches('@'), field.to_text()));
        } else if k == "#text" {
            text_content = field.to_text();
        } else if k == "#raw-text" {
            raw_text_content = field.to_text();
        } else if k == "#comment" {
            comment_content = field.to_text();
        } else if k == "#text-tail" {
            text_tail_content = field.to_text();
        } else if k == "#cdata" {
            cdata_content = field.to_text();
        } else if k == "#compact" {
            is_compact = field.as_value().and_then(Value::as_bool).unwrap_or(false);
        } else {
            child_elements.push((k, field));
        }
    }

    let mut start = BytesStart::new(name);
    for (k, v) in &attrs {
        start.push_attribute((*k, v.as_str()));
    }
    writer.write_event(Event::Start(start))?;

    let has_mixed_content = !cdata_content.is_empty()
        || !text_content.is_empty()
        || !raw_text_content.is_empty()
        || !comment_content.is_empty()
        || !text_tail_content.is_empty();

    let compact_child = match child_elements.as_slice() {
        [(child_name, field)] if is_compact => match field.as_value() {
            Some(v @ Value::Object(_)) => Some((*child_name, v)),
            // A pre-serialized child was written for the indented layout, so it
            // can't be placed inline; fragment reassembly takes the tree path for
            // such a root instead (see `fragments::needs_tree_path`).
            None if matches!(field, Field::Entry(Entry::One(Item::Frag(_)), _)) => {
                return Err("compact element with a pre-serialized child".into());
            }
            _ => None,
        },
        _ => None,
    };

    if let Some((child_name, child_value)) = compact_child {
        // Single-element wrapper with zero surrounding whitespace in the source
        // (e.g. `<connector><targetReference>X</targetReference></connector>`) --
        // render the wrapper and its one child on the same line, with no
        // indent/newline in between, matching the original formatting.
        write_element(writer, child_name, child_value, indent_level)?;
    } else {
        if !child_elements.is_empty() {
            writer.write_event(Event::Text(BytesText::new(
                format!("\n{}", child_indent).as_str(),
            )))?;

            let child_count = child_elements.len();
            for (idx, (child_name, field)) in child_elements.iter().enumerate() {
                let is_last = idx == child_count - 1;
                match *field {
                    Field::Value(Value::Array(arr))
                    | Field::Entry(Entry::One(Item::Val(Value::Array(arr))), _) => {
                        let arr_len = arr.len();
                        for (i, item) in arr.iter().enumerate() {
                            let arr_last = i == arr_len - 1;
                            write_element(writer, child_name, item, indent_level + 1)?;
                            if !arr_last {
                                writer.write_event(Event::Text(BytesText::new(
                                    format!("\n{}", child_indent).as_str(),
                                )))?;
                            }
                        }
                    }
                    Field::Entry(Entry::Many(items), fragments) => {
                        let arr_len = items.len();
                        for (i, item) in items.iter().enumerate() {
                            let arr_last = i == arr_len - 1;
                            write_item(writer, child_name, item, fragments, indent_level + 1)?;
                            if !arr_last {
                                writer.write_event(Event::Text(BytesText::new(
                                    format!("\n{}", child_indent).as_str(),
                                )))?;
                            }
                        }
                    }
                    Field::Value(v @ Value::Object(_))
                    | Field::Entry(Entry::One(Item::Val(v @ Value::Object(_))), _) => {
                        write_element(writer, child_name, v, indent_level + 1)?;
                    }
                    Field::Entry(Entry::One(Item::Frag(frag)), fragments) => {
                        // Already serialized, at this child's level.
                        writer.get_mut().write_all(fragments.bytes(frag))?;
                    }
                    Field::Value(v) | Field::Entry(Entry::One(Item::Val(v)), _) => {
                        writer.write_event(Event::Start(BytesStart::new(*child_name)))?;
                        writer.write_event(Event::Text(BytesText::new(
                            value_to_string(v).as_str(),
                        )))?;
                        writer.write_event(Event::End(BytesEnd::new(*child_name)))?;
                    }
                }
                if !is_last {
                    writer.write_event(Event::Text(BytesText::new(
                        format!("\n{}", child_indent).as_str(),
                    )))?;
                }
            }

            writer.write_event(Event::Text(BytesText::new(
                format!("\n{}", indent).as_str(),
            )))?;
        }

        // A single element can carry both real child elements *and* its own
        // direct mixed content (e.g. `<item><fullName>X</fullName><![CDATA[..]]></item>`).
        // child_elements and the various *_content locals are mutually
        // populated from disjoint keys (see the filter_map above), so this
        // must run independently of the child_elements branch rather than as
        // an `else if` - otherwise a real child element sibling silently
        // discards any #text/#cdata/#comment/#text-tail on the same element.
        if has_mixed_content {
            // Add newline+indent before content when no leading text and no
            // child elements already provided one (keeps CDATA/comment on
            // their own line without doubling up on the child_elements
            // branch's own trailing newline+indent above).
            if child_elements.is_empty()
                && text_content.is_empty()
                && raw_text_content.is_empty()
                && comment_content.is_empty()
            {
                writer.write_event(Event::Text(BytesText::new(
                    format!("\n{}", child_indent).as_str(),
                )))?;
            }
            // Output in order: #text, #raw-text, #comment, #text-tail, #cdata
            if !text_content.is_empty() {
                writer.write_event(Event::Text(BytesText::new(text_content.as_str())))?;
            }
            // #raw-text: sidecar content injected pre-unescaped; use partial_escape so
            // literal " in YAML is not converted to &quot; but < > & are still safe.
            if !raw_text_content.is_empty() {
                writer.write_event(Event::Text(BytesText::from_escaped(partial_escape(
                    raw_text_content.as_str(),
                ))))?;
            }
            if !comment_content.is_empty() {
                // XML comment content is never subject to entity resolution on
                // read (the reader stores it raw - see parse_xml_cdata.rs's
                // Event::Comment handling), so it must never be escaped on
                // write either. `BytesText::new` escapes (quick-xml treats it
                // like text content); `from_escaped` writes the bytes verbatim.
                // Using `new` here made every `&` in a comment gain one more
                // `&amp;` layer on each successive disassemble/reassemble cycle.
                writer.write_event(Event::Comment(BytesText::from_escaped(
                    comment_content.as_str(),
                )))?;
            }
            if !text_tail_content.is_empty() {
                writer.write_event(Event::Text(BytesText::new(text_tail_content.as_str())))?;
            }
            if !cdata_content.is_empty() {
                writer.write_event(Event::CData(BytesCData::new(cdata_content.as_str())))?;
            }
            // Add newline+indent before closing tag only for CDATA (keeps compact
            // for text-only), and only when child_elements didn't already add its
            // own trailing newline+indent above.
            if !cdata_content.is_empty() && child_elements.is_empty() {
                writer.write_event(Event::Text(BytesText::new(
                    format!("\n{}", indent).as_str(),
                )))?;
            }
        }
    }

    writer.write_event(Event::End(BytesEnd::new(name)))?;
    Ok(())
}

/// Whether `write_element` writes anything for `value`. Only an array whose items
/// are all (recursively) empty arrays writes nothing; every other value writes at
/// least its own tags.
fn writes_output(value: &Value) -> bool {
    match value {
        Value::Array(items) => items.iter().any(writes_output),
        _ => true,
    }
}

/// Serialize `element` into `out` and return `out`. A non-object `element`
/// writes nothing.
///
/// The output never ends with whitespace, so it needs no trimming: it ends with
/// the `>` of the root's last tag, or -- when the root writes nothing -- with the
/// declaration, whose `\n` separator is then left out. (It used to be written and
/// trimmed off the finished `String`, which needs the whole output in memory.)
fn write_xml<W: Write>(
    element: &XmlElement,
    out: W,
) -> Result<W, Box<dyn std::error::Error + Send + Sync>> {
    // Use Writer::new (no indent) so leaf elements stay compact and match fixture format
    let mut writer = Writer::new(out);
    let Value::Object(element) = element else {
        return Ok(writer.into_inner());
    };

    // The root is BORROWED for serialization. It used to be `.cloned()` out of
    // `element` first -- a deep copy of the whole document, live alongside the
    // original for the entire write; heap-profiling sf-decomposer's workload
    // showed it as the largest avoidable share of reassemble's heap peak.
    let empty_root = Value::Object(Map::new());
    let (declaration, root_key, root_value) = if let Some(decl) = element.get("?xml") {
        let root_key = element
            .keys()
            .find(|k| *k != "?xml")
            .cloned()
            .unwrap_or_else(|| "root".to_string());
        let root_value = element.get(&root_key).unwrap_or(&empty_root);
        (Some(decl), root_key, root_value)
    } else {
        let root_key = element
            .keys()
            .next()
            .cloned()
            .unwrap_or_else(|| "root".to_string());
        let root_value = element.get(&root_key).unwrap_or(&empty_root);
        (None, root_key, root_value)
    };

    let root_writes_output = writes_output(root_value);
    if let Some(obj) = declaration.and_then(|d| d.as_object()) {
        let version = obj
            .get("@version")
            .and_then(|v| v.as_str())
            .unwrap_or("1.0");
        let encoding = obj.get("@encoding").and_then(|v| v.as_str());
        let standalone = obj.get("@standalone").and_then(|v| v.as_str());
        writer.write_event(Event::Decl(BytesDecl::new(version, encoding, standalone)))?;
        if root_writes_output {
            writer.write_event(Event::Text(BytesText::new("\n")))?;
        }
    }

    if root_writes_output {
        write_element(&mut writer, &root_key, root_value, 0)?;
    }
    Ok(writer.into_inner())
}

/// Serialize `element` straight to a file at `path` (created or truncated),
/// followed by a `\n` when `trailing_newline` is set.
///
/// Produces the same bytes as writing `build_xml_string(element)` (plus the
/// newline), but never holds the serialized document in memory: reassemble used
/// to keep the whole output twice over (the writer's buffer and the `String`)
/// alongside the merged tree at its heap peak.
pub(crate) fn write_xml_file(
    element: &XmlElement,
    path: &Path,
    trailing_newline: bool,
) -> Result<(), Box<dyn std::error::Error + Send + Sync>> {
    let file = std::fs::File::create(path)?;
    let mut out = write_xml(element, BufWriter::new(file))?;
    if trailing_newline {
        out.write_all(b"\n")?;
    }
    // BufWriter's drop flushes but swallows the error; flush explicitly to surface it.
    out.flush()?;
    Ok(())
}

/// Build XML string from XmlElement.
pub fn build_xml_string(element: &XmlElement) -> String {
    let out = write_xml(element, Vec::new())
        .ok()
        .and_then(|bytes| String::from_utf8(bytes).ok())
        .unwrap_or_default();
    debug_assert_eq!(
        out.trim_end().len(),
        out.len(),
        "serialized XML must not end with whitespace"
    );
    out
}

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

    #[test]
    fn build_xml_string_non_object_returns_empty() {
        assert!(build_xml_string(&Value::Array(vec![])).is_empty());
        assert!(build_xml_string(&Value::Null).is_empty());
    }

    #[test]
    fn build_xml_string_simple_root() {
        let el = json!({
            "?xml": { "@version": "1.0", "@encoding": "UTF-8" },
            "root": { "child": "value" }
        });
        let out = build_xml_string(&el);
        assert!(out.contains("<?xml"));
        assert!(out.contains("<root>"));
        assert!(out.contains("<child>value</child>"));
        assert!(out.contains("</root>"));
    }

    #[test]
    fn build_xml_string_with_attributes() {
        let el = json!({
            "root": { "@xmlns": "http://example.com", "a": "b" }
        });
        let out = build_xml_string(&el);
        assert!(out.contains("xmlns"));
        assert!(out.contains("http://example.com"));
        assert!(out.contains("<a>b</a>"));
    }

    #[test]
    fn build_xml_string_with_array() {
        let el = json!({
            "root": { "item": [ { "x": "1" }, { "x": "2" } ] }
        });
        let out = build_xml_string(&el);
        assert!(out.contains("<item>"));
        assert!(out.contains("<x>1</x>"));
        assert!(out.contains("<x>2</x>"));
    }

    #[test]
    fn build_xml_string_without_declaration() {
        let el = json!({ "root": { "a": "b" } });
        let out = build_xml_string(&el);
        assert!(!out.contains("<?xml"));
        assert!(out.contains("<root>"));
    }

    #[test]
    fn build_xml_string_with_text_comment_cdata() {
        let root = json!({
            "#text": "text",
            "#comment": " a comment ",
            "#cdata": "<cdata>"
        });
        let el = json!({
            "?xml": { "@version": "1.0" },
            "root": root
        });
        let out = build_xml_string(&el);
        assert!(out.contains("text"));
        assert!(out.contains("<!--"));
        assert!(out.contains(" a comment "));
        assert!(out.contains("<![CDATA["));
        assert!(out.contains("<cdata>"));
    }

    #[test]
    fn build_xml_string_with_declaration_encoding_standalone() {
        let el = json!({
            "?xml": { "@version": "1.0", "@encoding": "UTF-8", "@standalone": "yes" },
            "root": { "a": "b" }
        });
        let out = build_xml_string(&el);
        assert!(out.contains("<?xml"));
        assert!(out.contains("UTF-8"));
        assert!(out.contains("standalone"));
        assert!(out.contains("<root>"));
    }

    #[test]
    fn build_xml_string_primitive_sibling_children() {
        // Root with multiple children: one object, one primitive (hits _ => branch)
        let el = json!({
            "root": { "obj": { "x": "1" }, "num": 42, "flag": true }
        });
        let out = build_xml_string(&el);
        assert!(out.contains("<obj>"));
        assert!(out.contains("<num>42</num>"));
        assert!(out.contains("<flag>true</flag>"));
    }

    #[test]
    fn build_xml_string_null_child_value() {
        let el = json!({
            "root": { "empty": null }
        });
        let out = build_xml_string(&el);
        assert!(out.contains("<empty>"));
        assert!(out.contains("</empty>"));
        // value_to_string maps Value::Null -> "" explicitly; without that
        // explicit arm it would fall through to serde_json::to_string and
        // emit the literal `null`, so guard against that regression.
        assert!(
            !out.contains("null"),
            "Value::Null child should render as empty content, not the string \"null\": {out}"
        );
        assert!(out.contains("<empty></empty>"));
    }

    #[test]
    fn build_xml_string_primitive_siblings_have_inter_element_indent() {
        // Two primitive sibling children: between the non-last `<a>` and the
        // last `<b>` the writer should emit a newline+indent. The `!is_last`
        // guard on the close-tag indent is otherwise unobservable from
        // single-sibling or array-only fixtures.
        let el = json!({ "root": { "a": 1, "b": 2 } });
        let out = build_xml_string(&el);
        assert!(
            out.contains("<a>1</a>\n    <b>2</b>"),
            "expected `<a>1</a>` to be followed by newline + 4-space indent then `<b>2</b>`, got:\n{out}"
        );
        // And the last sibling should NOT have a trailing inter-sibling indent
        // before `</root>` (only the closing-tag-level indent).
        assert!(
            out.contains("<b>2</b>\n</root>"),
            "expected `<b>2</b>` to be followed directly by the root close tag, got:\n{out}"
        );
    }

    #[test]
    fn build_xml_string_comment_only_leaf() {
        // Comment-only leaf isolates the `!comment_content.is_empty()` leg of
        // the leaf-content guard. Without it the comment branch is never
        // entered and the comment vanishes from the output.
        let el = json!({
            "?xml": { "@version": "1.0" },
            "root": { "#comment": " just a comment " }
        });
        let out = build_xml_string(&el);
        assert!(out.contains("<!--"), "expected comment open in: {out}");
        assert!(
            out.contains(" just a comment "),
            "expected comment text preserved verbatim in: {out}"
        );
        assert!(out.contains("-->"));
    }

    #[test]
    fn build_xml_string_text_tail_only_leaf() {
        // Text-tail-only leaf isolates both the `||` joiner and the
        // `!text_tail_content.is_empty()` check on the leaf-content guard.
        // Without either, the text-tail content is silently dropped.
        let el = json!({
            "?xml": { "@version": "1.0" },
            "root": { "#text-tail": "tail-only-content" }
        });
        let out = build_xml_string(&el);
        assert!(
            out.contains("tail-only-content"),
            "expected text-tail content rendered between root tags, got:\n{out}"
        );
        assert!(out.contains("<root>"));
        assert!(out.contains("</root>"));
    }

    #[test]
    fn build_xml_string_cdata_only_no_text_or_comment() {
        let root = json!({ "#cdata": "only cdata content" });
        let el = json!({ "?xml": { "@version": "1.0" }, "root": root });
        let out = build_xml_string(&el);
        assert!(out.contains("<![CDATA["));
        assert!(out.contains("only cdata content"));
    }

    #[test]
    fn build_xml_string_declaration_only_defaults_root_key() {
        let el = json!({ "?xml": { "@version": "1.0", "@encoding": "UTF-8" } });
        let out = build_xml_string(&el);
        assert!(out.contains("<?xml"));
        assert!(out.contains("<root>"));
    }

    #[test]
    fn build_xml_string_declaration_non_object_skips_decl_write() {
        let el = json!({ "?xml": "not-an-object", "root": { "a": "b" } });
        let out = build_xml_string(&el);
        assert!(!out.contains("<?xml"));
        assert!(out.contains("<root>"));
    }

    #[test]
    fn build_xml_string_root_value_array_sibling_elements() {
        // Root value is Array (write_element Value::Array branch)
        let el = json!({
            "root": [ { "a": "1" }, { "b": "2" } ]
        });
        let out = build_xml_string(&el);
        assert!(out.contains("<root>"));
        assert!(out.contains("<a>1</a>"));
        assert!(out.contains("<b>2</b>"));
        assert!(out.contains("</root>"));
    }

    #[test]
    fn build_xml_string_root_value_primitive() {
        // Root value is primitive (write_element _ branch for top-level content)
        let el = json!({ "root": 42 });
        let out = build_xml_string(&el);
        assert!(out.contains("<root>42</root>"));
    }

    #[test]
    fn build_xml_string_array_child_not_last_sibling_writes_inter_element_indent() {
        // When an array child is NOT the last sibling, `if !is_last` in the
        // Value::Array arm must write an inter-element indent after all array
        // items. Without this path covered, mutating `!is_last` to always-false
        // would drop the indent and merge consecutive tags in the output.
        let el = json!({
            "root": {
                "items": [{ "x": "1" }],
                "sibling": "y"
            }
        });
        let out = build_xml_string(&el);
        assert!(
            out.contains("<items>"),
            "items element must be present: {out}"
        );
        assert!(
            out.contains("<sibling>y</sibling>"),
            "sibling must be present: {out}"
        );
    }

    #[test]
    fn build_xml_string_empty_array_child_produces_no_elements() {
        // A child whose value is an empty array: the inner for-loop body never
        // executes (arr_len == 0) but the is_last/not-is_last indent logic still runs.
        let el = json!({ "root": { "items": [] } });
        let out = build_xml_string(&el);
        // No <items> tags should appear since there are no items
        assert!(
            !out.contains("<items>"),
            "no elements for empty array: {out}"
        );
        assert!(
            out.contains("<root>"),
            "root element must be present: {out}"
        );
    }

    #[test]
    fn build_xml_string_attribute_value_array_uses_serde_fallback() {
        // An attribute value that is an Array hits value_to_string's `_` arm.
        let el = json!({
            "root": { "@tags": ["a", "b"], "child": "v" }
        });
        let out = build_xml_string(&el);
        assert!(
            out.contains("child"),
            "child element must be present: {out}"
        );
    }

    #[test]
    fn build_xml_string_attribute_value_object_uses_serde_fallback() {
        // Attribute value that is Object hits value_to_string _ branch (serde_json::to_string)
        let el = json!({
            "root": { "@complex": { "nested": true }, "child": "v" }
        });
        let out = build_xml_string(&el);
        assert!(out.contains("child"));
        assert!(out.contains("v"));
    }

    // ---- write_xml_file -------------------------------------------------------

    fn sample_doc() -> XmlElement {
        json!({
            "?xml": { "@version": "1.0", "@encoding": "UTF-8" },
            "Profile": {
                "@xmlns": "http://soap.sforce.com/2006/04/metadata",
                "custom": "false",
                "fieldPermissions": [
                    { "editable": "true", "field": "Account.Name" },
                    { "editable": "false", "field": "Account.Phone" }
                ],
                "description": { "#cdata": "a < b" }
            }
        })
    }

    #[test]
    fn write_xml_file_matches_build_xml_string() {
        let dir = tempfile::tempdir().unwrap();
        let doc = sample_doc();
        for trailing_newline in [false, true] {
            let path = dir.path().join(format!("out-{trailing_newline}.xml"));
            write_xml_file(&doc, &path, trailing_newline).unwrap();
            let mut expected = build_xml_string(&doc);
            if trailing_newline {
                expected.push('\n');
            }
            assert_eq!(std::fs::read_to_string(&path).unwrap(), expected);
        }
    }

    #[test]
    fn write_xml_file_truncates_existing_file() {
        let dir = tempfile::tempdir().unwrap();
        let path = dir.path().join("out.xml");
        std::fs::write(&path, "x".repeat(100_000)).unwrap();
        let doc = json!({ "root": { "a": "1" } });
        write_xml_file(&doc, &path, false).unwrap();
        assert_eq!(
            std::fs::read_to_string(&path).unwrap(),
            build_xml_string(&doc)
        );
    }

    #[test]
    fn write_xml_file_non_object_writes_empty_file() {
        let dir = tempfile::tempdir().unwrap();
        let path = dir.path().join("out.xml");
        write_xml_file(&json!("scalar"), &path, false).unwrap();
        assert_eq!(std::fs::read_to_string(&path).unwrap(), "");
    }

    #[test]
    fn write_xml_file_errors_when_directory_missing() {
        let dir = tempfile::tempdir().unwrap();
        let path = dir.path().join("missing").join("out.xml");
        assert!(write_xml_file(&sample_doc(), &path, false).is_err());
    }

    #[test]
    fn build_xml_string_trims_newline_after_declaration_only_document() {
        // An empty-array root writes nothing after the declaration's trailing "\n";
        // that "\n" is the one case where trimming actually removes bytes.
        let doc = json!({ "?xml": { "@version": "1.0" }, "root": [] });
        let out = build_xml_string(&doc);
        assert_eq!(out, r#"<?xml version="1.0"?>"#);
    }

    #[test]
    fn writes_output_only_false_for_arrays_of_empty_arrays() {
        assert!(!writes_output(&json!([])));
        assert!(!writes_output(&json!([[], [[]]])));
        assert!(writes_output(&json!([[], ["x"]])));
        assert!(writes_output(&json!([{}])));
        assert!(writes_output(&json!({})));
        assert!(writes_output(&json!("")));
        assert!(writes_output(&json!(null)));
    }

    #[test]
    fn declaration_newline_kept_when_root_writes_output() {
        let doc = json!({ "?xml": { "@version": "1.0" }, "root": [[], { "a": "1" }] });
        assert_eq!(
            build_xml_string(&doc),
            "<?xml version=\"1.0\"?>\n<root>\n    <a>1</a>\n</root>"
        );
    }

    #[test]
    fn nested_empty_array_root_writes_declaration_only() {
        let doc = json!({ "?xml": { "@version": "1.0" }, "root": [[], [[]]] });
        assert_eq!(build_xml_string(&doc), r#"<?xml version="1.0"?>"#);
        assert_eq!(build_xml_string(&json!({ "root": [] })), "");
    }

    #[test]
    fn write_xml_file_matches_build_xml_string_for_empty_root() {
        let dir = tempfile::tempdir().unwrap();
        let path = dir.path().join("out.xml");
        let doc = json!({ "?xml": { "@version": "1.0" }, "root": [] });
        write_xml_file(&doc, &path, true).unwrap();
        assert_eq!(
            std::fs::read_to_string(&path).unwrap(),
            format!("{}\n", build_xml_string(&doc))
        );
    }
}