rusty_xml-tree 0.8.0

Arena DOM for rusty_xml (libxml2 tree.h semantics)
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
812
813
814
815
816
//! Arena DOM matching libxml2 `tree.h` ownership: the document owns every node.
//! Handles are indices, not parent+child `&mut` pairs.

#![forbid(unsafe_code)]

use std::collections::HashMap;

/// libxml2 `xmlElementType` discriminants.
#[derive(Clone, Copy, PartialEq, Eq, Debug)]
#[repr(u32)]
pub enum NodeKind {
    Element = 1,
    Attribute = 2,
    Text = 3,
    CData = 4,
    EntityRef = 5,
    Entity = 6,
    Pi = 7,
    Comment = 8,
    Document = 9,
    DocumentType = 10,
    DocumentFrag = 11,
    Notation = 12,
    HtmlDocument = 13,
    Dtd = 14,
    ElementDecl = 15,
    AttributeDecl = 16,
    EntityDecl = 17,
    Namespace = 18,
    XIncludeStart = 19,
    XIncludeEnd = 20,
}

/// Parsed DTD attached to a document (`xmlDtd`).
#[derive(Clone, Debug, Default)]
pub struct XmlDtd {
    pub name: Option<String>,
    pub public_id: Option<String>,
    pub system_id: Option<String>,
    pub int_subset: Option<String>,
    /// General entity name → replacement text.
    pub entities: HashMap<String, String>,
    /// Parameter entity name → replacement.
    pub parameter_entities: HashMap<String, String>,
    /// Names of entities declared with an NDATA annotation. An attribute of
    /// type ENTITY must name one of these, which needs them kept apart from
    /// parsed entities rather than lumped in with them.
    pub unparsed_entities: std::collections::HashSet<String>,
    /// Notation names declared by `<!NOTATION>`. We parsed those declarations
    /// and threw the name away, so nothing could check that an NDATA
    /// annotation or a NOTATION attribute type names one that exists.
    pub notations: std::collections::HashSet<String>,
    /// Notation names referenced by an NDATA annotation, kept so the
    /// "Notation Declared" constraint can be checked once the whole subset is
    /// read rather than in declaration order.
    pub ndata_notations: Vec<String>,
    /// The internal subset used a parameter entity reference, so the set of
    /// entity declarations may be incomplete. XML 1.0 4.1 turns "Entity
    /// Declared" from a well-formedness constraint into a validity one in that
    /// case: an unresolvable entity must not kill the parse.
    pub has_parameter_entity_refs: bool,
    /// Namespace errors found while reading the subset -- a colon in an entity
    /// or notation name. Merged into the document's list.
    pub namespace_errors: Vec<String>,
    /// Element name → content model.
    pub elements: HashMap<String, ElementDecl>,
    /// Element types declared more than once. A map cannot represent that, and
    /// "Unique Element Type Declaration" is a validity constraint, so it has to
    /// be recorded as the declarations go by and reported at validation time
    /// rather than at parse time.
    pub duplicate_elements: Vec<String>,
    /// (element, attribute) → declaration.
    pub attributes: HashMap<(String, String), AttrDecl>,
}

#[derive(Clone, Debug)]
pub enum ElementDecl {
    Empty,
    Any,
    Mixed(Vec<String>),
    Children(String),
}

#[derive(Clone, Debug)]
pub struct AttrDecl {
    pub att_type: String,
    pub default: AttrDefault,
    pub default_value: Option<String>,
    pub enumerated: Vec<String>,
}

#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum AttrDefault {
    Required,
    Implied,
    Fixed,
    Value,
}

/// Stable handle into an [`XmlDoc`] arena. Valid for the lifetime of the doc.
#[derive(Clone, Copy, PartialEq, Eq, Hash, Debug)]
pub struct NodeId(pub u32);

impl NodeId {
    /// Document node is always slot 0.
    pub const DOCUMENT: NodeId = NodeId(0);

    pub fn index(self) -> usize {
        self.0 as usize
    }
}



#[derive(Clone, Debug)]
pub struct Node {
    pub kind: NodeKind,
    pub name: String,
    pub prefix: Option<String>,
    pub ns_uri: Option<String>,
    pub content: String,
    pub parent: Option<NodeId>,
    pub first_child: Option<NodeId>,
    pub last_child: Option<NodeId>,
    pub prev_sibling: Option<NodeId>,
    pub next_sibling: Option<NodeId>,
    pub first_attr: Option<NodeId>,
    pub last_attr: Option<NodeId>,
    /// Namespace declarations on this element (`xmlns` / `xmlns:prefix`), in source order.
    pub ns_defs: Vec<(Option<String>, String)>,
}

impl Node {
    fn new(kind: NodeKind, name: String) -> Self {
        Self {
            kind,
            name,
            prefix: None,
            ns_uri: None,
            content: String::new(),
            parent: None,
            first_child: None,
            last_child: None,
            prev_sibling: None,
            next_sibling: None,
            first_attr: None,
            last_attr: None,
            ns_defs: Vec::new(),
        }
    }
}

/// libxml2 `xmlDoc`.
#[derive(Clone, Debug)]
pub struct XmlDoc {
    nodes: Vec<Node>,
    /// XML version string; default `"1.0"`.
    pub version: String,
    /// Encoding name from the XML declaration, if any.
    pub encoding: Option<String>,
    /// `Some(true/false)` from `standalone`, `None` if omitted.
    pub standalone: Option<bool>,
    /// First element child of the document (cached; also discoverable by walk).
    root: Option<NodeId>,
    /// Internal / attached DTD, if any.
    pub dtd: Option<XmlDtd>,
    /// Entity references the parse could not resolve. They are kept as written
    /// rather than being fatal when the subset is incomplete, and the
    /// validator reports them.
    pub undeclared_entity_refs: Vec<String>,
    /// Text nodes whose content came from a character or entity reference.
    ///
    /// Such text is never ignorable whitespace: `<foo><foo/>&#32;<foo/></foo>`
    /// against an element-only content model is character data where none is
    /// allowed, and looking only at whether the text is blank cannot tell it
    /// from the indentation beside it.
    /// Namespace errors reported while parsing.
    ///
    /// A namespace violation is never a well-formedness error: libxml2 parses
    /// the document and logs one, and its own conformance harness scores the
    /// namespace tests by looking for exactly that -- the document must parse
    /// AND an error must have been reported. Rejecting instead would refuse
    /// input C reads, so they are recorded here for the caller to inspect.
    pub namespace_errors: Vec<String>,
    /// Non-fatal problems worth telling the caller about -- currently a
    /// declared encoding that contradicts the byte-order mark. The SAX error
    /// channel carries these too, but the default handler discards them, so a
    /// tree-parsing caller had no way to learn of one.
    pub warnings: Vec<String>,
    pub reference_text: std::collections::HashSet<NodeId>,
    /// Elements whose content included an entity reference, including one that
    /// expanded to nothing. `<foo>&empty;</foo>` against EMPTY is content, and
    /// the tree has no node to show for it.
    pub elements_with_entity_refs: std::collections::HashSet<NodeId>,
}

impl Default for XmlDoc {
    fn default() -> Self {
        Self::xml_new_doc(Some("1.0"))
    }
}

impl XmlDoc {
    /// `xmlNewDoc`.
    #[doc(alias = "xmlNewDoc")]
    pub fn xml_new_doc(version: Option<&str>) -> Self {
        Self::with_node_capacity(version, 1)
    }

    /// Build a document whose node arena is sized up front. Starting a parse
    /// used to allocate the arena, push into it, then reallocate on reserve --
    /// three trips for what one sized allocation does. The document node's
    /// name is implied by its kind, so it stores no String either.
    pub fn with_node_capacity(version: Option<&str>, cap: usize) -> Self {
        const MAX_ARENA_BYTES: usize = 32 << 20;
        let ceiling = MAX_ARENA_BYTES / std::mem::size_of::<Node>();
        // A floor of 4 keeps a small document from reallocating its way up
        // from a single slot, which is what Vec::new()+push used to give it.
        let mut nodes = Vec::with_capacity(cap.clamp(4, ceiling));
        nodes.push(Node::new(NodeKind::Document, String::new()));
        Self {
            nodes,
            version: version.unwrap_or("1.0").to_string(),
            encoding: None,
            standalone: None,
            root: None,
            dtd: None,
            undeclared_entity_refs: Vec::new(),
            namespace_errors: Vec::new(),
            warnings: Vec::new(),
            reference_text: Default::default(),
            elements_with_entity_refs: Default::default(),
        }
    }

    /// Pre-size the node arena. XML runs about one node per 10-15 input bytes,
    /// so a parser that knows the document length can skip most of the arena's
    /// doubling-and-copy. Capped so a huge document cannot reserve wildly.
    pub fn reserve_nodes(&mut self, n: usize) {
        // Measured node density is ~1 per 10-12 input bytes. The previous cap
        // of 65_536 was below a 700 KB document's node count, so the arena
        // still doubled-and-copied its way up -- about 22 MB of memcpy on a
        // 627 KB file. Shrinking Node itself would need an API break for a
        // sub-1% effect; reserving correctly removes the same traffic for free.
        // Cap by memory, not node count: 1<<20 nodes is ~190 MB of arena, which
        // a large document would commit up front before parsing a byte.
        const MAX_ARENA_BYTES: usize = 32 << 20;
        let cap = MAX_ARENA_BYTES / std::mem::size_of::<Node>();
        self.nodes.reserve(n.min(cap));
    }

    pub fn node(&self, id: NodeId) -> &Node {
        &self.nodes[id.index()]
    }

    pub fn node_mut(&mut self, id: NodeId) -> &mut Node {
        &mut self.nodes[id.index()]
    }

    pub fn kind(&self, id: NodeId) -> NodeKind {
        self.node(id).kind
    }

    pub fn name(&self, id: NodeId) -> &str {
        let n = self.node(id);
        if n.name.is_empty() {
            // Nodes whose name is fixed by their kind store no String at all;
            // allocating "#text" once per text node was a measurable share of
            // every parse. The canonical name is derived here instead.
            return match n.kind {
                NodeKind::Text => "#text",
                NodeKind::CData => "#cdata-section",
                NodeKind::Comment => "#comment",
                NodeKind::Document => "#document",
                _ => "",
            };
        }
        &n.name
    }

    pub fn prefix(&self, id: NodeId) -> Option<&str> {
        self.node(id).prefix.as_deref()
    }

    pub fn ns_uri(&self, id: NodeId) -> Option<&str> {
        self.node(id).ns_uri.as_deref()
    }

    pub fn content(&self, id: NodeId) -> &str {
        &self.node(id).content
    }

    pub fn parent(&self, id: NodeId) -> Option<NodeId> {
        self.node(id).parent
    }

    pub fn first_child(&self, id: NodeId) -> Option<NodeId> {
        self.node(id).first_child
    }

    pub fn last_child(&self, id: NodeId) -> Option<NodeId> {
        self.node(id).last_child
    }

    pub fn next_sibling(&self, id: NodeId) -> Option<NodeId> {
        self.node(id).next_sibling
    }

    pub fn prev_sibling(&self, id: NodeId) -> Option<NodeId> {
        self.node(id).prev_sibling
    }

    pub fn first_attr(&self, id: NodeId) -> Option<NodeId> {
        self.node(id).first_attr
    }

    pub fn ns_defs(&self, id: NodeId) -> &[(Option<String>, String)] {
        &self.node(id).ns_defs
    }

    /// Allocate a node whose name is implied by its kind, storing no String.
    /// [`XmlDoc::name`] reports the canonical name for these.
    pub fn alloc_unnamed(&mut self, kind: NodeKind) -> NodeId {
        let id = NodeId(self.nodes.len() as u32);
        self.nodes.push(Node::new(kind, String::new()));
        id
    }

    pub fn alloc(&mut self, kind: NodeKind, name: impl Into<String>) -> NodeId {
        let id = NodeId(self.nodes.len() as u32);
        self.nodes.push(Node::new(kind, name.into()));
        id
    }

    /// `xmlDocGetRootElement`.
    #[doc(alias = "xmlDocGetRootElement")]
    pub fn xml_doc_get_root_element(&self) -> Option<NodeId> {
        if let Some(r) = self.root {
            return Some(r);
        }
        let mut c = self.first_child(NodeId::DOCUMENT);
        while let Some(id) = c {
            if self.kind(id) == NodeKind::Element {
                return Some(id);
            }
            c = self.next_sibling(id);
        }
        None
    }

    /// `xmlDocSetRootElement`. Returns the previous root, if any.
    #[doc(alias = "xmlDocSetRootElement")]
    pub fn xml_doc_set_root_element(&mut self, elem: NodeId) -> Option<NodeId> {
        let prev = self.xml_doc_get_root_element();
        if let Some(p) = prev {
            self.xml_unlink_node(p);
        }
        self.xml_add_child(NodeId::DOCUMENT, elem);
        self.root = Some(elem);
        prev
    }

    /// `xmlNewNode`.
    #[doc(alias = "xmlNewNode")]
    pub fn xml_new_node(&mut self, ns_uri: Option<&str>, name: &str) -> NodeId {
        let id = self.alloc(NodeKind::Element, name);
        self.node_mut(id).ns_uri = ns_uri.map(str::to_string);
        id
    }

    /// `xmlNewDocNode`.
    #[doc(alias = "xmlNewDocNode")]
    pub fn xml_new_doc_node(
        &mut self,
        ns_uri: Option<&str>,
        name: &str,
        content: Option<&str>,
    ) -> NodeId {
        let id = self.xml_new_node(ns_uri, name);
        if let Some(c) = content {
            if !c.is_empty() {
                let t = self.alloc(NodeKind::Text, "#text");
                self.node_mut(t).content = c.to_string();
                self.xml_add_child(id, t);
            }
        }
        id
    }

    /// `xmlNewChild`.
    #[doc(alias = "xmlNewChild")]
    pub fn xml_new_child(
        &mut self,
        parent: NodeId,
        ns_uri: Option<&str>,
        name: &str,
        content: Option<&str>,
    ) -> NodeId {
        let id = self.xml_new_doc_node(ns_uri, name, content);
        self.xml_add_child(parent, id);
        id
    }

    /// `xmlAddChild`.
    #[doc(alias = "xmlAddChild")]
    pub fn xml_add_child(&mut self, parent: NodeId, child: NodeId) {
        if child == parent {
            return;
        }
        self.xml_unlink_node(child);
        self.node_mut(child).parent = Some(parent);
        let last = self.node(parent).last_child;
        if let Some(l) = last {
            self.node_mut(l).next_sibling = Some(child);
            self.node_mut(child).prev_sibling = Some(l);
        } else {
            self.node_mut(parent).first_child = Some(child);
        }
        self.node_mut(parent).last_child = Some(child);
        if parent == NodeId::DOCUMENT && self.kind(child) == NodeKind::Element {
            self.root = Some(child);
        }
    }

    /// `xmlAddNextSibling`.
    #[doc(alias = "xmlAddNextSibling")]
    pub fn xml_add_next_sibling(&mut self, cur: NodeId, elem: NodeId) {
        self.xml_unlink_node(elem);
        let parent = self.node(cur).parent;
        let next = self.node(cur).next_sibling;
        self.node_mut(elem).parent = parent;
        self.node_mut(elem).prev_sibling = Some(cur);
        self.node_mut(elem).next_sibling = next;
        self.node_mut(cur).next_sibling = Some(elem);
        if let Some(n) = next {
            self.node_mut(n).prev_sibling = Some(elem);
        } else if let Some(p) = parent {
            self.node_mut(p).last_child = Some(elem);
        }
    }

    /// `xmlAddPrevSibling`.
    #[doc(alias = "xmlAddPrevSibling")]
    pub fn xml_add_prev_sibling(&mut self, cur: NodeId, elem: NodeId) {
        self.xml_unlink_node(elem);
        let parent = self.node(cur).parent;
        let prev = self.node(cur).prev_sibling;
        self.node_mut(elem).parent = parent;
        self.node_mut(elem).next_sibling = Some(cur);
        self.node_mut(elem).prev_sibling = prev;
        self.node_mut(cur).prev_sibling = Some(elem);
        if let Some(p) = prev {
            self.node_mut(p).next_sibling = Some(elem);
        } else if let Some(par) = parent {
            self.node_mut(par).first_child = Some(elem);
        }
    }

    /// `xmlUnlinkNode`.
    #[doc(alias = "xmlUnlinkNode")]
    pub fn xml_unlink_node(&mut self, id: NodeId) {
        if id == NodeId::DOCUMENT {
            return;
        }
        let parent = self.node(id).parent;
        let prev = self.node(id).prev_sibling;
        let next = self.node(id).next_sibling;
        if let Some(p) = prev {
            self.node_mut(p).next_sibling = next;
        }
        if let Some(n) = next {
            self.node_mut(n).prev_sibling = prev;
        }
        if let Some(par) = parent {
            if self.node(par).first_child == Some(id) {
                self.node_mut(par).first_child = next;
            }
            if self.node(par).last_child == Some(id) {
                self.node_mut(par).last_child = prev;
            }
        }
        if self.root == Some(id) {
            self.root = None;
        }
        self.node_mut(id).parent = None;
        self.node_mut(id).prev_sibling = None;
        self.node_mut(id).next_sibling = None;
    }

    /// `xmlReplaceNode`.
    #[doc(alias = "xmlReplaceNode")]
    pub fn xml_replace_node(&mut self, old: NodeId, new: NodeId) -> NodeId {
        self.xml_add_next_sibling(old, new);
        self.xml_unlink_node(old);
        new
    }

    /// As [`XmlDoc::add_attr`], but takes ownership. The borrowing form has to
    /// allocate a fresh String for the name, the prefix and the value, all of
    /// which the parser already owns.
    pub fn add_attr_owned(
        &mut self,
        elem: NodeId,
        name: String,
        prefix: Option<String>,
        value: String,
    ) -> NodeId {
        let id = self.alloc(NodeKind::Attribute, name);
        self.node_mut(id).prefix = prefix;
        self.node_mut(id).content = value;
        self.node_mut(id).parent = Some(elem);
        let last = self.node(elem).last_attr;
        if let Some(l) = last {
            self.node_mut(l).next_sibling = Some(id);
            self.node_mut(id).prev_sibling = Some(l);
        } else {
            self.node_mut(elem).first_attr = Some(id);
        }
        self.node_mut(elem).last_attr = Some(id);
        id
    }

    pub fn add_attr(&mut self, elem: NodeId, name: &str, prefix: Option<&str>, value: &str) -> NodeId {
        let id = self.alloc(NodeKind::Attribute, name);
        self.node_mut(id).prefix = prefix.map(str::to_string);
        self.node_mut(id).content = value.to_string();
        self.node_mut(id).parent = Some(elem);
        let last = self.node(elem).last_attr;
        if let Some(l) = last {
            self.node_mut(l).next_sibling = Some(id);
            self.node_mut(id).prev_sibling = Some(l);
        } else {
            self.node_mut(elem).first_attr = Some(id);
        }
        self.node_mut(elem).last_attr = Some(id);
        id
    }

    pub fn push_ns_def(&mut self, elem: NodeId, prefix: Option<String>, uri: String) {
        self.node_mut(elem).ns_defs.push((prefix, uri));
    }

    /// `xmlSetProp`.
    #[doc(alias = "xmlSetProp")]
    pub fn xml_set_prop(&mut self, node: NodeId, name: &str, value: &str) -> NodeId {
        let mut a = self.first_attr(node);
        while let Some(id) = a {
            if self.node(id).prefix.is_none() && self.node(id).name == name {
                self.node_mut(id).content = value.to_string();
                return id;
            }
            a = self.next_sibling(id);
        }
        self.add_attr(node, name, None, value)
    }

    /// `xmlGetProp`.
    #[doc(alias = "xmlGetProp")]
    pub fn xml_get_prop(&self, node: NodeId, name: &str) -> Option<String> {
        let mut a = self.first_attr(node);
        while let Some(id) = a {
            if self.node(id).prefix.is_none() && self.node(id).name == name {
                return Some(self.node(id).content.clone());
            }
            a = self.next_sibling(id);
        }
        None
    }

    /// `xmlHasProp`.
    #[doc(alias = "xmlHasProp")]
    pub fn xml_has_prop(&self, node: NodeId, name: &str) -> bool {
        self.xml_get_prop(node, name).is_some()
    }

    /// `xmlUnsetProp`.
    #[doc(alias = "xmlUnsetProp")]
    pub fn xml_unset_prop(&mut self, node: NodeId, name: &str) -> bool {
        let mut a = self.first_attr(node);
        let mut prev: Option<NodeId> = None;
        while let Some(id) = a {
            let next = self.next_sibling(id);
            if self.node(id).prefix.is_none() && self.node(id).name == name {
                if let Some(p) = prev {
                    self.node_mut(p).next_sibling = next;
                } else {
                    self.node_mut(node).first_attr = next;
                }
                if next.is_none() {
                    self.node_mut(node).last_attr = prev;
                }
                if let Some(n) = next {
                    self.node_mut(n).prev_sibling = prev;
                }
                self.node_mut(id).parent = None;
                self.node_mut(id).prev_sibling = None;
                self.node_mut(id).next_sibling = None;
                return true;
            }
            prev = Some(id);
            a = next;
        }
        false
    }

    /// `xmlNodeGetContent` — concatenate descendant text/CDATA.
    #[doc(alias = "xmlNodeGetContent")]
    pub fn xml_node_get_content(&self, id: NodeId) -> String {
        match self.kind(id) {
            NodeKind::Text | NodeKind::CData | NodeKind::Comment | NodeKind::Pi | NodeKind::Attribute => {
                self.content(id).to_string()
            }
            _ => {
                let mut out = String::new();
                self.collect_text(id, &mut out);
                out
            }
        }
    }

    fn collect_text(&self, id: NodeId, out: &mut String) {
        let mut c = self.first_child(id);
        while let Some(ch) = c {
            match self.kind(ch) {
                NodeKind::Text | NodeKind::CData => out.push_str(self.content(ch)),
                NodeKind::Element => self.collect_text(ch, out),
                _ => {}
            }
            c = self.next_sibling(ch);
        }
    }

    /// `xmlNodeSetContent` — replace children with a single text node.
    #[doc(alias = "xmlNodeSetContent")]
    pub fn xml_node_set_content(&mut self, id: NodeId, content: &str) {
        match self.kind(id) {
            NodeKind::Text | NodeKind::CData | NodeKind::Comment | NodeKind::Pi | NodeKind::Attribute => {
                self.node_mut(id).content = content.to_string();
            }
            _ => {
                let mut c = self.first_child(id);
                while let Some(ch) = c {
                    let next = self.next_sibling(ch);
                    self.xml_unlink_node(ch);
                    c = next;
                }
                if !content.is_empty() {
                    let t = self.alloc(NodeKind::Text, "#text");
                    self.node_mut(t).content = content.to_string();
                    self.xml_add_child(id, t);
                }
            }
        }
    }

    /// `xmlIsBlankNode`.
    #[doc(alias = "xmlIsBlankNode")]
    pub fn xml_is_blank_node(&self, id: NodeId) -> bool {
        match self.kind(id) {
            NodeKind::Text | NodeKind::CData => self.content(id).chars().all(|c| {
                c == ' ' || c == '\t' || c == '\n' || c == '\r'
            }),
            _ => false,
        }
    }

    /// `xmlSearchNs` — walk ancestors for a prefix binding.
    #[doc(alias = "xmlSearchNs")]
    pub fn xml_search_ns(&self, node: NodeId, prefix: Option<&str>) -> Option<String> {
        if prefix == Some("xml") {
            return Some("http://www.w3.org/XML/1998/namespace".into());
        }
        if prefix == Some("xmlns") {
            return Some("http://www.w3.org/2000/xmlns/".into());
        }
        let mut cur = Some(node);
        while let Some(id) = cur {
            for (p, uri) in self.ns_defs(id) {
                if p.as_deref() == prefix {
                    return Some(uri.clone());
                }
            }
            cur = self.parent(id);
        }
        None
    }

    /// `xmlNewNs` — add a namespace declaration on an element.
    #[doc(alias = "xmlNewNs")]
    pub fn xml_new_ns(&mut self, node: NodeId, href: &str, prefix: Option<&str>) {
        self.push_ns_def(node, prefix.map(str::to_string), href.to_string());
    }

    /// `xmlSetNs`.
    #[doc(alias = "xmlSetNs")]
    pub fn xml_set_ns(&mut self, node: NodeId, href: Option<&str>, prefix: Option<&str>) {
        self.node_mut(node).ns_uri = href.map(str::to_string);
        self.node_mut(node).prefix = prefix.map(str::to_string);
    }

    /// `xmlCopyDoc` — deep copy.
    #[doc(alias = "xmlCopyDoc")]
    pub fn xml_copy_doc(&self) -> XmlDoc {
        self.clone()
    }

    pub fn qname(&self, id: NodeId) -> String {
        match self.prefix(id) {
            Some(p) => format!("{}:{}", p, self.name(id)),
            None => self.name(id).to_string(),
        }
    }

    pub fn children(&self, id: NodeId) -> NodeIter<'_> {
        NodeIter {
            doc: self,
            next: self.first_child(id),
        }
    }

    pub fn attrs(&self, id: NodeId) -> NodeIter<'_> {
        NodeIter {
            doc: self,
            next: self.first_attr(id),
        }
    }

    pub fn len(&self) -> usize {
        self.nodes.len()
    }
}

/// Sibling iterator.
pub struct NodeIter<'a> {
    doc: &'a XmlDoc,
    next: Option<NodeId>,
}

impl Iterator for NodeIter<'_> {
    type Item = NodeId;

    fn next(&mut self) -> Option<Self::Item> {
        let n = self.next?;
        self.next = self.doc.next_sibling(n);
        Some(n)
    }
}

/// `xmlFreeDoc` is `Drop`.
#[doc(alias = "xmlFreeDoc")]
pub fn xml_free_doc(_doc: XmlDoc) {}

impl XmlDoc {
    /// Deep-copy every child of `src_parent` in `src` under `dst_parent` here.
    ///
    /// Needed because an entity whose replacement text contains markup has to
    /// become NODES, not the escaped text of that markup. `<!ENTITY e
    /// "<b>x</b>">` used in content produced the literal string `<b>x</b>` in
    /// the tree, so anything reading the document for structure got garbage
    /// and DTD validation saw character data where an element was declared.
    ///
    /// Iterative, like every other traversal here: the replacement is
    /// attacker-supplied and may be arbitrarily deep.
    pub fn xml_copy_children_from(
        &mut self,
        src: &XmlDoc,
        src_parent: NodeId,
        dst_parent: NodeId,
    ) {
        // (source node, destination parent), pushed so they pop in order.
        let mut stack: Vec<(NodeId, NodeId)> = Vec::new();
        let mut c = src.last_child(src_parent);
        while let Some(x) = c {
            stack.push((x, dst_parent));
            c = src.prev_sibling(x);
        }
        while let Some((s, parent)) = stack.pop() {
            let n = src.node(s);
            let copy = self.alloc(n.kind, n.name.clone());
            {
                let d = self.node_mut(copy);
                d.prefix = n.prefix.clone();
                d.ns_uri = n.ns_uri.clone();
                d.content = n.content.clone();
                d.ns_defs = n.ns_defs.clone();
            }
            self.xml_add_child(parent, copy);
            // Carry the source's own judgement across rather than marking
            // everything: a literal space in an entity's replacement is still
            // ignorable whitespace, only a character reference written out in
            // that replacement is not.
            if src.reference_text.contains(&s) {
                self.reference_text.insert(copy);
            }
            // Attributes are a separate chain, not children.
            let mut a = src.first_attr(s);
            while let Some(x) = a {
                let an = src.node(x);
                let (nm, pre, val, uri) = (
                    an.name.clone(),
                    an.prefix.clone(),
                    an.content.clone(),
                    an.ns_uri.clone(),
                );
                let ac = self.add_attr_owned(copy, nm, pre, val);
                self.node_mut(ac).ns_uri = uri;
                a = src.next_sibling(x);
            }
            let mut k = src.last_child(s);
            while let Some(x) = k {
                stack.push((x, copy));
                k = src.prev_sibling(x);
            }
        }
    }
}