libreoffice-pure 0.3.4

Pure-Rust LibreOffice-compatible document generation CLI
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
//! High-level pure-Rust convenience helpers that mirror the LibreOffice
//! command set.
//!
//! These functions take a single byte slice and return a single byte
//! vector, so they are the easiest way to plumb the workspace into a
//! larger application that just wants `bytes -> bytes` document
//! conversion.
//!
//! Available helpers:
//! - [`docx_to_pdf_bytes`] – DOCX → PDF
//! - [`doc_to_docx_bytes`] – legacy binary `.doc` → DOCX
//! - [`pptx_to_pdf_bytes`] – PPTX → PDF
//! - [`xlsx_recalc_bytes`] – recompute formula caches inside an XLSX
//! - [`accept_all_tracked_changes_docx_bytes`] – accept all `w:ins`/`w:del`
//!   tracked revisions inside a DOCX

use std::collections::BTreeMap;

use lo_calc::{evaluate_formula, Value};
use lo_core::{
    parse_xml_document, serialize_xml_document, CellAddr, LoError, Result, Sheet, XmlItem, XmlNode,
};
use lo_zip::{normalize_zip_path, rels_path_for, resolve_part_target, ZipArchive};

/// Convert a DOCX byte stream into a single-page text PDF.
pub fn docx_to_pdf_bytes(bytes: &[u8]) -> Result<Vec<u8>> {
    let doc = lo_writer::from_docx_bytes("document", bytes)?;
    lo_writer::save_as(&doc, "pdf")
}

/// Convert a legacy binary `.doc` file (Word 97-2003) into a DOCX byte
/// stream by extracting the piece-table text and re-emitting it.
pub fn doc_to_docx_bytes(bytes: &[u8]) -> Result<Vec<u8>> {
    let doc = lo_writer::from_doc_bytes("document", bytes)?;
    lo_writer::save_as(&doc, "docx")
}

/// Convert a PPTX byte stream into a multi-page text PDF.
pub fn pptx_to_pdf_bytes(bytes: &[u8]) -> Result<Vec<u8>> {
    let deck = lo_impress::from_pptx_bytes("presentation", bytes)?;
    lo_impress::save_as(&deck, "pdf")
}

// ---------------------------------------------------------------------------
// Generic format converters
// ---------------------------------------------------------------------------

/// Convert a writer-format byte stream from `from` to `to`.
///
/// `from`/`to` are case-insensitive format hints accepted by
/// `lo_writer::load_bytes` / `lo_writer::save_as`. The legacy `.doc`
/// format is also supported as a source via `from = "doc"`.
pub fn writer_convert_bytes(input: &[u8], from: &str, to: &str) -> Result<Vec<u8>> {
    let doc = lo_writer::load_bytes("document", input, from)?;
    lo_writer::save_as(&doc, to)
}

/// Convert a calc-format byte stream from `from` to `to`. Accepts the
/// `csv`, `xlsx`, `ods` source formats and any of `csv`, `html`, `svg`,
/// `pdf`, `ods`, `xlsx` as targets.
pub fn calc_convert_bytes(input: &[u8], from: &str, to: &str) -> Result<Vec<u8>> {
    let workbook = lo_calc::load_bytes("workbook", input, from)?;
    lo_calc::save_as(&workbook, to)
}

/// Convert an impress-format byte stream from `from` to `to`. Accepts
/// `pptx`, `odp`, `txt` as sources and any of `html`, `svg`, `pdf`,
/// `odp`, `pptx` as targets.
pub fn impress_convert_bytes(input: &[u8], from: &str, to: &str) -> Result<Vec<u8>> {
    let deck = lo_impress::load_bytes("presentation", input, from)?;
    lo_impress::save_as(&deck, to)
}

// ---- Writer shortcuts -----------------------------------------------------

pub fn docx_to_html_bytes(input: &[u8]) -> Result<Vec<u8>> {
    writer_convert_bytes(input, "docx", "html")
}
pub fn docx_to_txt_bytes(input: &[u8]) -> Result<Vec<u8>> {
    writer_convert_bytes(input, "docx", "txt")
}
pub fn docx_to_odt_bytes(input: &[u8]) -> Result<Vec<u8>> {
    writer_convert_bytes(input, "docx", "odt")
}
pub fn odt_to_pdf_bytes(input: &[u8]) -> Result<Vec<u8>> {
    writer_convert_bytes(input, "odt", "pdf")
}
pub fn odt_to_docx_bytes(input: &[u8]) -> Result<Vec<u8>> {
    writer_convert_bytes(input, "odt", "docx")
}
pub fn odt_to_html_bytes(input: &[u8]) -> Result<Vec<u8>> {
    writer_convert_bytes(input, "odt", "html")
}

// ---- Calc shortcuts -------------------------------------------------------

pub fn xlsx_to_pdf_bytes(input: &[u8]) -> Result<Vec<u8>> {
    calc_convert_bytes(input, "xlsx", "pdf")
}
pub fn xlsx_to_html_bytes(input: &[u8]) -> Result<Vec<u8>> {
    calc_convert_bytes(input, "xlsx", "html")
}
pub fn xlsx_to_csv_bytes(input: &[u8]) -> Result<Vec<u8>> {
    calc_convert_bytes(input, "xlsx", "csv")
}
pub fn xlsx_to_ods_bytes(input: &[u8]) -> Result<Vec<u8>> {
    calc_convert_bytes(input, "xlsx", "ods")
}
pub fn ods_to_pdf_bytes(input: &[u8]) -> Result<Vec<u8>> {
    calc_convert_bytes(input, "ods", "pdf")
}
pub fn ods_to_xlsx_bytes(input: &[u8]) -> Result<Vec<u8>> {
    calc_convert_bytes(input, "ods", "xlsx")
}
pub fn ods_to_csv_bytes(input: &[u8]) -> Result<Vec<u8>> {
    calc_convert_bytes(input, "ods", "csv")
}

// ---- Impress shortcuts ----------------------------------------------------

pub fn pptx_to_html_bytes(input: &[u8]) -> Result<Vec<u8>> {
    impress_convert_bytes(input, "pptx", "html")
}
pub fn pptx_to_svg_bytes(input: &[u8]) -> Result<Vec<u8>> {
    impress_convert_bytes(input, "pptx", "svg")
}
pub fn pptx_to_odp_bytes(input: &[u8]) -> Result<Vec<u8>> {
    impress_convert_bytes(input, "pptx", "odp")
}
pub fn odp_to_pdf_bytes(input: &[u8]) -> Result<Vec<u8>> {
    impress_convert_bytes(input, "odp", "pdf")
}
pub fn odp_to_pptx_bytes(input: &[u8]) -> Result<Vec<u8>> {
    impress_convert_bytes(input, "odp", "pptx")
}

// ---------------------------------------------------------------------------
// XLSX recalc
// ---------------------------------------------------------------------------

/// Re-evaluate every formula in an XLSX workbook and rewrite the cached
/// `<v>` values inside the existing sheet XML. The result is a fresh
/// XLSX byte stream with the same shape as the input, minus the
/// `xl/calcChain.xml` part.
pub fn xlsx_recalc_bytes(bytes: &[u8]) -> Result<Vec<u8>> {
    let zip = ZipArchive::new(bytes)?;
    let workbook = lo_calc::from_xlsx_bytes("workbook", bytes)?;
    let sheet_targets = parse_xlsx_sheet_targets(&zip)?;

    let mut entries: Vec<lo_zip::ZipEntry> = Vec::new();
    for entry_name in zip.entries() {
        let path = normalize_zip_path(entry_name);
        if path == "xl/calcChain.xml" {
            continue;
        }
        if path == "[Content_Types].xml" {
            let xml = zip.read_string(&path)?;
            let mut root = parse_xml_document(&xml)?;
            remove_content_type_override(&mut root, "/xl/calcChain.xml");
            entries.push(lo_zip::ZipEntry::new(
                path,
                serialize_xml_document(&root).into_bytes(),
            ));
            continue;
        }
        if path == "xl/_rels/workbook.xml.rels" {
            let xml = zip.read_string(&path)?;
            let mut root = parse_xml_document(&xml)?;
            remove_calc_chain_relationships(&mut root);
            entries.push(lo_zip::ZipEntry::new(
                path,
                serialize_xml_document(&root).into_bytes(),
            ));
            continue;
        }
        if path == "xl/workbook.xml" {
            let xml = zip.read_string(&path)?;
            let mut root = parse_xml_document(&xml)?;
            mark_workbook_recalculated(&mut root);
            entries.push(lo_zip::ZipEntry::new(
                path,
                serialize_xml_document(&root).into_bytes(),
            ));
            continue;
        }
        if let Some(sheet_index) = sheet_targets.iter().position(|(target, _)| target == &path) {
            if let Some(sheet) = workbook.sheets.get(sheet_index) {
                let xml = zip.read_string(&path)?;
                let mut root = parse_xml_document(&xml)?;
                patch_xlsx_sheet_formula_cache(&mut root, sheet)?;
                entries.push(lo_zip::ZipEntry::new(
                    path,
                    serialize_xml_document(&root).into_bytes(),
                ));
                continue;
            }
        }
        entries.push(lo_zip::ZipEntry::new(path, zip.read(entry_name)?));
    }
    lo_zip::ooxml_package(&entries)
}

fn parse_xlsx_sheet_targets(zip: &ZipArchive) -> Result<Vec<(String, String)>> {
    let workbook_root = parse_xml_document(&zip.read_string("xl/workbook.xml")?)?;
    let rels = parse_relationships(zip, "xl/workbook.xml")?;
    let mut out = Vec::new();
    if let Some(sheets) = workbook_root.child("sheets") {
        for (index, sheet) in sheets.children_named("sheet").enumerate() {
            let name = sheet.attr("name").unwrap_or("Sheet").to_string();
            let target = sheet
                .attr("id")
                .or_else(|| sheet.attr("r:id"))
                .and_then(|id| rels.get(id))
                .cloned()
                .unwrap_or_else(|| format!("xl/worksheets/sheet{}.xml", index + 1));
            out.push((normalize_zip_path(&target), name));
        }
    }
    Ok(out)
}

fn parse_relationships(zip: &ZipArchive, part: &str) -> Result<BTreeMap<String, String>> {
    let rels_path = rels_path_for(part);
    if !zip.contains(&rels_path) {
        return Ok(BTreeMap::new());
    }
    let root = parse_xml_document(&zip.read_string(&rels_path)?)?;
    let mut map = BTreeMap::new();
    for rel in root.children_named("Relationship") {
        if let (Some(id), Some(target)) = (rel.attr("Id"), rel.attr("Target")) {
            map.insert(id.to_string(), resolve_part_target(part, target));
        }
    }
    Ok(map)
}

fn remove_content_type_override(root: &mut XmlNode, part_name: &str) {
    root.items.retain(|item| match item {
        XmlItem::Node(node) if node.local_name() == "Override" => {
            node.attr("PartName") != Some(part_name)
        }
        _ => true,
    });
    sync_node_children(root);
}

fn remove_calc_chain_relationships(root: &mut XmlNode) {
    root.items.retain(|item| match item {
        XmlItem::Node(node) if node.local_name() == "Relationship" => {
            let target = node.attr("Target").unwrap_or("");
            let rel_type = node.attr("Type").unwrap_or("");
            !target.ends_with("calcChain.xml")
                && !rel_type.to_ascii_lowercase().contains("calcchain")
        }
        _ => true,
    });
    sync_node_children(root);
}

fn mark_workbook_recalculated(root: &mut XmlNode) {
    let mut found = false;
    for item in &mut root.items {
        if let XmlItem::Node(node) = item {
            if node.local_name() == "calcPr" {
                node.attributes
                    .insert("calcCompleted".to_string(), "1".to_string());
                node.attributes
                    .insert("fullCalcOnLoad".to_string(), "0".to_string());
                node.attributes.remove("calcMode");
                found = true;
            }
        }
    }
    if !found {
        let mut attrs = BTreeMap::new();
        attrs.insert("calcCompleted".to_string(), "1".to_string());
        attrs.insert("fullCalcOnLoad".to_string(), "0".to_string());
        root.items.push(XmlItem::Node(XmlNode {
            name: "calcPr".to_string(),
            attributes: attrs,
            children: Vec::new(),
            items: Vec::new(),
            text: String::new(),
        }));
    }
    sync_node_children(root);
}

fn patch_xlsx_sheet_formula_cache(root: &mut XmlNode, sheet: &Sheet) -> Result<()> {
    let Some(sheet_data) = child_mut(root, "sheetData") else {
        return Ok(());
    };
    for row in &mut sheet_data.children {
        if row.local_name() != "row" {
            continue;
        }
        let row_number = row
            .attr("r")
            .and_then(|value| value.parse::<usize>().ok())
            .unwrap_or(1);
        for cell in &mut row.children {
            if cell.local_name() == "c" {
                patch_formula_cell(cell, row_number, sheet)?;
            }
        }
        sync_node_items_from_children(row);
    }
    sync_node_items_from_children(sheet_data);
    sync_node_items_from_children(root);
    Ok(())
}

fn patch_formula_cell(cell: &mut XmlNode, fallback_row: usize, sheet: &Sheet) -> Result<()> {
    let formula = cell
        .children
        .iter()
        .find(|child| child.local_name() == "f")
        .map(|node| text_content(node));
    let Some(formula) = formula else {
        return Ok(());
    };
    if formula.trim().is_empty() {
        return Ok(());
    }
    let (row_1, col_1) = cell
        .attr("r")
        .and_then(parse_a1_cell_ref)
        .unwrap_or((fallback_row, 1));
    let _addr = CellAddr::new(
        row_1.saturating_sub(1) as u32,
        col_1.saturating_sub(1) as u32,
    );
    let value = evaluate_formula(&formula, sheet)?;
    let mut new_items = Vec::new();
    for item in &cell.items {
        match item {
            XmlItem::Text(text) => new_items.push(XmlItem::Text(text.clone())),
            XmlItem::Node(node) if matches!(node.local_name(), "v" | "is") => {}
            XmlItem::Node(node) => new_items.push(XmlItem::Node(node.clone())),
        }
    }
    new_items.push(XmlItem::Node(make_value_node(&value)));
    cell.items = new_items;
    sync_node_children(cell);
    apply_formula_cache_type(cell, &value);
    Ok(())
}

fn text_content(node: &XmlNode) -> String {
    let mut out = String::new();
    if !node.text.is_empty() {
        out.push_str(&node.text);
    }
    for child in &node.children {
        out.push_str(&text_content(child));
    }
    out
}

fn apply_formula_cache_type(cell: &mut XmlNode, value: &Value) {
    match value {
        Value::Number(_) | Value::Blank => {
            cell.attributes.remove("t");
        }
        Value::Text(_) => {
            cell.attributes.insert("t".to_string(), "str".to_string());
        }
        Value::Bool(_) => {
            cell.attributes.insert("t".to_string(), "b".to_string());
        }
        Value::Error(_) => {
            cell.attributes.insert("t".to_string(), "e".to_string());
        }
    }
}

fn make_value_node(value: &Value) -> XmlNode {
    let text = match value {
        Value::Blank => String::new(),
        Value::Number(number) => {
            if number.fract() == 0.0 && number.is_finite() {
                format!("{}", *number as i64)
            } else {
                number.to_string()
            }
        }
        Value::Text(text) => text.clone(),
        Value::Bool(value) => {
            if *value {
                "1".to_string()
            } else {
                "0".to_string()
            }
        }
        Value::Error(text) => text.clone(),
    };
    XmlNode {
        name: "v".to_string(),
        attributes: BTreeMap::new(),
        children: Vec::new(),
        items: if text.is_empty() {
            Vec::new()
        } else {
            vec![XmlItem::Text(text.clone())]
        },
        text,
    }
}

fn parse_a1_cell_ref(input: &str) -> Option<(usize, usize)> {
    let mut letters = String::new();
    let mut digits = String::new();
    for ch in input.chars() {
        if ch == '$' {
            continue;
        }
        if ch.is_ascii_alphabetic() && digits.is_empty() {
            letters.push(ch);
        } else if ch.is_ascii_digit() {
            digits.push(ch);
        } else {
            return None;
        }
    }
    if letters.is_empty() || digits.is_empty() {
        return None;
    }
    let row = digits.parse().ok()?;
    let mut col = 0usize;
    for ch in letters.chars() {
        col = col * 26 + ((ch.to_ascii_uppercase() as u8 - b'A' + 1) as usize);
    }
    Some((row, col))
}

// ---------------------------------------------------------------------------
// Accept all tracked changes
// ---------------------------------------------------------------------------

/// Walk every WordprocessingML part inside a DOCX, accept all `w:ins`
/// (insertions) and discard all `w:del`/`w:delText`/`w:moveFrom`/related
/// revision markers, then re-emit the package.
pub fn accept_all_tracked_changes_docx_bytes(bytes: &[u8]) -> Result<Vec<u8>> {
    let zip = ZipArchive::new(bytes)?;
    let mut entries: Vec<lo_zip::ZipEntry> = Vec::new();
    for entry_name in zip.entries() {
        let path = normalize_zip_path(entry_name);
        if is_wordprocessing_xml(&path) {
            let xml = zip.read_string(&path)?;
            let root = parse_xml_document(&xml)?;
            let accepted = accept_revision_root(&root, &path);
            entries.push(lo_zip::ZipEntry::new(
                path,
                serialize_xml_document(&accepted).into_bytes(),
            ));
        } else {
            entries.push(lo_zip::ZipEntry::new(path, zip.read(entry_name)?));
        }
    }
    lo_zip::ooxml_package(&entries)
}

/// Alias kept for parity with the upstream package's helper name.
pub fn accept_tracked_changes_docx_bytes(bytes: &[u8]) -> Result<Vec<u8>> {
    accept_all_tracked_changes_docx_bytes(bytes)
}

/// Alias kept for parity with the upstream package's helper name.
pub fn recalc_existing_xlsx_bytes(bytes: &[u8]) -> Result<Vec<u8>> {
    xlsx_recalc_bytes(bytes)
}

fn is_wordprocessing_xml(path: &str) -> bool {
    path.starts_with("word/")
        && path.ends_with(".xml")
        && !path.contains("_rels/")
        && !path.ends_with("fontTable.xml")
}

fn accept_revision_root(root: &XmlNode, path: &str) -> XmlNode {
    let items = accept_revision_items(&root.items);
    let mut node = rebuild_node(root, items, root.attributes.clone());
    if path.ends_with("settings.xml") {
        // settings.xml carries the document-wide <w:trackRevisions/>
        // toggle. After accepting all revisions we also turn track
        // changes off so re-opening the file in Word doesn't immediately
        // start recording again.
        node.items.retain(
            |item| !matches!(item, XmlItem::Node(child) if child.local_name() == "trackRevisions"),
        );
        sync_node_children(&mut node);
    }
    node
}

fn accept_revision_items(items: &[XmlItem]) -> Vec<XmlItem> {
    let mut out = Vec::new();
    for item in items {
        match item {
            XmlItem::Text(text) => out.push(XmlItem::Text(text.clone())),
            XmlItem::Node(node) => out.extend(accept_revision_node(node)),
        }
    }
    out
}

fn accept_revision_node(node: &XmlNode) -> Vec<XmlItem> {
    let local = node.local_name();
    // Drop deletions, move-source markers, and revision-history change
    // siblings outright. The full list mirrors the WordprocessingML
    // tracked-changes element vocabulary.
    if matches!(
        local,
        "del"
            | "delText"
            | "delInstrText"
            | "cellDel"
            | "moveFrom"
            | "moveFromRangeStart"
            | "moveFromRangeEnd"
            | "moveToRangeStart"
            | "moveToRangeEnd"
            | "customXmlDelRangeStart"
            | "customXmlDelRangeEnd"
            | "customXmlMoveFromRangeStart"
            | "customXmlMoveFromRangeEnd"
            | "customXmlMoveToRangeStart"
            | "customXmlMoveToRangeEnd"
            | "trackRevisions"
    ) {
        return Vec::new();
    }
    // Insertions and move targets are unwrapped — their text becomes
    // part of the surrounding paragraph.
    if matches!(
        local,
        "ins" | "moveTo" | "customXmlInsRangeStart" | "customXmlInsRangeEnd"
    ) {
        return accept_revision_items(&node.items);
    }
    // pPrChange/rPrChange/etc. are revision history snapshots — keep
    // the surrounding properties node, drop the change record itself.
    if local.ends_with("Change") {
        return Vec::new();
    }
    // Whole rows marked as deleted via <w:trPr><w:del/></w:trPr> are
    // dropped along with their contents.
    if row_deleted(node) {
        return Vec::new();
    }
    let items = accept_revision_items(&node.items);
    vec![XmlItem::Node(rebuild_node(
        node,
        items,
        node.attributes.clone(),
    ))]
}

fn row_deleted(node: &XmlNode) -> bool {
    if node.local_name() != "tr" {
        return false;
    }
    node.child("trPr")
        .map(|trpr| {
            trpr.children
                .iter()
                .any(|child| child.local_name() == "del")
        })
        .unwrap_or(false)
}

// ---------------------------------------------------------------------------
// Shared XmlNode mutation helpers
// ---------------------------------------------------------------------------

fn rebuild_node(
    template: &XmlNode,
    items: Vec<XmlItem>,
    attributes: BTreeMap<String, String>,
) -> XmlNode {
    let mut node = XmlNode {
        name: template.name.clone(),
        attributes,
        children: Vec::new(),
        items,
        text: String::new(),
    };
    sync_node_children(&mut node);
    node
}

fn sync_node_children(node: &mut XmlNode) {
    node.children = node
        .items
        .iter()
        .filter_map(|item| match item {
            XmlItem::Node(child) => Some(child.clone()),
            _ => None,
        })
        .collect();
    node.text = node
        .items
        .iter()
        .filter_map(|item| match item {
            XmlItem::Text(text) => Some(text.clone()),
            _ => None,
        })
        .collect::<Vec<_>>()
        .join("");
}

fn sync_node_items_from_children(node: &mut XmlNode) {
    let mut child_index = 0usize;
    let mut new_items = Vec::with_capacity(node.items.len().max(node.children.len()));
    for item in &node.items {
        match item {
            XmlItem::Text(text) => new_items.push(XmlItem::Text(text.clone())),
            XmlItem::Node(_) => {
                if let Some(updated) = node.children.get(child_index) {
                    new_items.push(XmlItem::Node(updated.clone()));
                    child_index += 1;
                }
            }
        }
    }
    while let Some(updated) = node.children.get(child_index) {
        new_items.push(XmlItem::Node(updated.clone()));
        child_index += 1;
    }
    node.items = new_items;
    sync_node_children(node);
}

fn child_mut<'a>(node: &'a mut XmlNode, name: &str) -> Option<&'a mut XmlNode> {
    node.children
        .iter_mut()
        .find(|child| child.local_name() == name || child.name == name)
}

#[allow(dead_code)]
fn _assert_send_sync() {
    fn assert<T: Send + Sync>() {}
    assert::<Result<Vec<u8>>>();
    let _ = LoError::Parse(String::new());
}