Skip to main content

f_office_xml/
lib.rs

1//! XML tree for Office Open XML parts.
2//!
3//! The tree keeps every element, attribute, namespace prefix and comment, and the markup that
4//! no format crate reads, including `mc:AlternateContent`, so that a format crate reads what it
5//! knows and passes over the rest. It is not lossless, and nothing writes it back: text takes
6//! XML's normalization of line ends, with its character and entity references resolved and its
7//! CDATA sections joined to it; attribute values take XML's attribute-value normalization; and
8//! the XML declaration and processing instructions keep only their place. Each node keeps
9//! where its markup lies in the parsed bytes ([`Document::span`]), so that an edit replaces
10//! those bytes and keeps every other byte of the part; new XML for an edit is parsed with the
11//! namespace declarations of its place ([`Document::parse_fragment`]), and two nodes compare as
12//! written or by meaning ([`Document::same_tree`]). Typed views in the
13//! format crates read from this tree. The reader refuses a `DOCTYPE` and limits the
14//! nesting depth and the number of nodes. A namespace prefix without a declaration does not
15//! stop the reader: the tree lists it ([`Document::undeclared_prefixes`]), so that a format
16//! crate can warn of it. The tables of the enumerations ([`enumeration`]) are the names that
17//! the format crates read the values of such a type through.
18
19mod compare;
20pub mod enumeration;
21mod fragment;
22#[cfg(test)]
23mod span_tests;
24mod stream;
25
26pub use compare::Equality;
27pub use fragment::Fragment;
28pub use stream::{StreamedBody, scan_body_children};
29
30use std::borrow::Cow;
31use std::collections::{HashMap, HashSet};
32use std::fmt;
33
34use quick_xml::XmlVersion;
35use quick_xml::events::{BytesDecl, BytesRef, BytesStart, Event};
36use quick_xml::name::{QName, ResolveResult};
37use quick_xml::reader::NsReader;
38
39/// Limits that protect the reader against hostile input. Start from [`Limits::default`] and set
40/// the limits that differ, so that a new limit breaks no caller.
41#[derive(Clone, Copy, Debug, PartialEq, Eq)]
42#[non_exhaustive]
43pub struct Limits {
44    /// The deepest element nesting allowed.
45    pub max_depth: usize,
46    /// The most nodes allowed in one document.
47    pub max_nodes: usize,
48}
49
50impl Default for Limits {
51    fn default() -> Self {
52        Self {
53            max_depth: 256,
54            max_nodes: 4_000_000,
55        }
56    }
57}
58
59impl Limits {
60    /// Limits tuned for memory-constrained devices such as phones and browser tabs.
61    #[must_use]
62    pub const fn mobile() -> Self {
63        Self {
64            max_depth: 128,
65            max_nodes: 500_000,
66        }
67    }
68}
69
70/// Why a part could not be read, or a node's span or a fragment not given.
71#[derive(Clone, Debug, PartialEq, Eq)]
72#[non_exhaustive]
73pub enum Error {
74    /// The XML is not well formed.
75    Syntax(String),
76    /// The part has a `DOCTYPE`, which Office Open XML never uses.
77    DocType,
78    /// The nesting is deeper than [`Limits::max_depth`].
79    TooDeep,
80    /// The part has more nodes than [`Limits::max_nodes`].
81    TooManyNodes,
82    /// The part has no root element.
83    NoRoot,
84    /// The part has more bytes than a span can count, `u32::MAX`.
85    TooLarge,
86    /// The part is not in UTF-8, as its byte order mark or its XML declaration says: the
87    /// encoding that it names. Its spans are not given ([`Document::span`]), because bytes in
88    /// UTF-8 in their place would garble it.
89    NotUtf8(String),
90    /// The document has no such node.
91    NoSuchNode,
92    /// A fragment uses a namespace prefix that neither it nor the declarations in scope
93    /// declare ([`Document::parse_fragment`]).
94    UndeclaredPrefix(String),
95}
96
97impl fmt::Display for Error {
98    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
99        match self {
100            Self::Syntax(message) => write!(f, "malformed XML: {message}"),
101            Self::DocType => f.write_str("XML with a DOCTYPE is not allowed"),
102            Self::TooDeep => f.write_str("XML nesting is too deep"),
103            Self::TooManyNodes => f.write_str("XML has too many nodes"),
104            Self::NoRoot => f.write_str("XML has no root element"),
105            Self::TooLarge => f.write_str("XML part is larger than 4 GiB"),
106            Self::NotUtf8(encoding) => write!(f, "XML part is in {encoding}, not in UTF-8"),
107            Self::NoSuchNode => f.write_str("XML document has no such node"),
108            Self::UndeclaredPrefix(prefix) => {
109                write!(
110                    f,
111                    "XML fragment uses the prefix {prefix} without a declaration"
112                )
113            }
114        }
115    }
116}
117
118impl std::error::Error for Error {}
119
120/// A node in a [`Document`].
121#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
122pub struct NodeId(u32);
123
124/// A namespace URI interned in a [`Document`].
125#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
126pub struct NamespaceId(u32);
127
128/// Byte range into [`Document::strings`].
129#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
130struct StrSpan {
131    start: u32,
132    len: u32,
133}
134
135impl StrSpan {
136    const EMPTY: Self = Self { start: 0, len: 0 };
137
138    fn slice(self, buf: &str) -> &str {
139        let start = self.start as usize;
140        let end = start.saturating_add(self.len as usize);
141        buf.get(start..end).unwrap_or("")
142    }
143}
144
145/// Contiguous element range into an arena `Vec` (`children_pool` or `attrs`).
146#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
147struct SliceRange {
148    start: u32,
149    len: u32,
150}
151
152impl SliceRange {
153    const EMPTY: Self = Self { start: 0, len: 0 };
154
155    fn bounds(self) -> std::ops::Range<usize> {
156        let start = self.start as usize;
157        start..start.saturating_add(self.len as usize)
158    }
159}
160
161/// An element or attribute name borrowed from a [`Document`]'s string arena.
162#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
163pub struct Name<'a> {
164    /// The prefix as written in the part, if any.
165    pub prefix: Option<&'a str>,
166    /// The local name.
167    pub local: &'a str,
168    /// The namespace that the prefix resolves to, if any: `None` for a name without a prefix
169    /// outside a default namespace, and for a prefix without a declaration
170    /// ([`Document::undeclared_prefixes`]).
171    pub namespace: Option<NamespaceId>,
172}
173
174/// One attribute of an element borrowed from a [`Document`]'s arena.
175#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
176pub struct Attribute<'a> {
177    /// The attribute name.
178    pub name: Name<'a>,
179    /// The value, with entity references resolved.
180    pub value: &'a str,
181}
182
183/// Zero-copy view of an element's attributes stored contiguously in a [`Document`]'s arena.
184#[derive(Clone, Copy, Debug)]
185pub struct Attrs<'a> {
186    strings: &'a str,
187    attrs: &'a [ArenaAttr],
188}
189
190impl<'a> Attrs<'a> {
191    /// Returns the number of attributes on this element.
192    #[must_use]
193    pub const fn len(&self) -> usize {
194        self.attrs.len()
195    }
196
197    /// Returns `true` when this element has no attributes.
198    #[must_use]
199    pub const fn is_empty(&self) -> bool {
200        self.attrs.is_empty()
201    }
202
203    /// Returns an iterator over the element's attributes in document order.
204    #[must_use]
205    pub const fn iter(&self) -> AttrsIter<'a> {
206        AttrsIter {
207            strings: self.strings,
208            attrs: self.attrs,
209        }
210    }
211
212    /// Returns the attribute at `index`, or `None` if out of bounds.
213    #[must_use]
214    pub fn get(&self, index: usize) -> Option<Attribute<'a>> {
215        self.attrs.get(index).map(|attr| attr.view(self.strings))
216    }
217}
218
219/// Iterator over an element's attributes in document order ([`Attrs::iter`]).
220#[derive(Clone, Debug)]
221pub struct AttrsIter<'a> {
222    strings: &'a str,
223    attrs: &'a [ArenaAttr],
224}
225
226impl<'a> Iterator for AttrsIter<'a> {
227    type Item = Attribute<'a>;
228
229    fn next(&mut self) -> Option<Self::Item> {
230        let (first, rest) = self.attrs.split_first()?;
231        self.attrs = rest;
232        Some(first.view(self.strings))
233    }
234
235    fn size_hint(&self) -> (usize, Option<usize>) {
236        (self.attrs.len(), Some(self.attrs.len()))
237    }
238}
239
240impl DoubleEndedIterator for AttrsIter<'_> {
241    fn next_back(&mut self) -> Option<Self::Item> {
242        let (last, rest) = self.attrs.split_last()?;
243        self.attrs = rest;
244        Some(last.view(self.strings))
245    }
246}
247
248impl ExactSizeIterator for AttrsIter<'_> {}
249
250impl<'a> IntoIterator for Attrs<'a> {
251    type Item = Attribute<'a>;
252    type IntoIter = AttrsIter<'a>;
253
254    fn into_iter(self) -> Self::IntoIter {
255        self.iter()
256    }
257}
258
259impl<'a> IntoIterator for &Attrs<'a> {
260    type Item = Attribute<'a>;
261    type IntoIter = AttrsIter<'a>;
262
263    fn into_iter(self) -> Self::IntoIter {
264        self.iter()
265    }
266}
267
268impl PartialEq for Attrs<'_> {
269    fn eq(&self, other: &Self) -> bool {
270        self.len() == other.len() && self.iter().eq(other.iter())
271    }
272}
273
274impl Eq for Attrs<'_> {}
275
276/// An element with its attributes, borrowed zero-copy from a [`Document`]'s arena.
277#[derive(Clone, Copy, Debug, PartialEq, Eq)]
278pub struct Element<'a> {
279    /// The element name.
280    pub name: Name<'a>,
281    /// The attributes in document order, including namespace declarations.
282    pub attributes: Attrs<'a>,
283}
284
285/// What a node holds, borrowed zero-copy from a [`Document`]'s arena.
286#[derive(Clone, Copy, Debug, PartialEq, Eq)]
287pub enum NodeKind<'a> {
288    /// An element.
289    Element(Element<'a>),
290    /// Character data, with entity references resolved.
291    Text(&'a str),
292    /// A comment, a processing instruction or the XML declaration, kept as written.
293    Other(&'a str),
294}
295
296/// Compact flat attribute entry stored in [`Document::attrs`].
297#[derive(Clone, Copy, Debug)]
298struct ArenaAttr {
299    prefix: Option<StrSpan>,
300    local: StrSpan,
301    namespace: Option<NamespaceId>,
302    value: StrSpan,
303}
304
305impl ArenaAttr {
306    fn view<'a>(&self, strings: &'a str) -> Attribute<'a> {
307        Attribute {
308            name: Name {
309                prefix: self.prefix.map(|span| span.slice(strings)),
310                local: self.local.slice(strings),
311                namespace: self.namespace,
312            },
313            value: self.value.slice(strings),
314        }
315    }
316}
317
318/// Compact flat node payload stored in [`Document::nodes`].
319#[derive(Clone, Copy, Debug)]
320enum ArenaKind {
321    Element {
322        prefix: Option<StrSpan>,
323        local: StrSpan,
324        namespace: Option<NamespaceId>,
325        attrs: SliceRange,
326    },
327    Text(StrSpan),
328    Other(StrSpan),
329}
330
331#[derive(Clone, Copy, Debug)]
332struct Node {
333    kind: ArenaKind,
334    children: SliceRange,
335    /// The namespace declarations in scope at an element: those of the nearest element, the
336    /// element itself or an ancestor, that declares a namespace. `None` for other nodes and for
337    /// an element with no declaration in scope.
338    scope: Option<ScopeId>,
339    /// Where the node's markup lies in the parsed bytes ([`Document::span`]).
340    span: Span,
341}
342
343/// Where a node's markup lies in the parsed bytes: the offset of its first byte and the offset
344/// after its last.
345#[derive(Clone, Copy, Debug, Default)]
346struct Span {
347    start: u32,
348    end: u32,
349}
350
351/// The place of a [`Scope`] in the document's list of them.
352#[derive(Clone, Copy, Debug)]
353struct ScopeId(u32);
354
355/// The namespace declarations of one element, with the scope of the nearest ancestor that
356/// declares a namespace: the prefixes in scope at the element and at each descendant that
357/// declares none.
358#[derive(Clone, Debug)]
359struct Scope {
360    /// The scope outside this one, if any.
361    outer: Option<ScopeId>,
362    /// Each prefix that the element declares, `""` for the default namespace, with the namespace
363    /// that it binds, after the aliases of the parse.
364    bindings: Vec<(String, NamespaceId)>,
365}
366
367/// The byte order mark of UTF-8.
368const UTF8_MARK: [u8; 3] = [0xEF, 0xBB, 0xBF];
369
370/// The namespace that the prefix `xml` is bound to by definition (Namespaces in XML 1.0, 3).
371const XML_NAMESPACE: &str = "http://www.w3.org/XML/1998/namespace";
372
373/// A parsed XML part stored in flat contiguous arenas (nodes, child indices, attributes, and a
374/// single UTF-8 string buffer with interned tag and attribute names).
375#[derive(Clone, Debug)]
376pub struct Document {
377    nodes: Vec<Node>,
378    children_pool: Vec<NodeId>,
379    attrs: Vec<ArenaAttr>,
380    strings: String,
381    top: Vec<NodeId>,
382    namespaces: Vec<String>,
383    scopes: Vec<Scope>,
384    undeclared_prefixes: Vec<String>,
385    /// The encoding that the part's byte order mark or XML declaration names when it is not
386    /// UTF-8, and `None` for a part in UTF-8.
387    encoding: Option<String>,
388}
389
390impl Document {
391    /// Parses a part.
392    ///
393    /// # Errors
394    ///
395    /// Returns an error when the XML is malformed, has a `DOCTYPE`, or breaks a limit.
396    pub fn parse(bytes: &[u8], limits: &Limits) -> Result<Self, Error> {
397        Builder::new(*limits, &[]).run(bytes)
398    }
399
400    /// Parses a part and resolves each namespace URI on the left of an alias pair to the URI
401    /// on the right, so that two spellings of one vocabulary read the same. The namespace
402    /// declarations stay in the element attributes as written.
403    ///
404    /// # Errors
405    ///
406    /// Returns an error when the XML is malformed, has a `DOCTYPE`, or breaks a limit.
407    pub fn parse_with_aliases(
408        bytes: &[u8],
409        limits: &Limits,
410        aliases: &[(&str, &str)],
411    ) -> Result<Self, Error> {
412        Builder::new(*limits, aliases).run(bytes)
413    }
414
415    /// Returns the root element.
416    ///
417    /// # Errors
418    ///
419    /// Returns [`Error::NoRoot`] when the document has no element at the top level.
420    pub fn root(&self) -> Result<NodeId, Error> {
421        self.top
422            .iter()
423            .copied()
424            .find(|id| self.element(*id).is_some())
425            .ok_or(Error::NoRoot)
426    }
427
428    /// Returns what a node holds.
429    #[must_use]
430    pub fn kind(&self, id: NodeId) -> Option<NodeKind<'_>> {
431        let node = self.node(id)?;
432        Some(match node.kind {
433            ArenaKind::Element {
434                prefix,
435                local,
436                namespace,
437                attrs,
438            } => NodeKind::Element(Element {
439                name: Name {
440                    prefix: prefix.map(|span| span.slice(&self.strings)),
441                    local: local.slice(&self.strings),
442                    namespace,
443                },
444                attributes: Attrs {
445                    strings: &self.strings,
446                    attrs: self.attrs.get(attrs.bounds()).unwrap_or(&[]),
447                },
448            }),
449            ArenaKind::Text(span) => NodeKind::Text(span.slice(&self.strings)),
450            ArenaKind::Other(span) => NodeKind::Other(span.slice(&self.strings)),
451        })
452    }
453
454    /// Returns the element at a node, or `None` for other nodes.
455    #[must_use]
456    pub fn element(&self, id: NodeId) -> Option<Element<'_>> {
457        match self.kind(id)? {
458            NodeKind::Element(element) => Some(element),
459            NodeKind::Text(_) | NodeKind::Other(_) => None,
460        }
461    }
462
463    /// Returns the text at a node, or `None` for other nodes.
464    #[must_use]
465    pub fn text(&self, id: NodeId) -> Option<&str> {
466        match self.node(id)?.kind {
467            ArenaKind::Text(span) => Some(span.slice(&self.strings)),
468            ArenaKind::Element { .. } | ArenaKind::Other(_) => None,
469        }
470    }
471
472    /// Returns the children of a node in document order.
473    #[must_use]
474    pub fn children(&self, id: NodeId) -> &[NodeId] {
475        self.node(id)
476            .and_then(|node| self.children_pool.get(node.children.bounds()))
477            .unwrap_or(&[])
478    }
479
480    /// Returns the child elements of a node in document order.
481    pub fn child_elements(&self, id: NodeId) -> impl Iterator<Item = NodeId> + '_ {
482        self.children(id)
483            .iter()
484            .copied()
485            .filter(|child| self.element(*child).is_some())
486    }
487
488    /// Replaces the children of a node, in document order. The new children are nodes of this
489    /// document, so that an edit can drop, keep and move nodes; a node that no parent lists any
490    /// more drops out of the tree. Nothing changes for a node that the document lacks.
491    pub fn set_children(&mut self, id: NodeId, children: Vec<NodeId>) {
492        if self.nodes.get(id.0 as usize).is_none() {
493            return;
494        }
495        let range = if children.is_empty() {
496            SliceRange::EMPTY
497        } else {
498            let start = u32::try_from(self.children_pool.len()).unwrap_or(u32::MAX);
499            let len = u32::try_from(children.len()).unwrap_or(u32::MAX);
500            self.children_pool.extend(children);
501            SliceRange { start, len }
502        };
503        if let Some(node) = self.nodes.get_mut(id.0 as usize) {
504            node.children = range;
505        }
506    }
507
508    /// Sets an attribute of an element, so that an edit can leave a note on it: the value of
509    /// an attribute with this namespace URI and local name changes, or the attribute is added.
510    /// Pass `None` as the namespace for an unprefixed attribute. Nothing changes for a node that
511    /// is no element.
512    pub fn set_attribute(&mut self, id: NodeId, namespace: Option<&str>, local: &str, value: &str) {
513        let namespace = namespace.map(|uri| {
514            let index = self.namespaces.iter().position(|known| known == uri);
515            NamespaceId(
516                u32::try_from(index.unwrap_or_else(|| {
517                    self.namespaces.push(uri.to_owned());
518                    self.namespaces.len() - 1
519                }))
520                .unwrap_or(u32::MAX),
521            )
522        });
523        let Some(ArenaKind::Element { attrs, .. }) =
524            self.nodes.get(id.0 as usize).map(|node| node.kind)
525        else {
526            return;
527        };
528        let bounds = attrs.bounds();
529        let existing_index = self.attrs.get(bounds.clone()).and_then(|slice| {
530            slice
531                .iter()
532                .position(|attr| {
533                    attr.namespace == namespace && attr.local.slice(&self.strings) == local
534                })
535                .map(|offset| bounds.start + offset)
536        });
537        let value_span = push_str_arena(&mut self.strings, value);
538        if let Some(idx) = existing_index {
539            if let Some(attr) = self.attrs.get_mut(idx) {
540                attr.value = value_span;
541            }
542            return;
543        }
544        let local_span = push_str_arena(&mut self.strings, local);
545        let new_start = u32::try_from(self.attrs.len()).unwrap_or(u32::MAX);
546        let old_len = bounds.len();
547        self.attrs.reserve(old_len + 1);
548        for idx in bounds {
549            if let Some(&copied) = self.attrs.get(idx) {
550                self.attrs.push(copied);
551            }
552        }
553        self.attrs.push(ArenaAttr {
554            prefix: None,
555            local: local_span,
556            namespace,
557            value: value_span,
558        });
559        let new_range = SliceRange {
560            start: new_start,
561            len: u32::try_from(old_len + 1).unwrap_or(u32::MAX),
562        };
563        if let Some(Node {
564            kind: ArenaKind::Element { attrs, .. },
565            ..
566        }) = self.nodes.get_mut(id.0 as usize)
567        {
568            *attrs = new_range;
569        }
570    }
571
572    /// Returns the namespace prefixes that the part uses on an element or an attribute without
573    /// a declaration in scope, which XML's namespaces forbid, each once in the order of its
574    /// first use. `xml` and `xmlns` need no declaration. Such a name keeps its prefix and has
575    /// no namespace: an element of it is none that [`Document::is`] or [`Document::child`]
576    /// finds, and an attribute of it reads as an attribute without a prefix.
577    #[must_use]
578    pub fn undeclared_prefixes(&self) -> &[String] {
579        &self.undeclared_prefixes
580    }
581
582    /// Returns the namespace that the prefix `prefix` (`""` for the default namespace) is
583    /// bound to at the element `id`: by the nearest declaration of the element or of an
584    /// ancestor, as the part was parsed, after the aliases of [`Document::parse_with_aliases`].
585    /// The prefix `xml` is bound as XML defines it. `None` for a prefix that no declaration in
586    /// scope binds, for a declaration of the empty name, and for a node that is no element.
587    /// A format crate reads a prefix in an attribute's value through it, such as the namespaces
588    /// that a choice of alternate content requires.
589    #[must_use]
590    pub fn prefix_namespace(&self, id: NodeId, prefix: &str) -> Option<&str> {
591        self.element(id)?;
592        if prefix == "xml" {
593            return Some(XML_NAMESPACE);
594        }
595        let mut scope = self.node(id)?.scope;
596        while let Some(ScopeId(index)) = scope {
597            let found = self.scopes.get(index as usize)?;
598            if let Some((_, namespace)) = found.bindings.iter().find(|(name, _)| name == prefix) {
599                let uri = self.namespace_uri(*namespace);
600                return (!uri.is_empty()).then_some(uri);
601            }
602            scope = found.outer;
603        }
604        None
605    }
606
607    /// Returns where a node's markup lies in the bytes that were parsed, as offsets into those
608    /// bytes, before any normalization: an element from the `<` of its start tag to the byte
609    /// after the `>` of its end tag or of its empty tag; a text node from its first byte to the
610    /// byte after its last, with the character and entity references and the CDATA sections
611    /// that it joins; and a comment, a processing instruction or the XML declaration as
612    /// written. A span keeps the bytes as parsed: [`Document::set_children`] does not change
613    /// it. Replacing the bytes of a span replaces the node in the part, so that an edit keeps
614    /// every other byte as it was.
615    ///
616    /// # Errors
617    ///
618    /// Returns [`Error::NotUtf8`] when the part is not in UTF-8, and [`Error::NoSuchNode`] for
619    /// a node that the document lacks.
620    pub fn span(&self, id: NodeId) -> Result<std::ops::Range<usize>, Error> {
621        if let Some(encoding) = &self.encoding {
622            return Err(Error::NotUtf8(encoding.clone()));
623        }
624        let span = self.node(id).ok_or(Error::NoSuchNode)?.span;
625        Ok(span.start as usize..span.end as usize)
626    }
627
628    /// Returns the namespace declarations in scope at the element `id`, its own among them:
629    /// each prefix (`""` for the default namespace) with the URI that it binds after the
630    /// aliases of the parse, from the nearest declaration of the prefix only, the element's
631    /// own first and then outward. Empty for a node that is no element. A fragment that takes
632    /// the place of the element's content, or of a child, is parsed with them
633    /// ([`Document::parse_fragment`]).
634    #[must_use]
635    pub fn namespaces_in_scope(&self, id: NodeId) -> Vec<(String, String)> {
636        let mut found: Vec<(String, String)> = Vec::new();
637        if self.element(id).is_none() {
638            return found;
639        }
640        let mut scope = self.node(id).and_then(|node| node.scope);
641        while let Some(ScopeId(index)) = scope {
642            let Some(outer) = self.scopes.get(index as usize) else {
643                break;
644            };
645            for (prefix, namespace) in &outer.bindings {
646                if found.iter().all(|(known, _)| known != prefix) {
647                    found.push((prefix.clone(), self.namespace_uri(*namespace).to_owned()));
648                }
649            }
650            scope = outer.outer;
651        }
652        found
653    }
654
655    /// Returns the URI of an interned namespace.
656    #[must_use]
657    pub fn namespace_uri(&self, id: NamespaceId) -> &str {
658        self.namespaces
659            .get(id.0 as usize)
660            .map_or("", String::as_str)
661    }
662
663    /// Tells whether a node is an element with this namespace URI and local name.
664    #[must_use]
665    pub fn is(&self, id: NodeId, namespace: &str, local: &str) -> bool {
666        self.element(id)
667            .is_some_and(|element| self.name_is(&element.name, Some(namespace), local))
668    }
669
670    /// Returns the first child element with this namespace URI and local name.
671    #[must_use]
672    pub fn child(&self, id: NodeId, namespace: &str, local: &str) -> Option<NodeId> {
673        self.child_elements(id)
674            .find(|child| self.is(*child, namespace, local))
675    }
676
677    /// Returns an attribute value. Pass `None` as the namespace for an unprefixed attribute.
678    #[must_use]
679    pub fn attribute(&self, id: NodeId, namespace: Option<&str>, local: &str) -> Option<&str> {
680        self.element(id)?
681            .attributes
682            .iter()
683            .find(|attribute| self.name_is(&attribute.name, namespace, local))
684            .map(|attribute| attribute.value)
685    }
686
687    /// Returns all text below a node, in document order.
688    #[must_use]
689    pub fn text_content(&self, id: NodeId) -> String {
690        let mut out = String::new();
691        self.collect_text(id, &mut out);
692        out
693    }
694
695    fn collect_text(&self, id: NodeId, out: &mut String) {
696        if let Some(text) = self.text(id) {
697            out.push_str(text);
698        }
699        for child in self.children(id) {
700            self.collect_text(*child, out);
701        }
702    }
703
704    fn name_is(&self, name: &Name<'_>, namespace: Option<&str>, local: &str) -> bool {
705        let uri = name.namespace.map(|ns| self.namespace_uri(ns));
706        name.local == local && uri == namespace
707    }
708
709    fn node(&self, id: NodeId) -> Option<&Node> {
710        self.nodes.get(id.0 as usize)
711    }
712}
713
714/// Appends `text` to `strings` and returns its [`StrSpan`].
715fn push_str_arena(strings: &mut String, text: &str) -> StrSpan {
716    if text.is_empty() {
717        return StrSpan::EMPTY;
718    }
719    let start = u32::try_from(strings.len()).unwrap_or(u32::MAX);
720    let len = u32::try_from(text.len()).unwrap_or(u32::MAX);
721    strings.push_str(text);
722    StrSpan { start, len }
723}
724
725struct Builder {
726    limits: Limits,
727    nodes: Vec<Node>,
728    children_pool: Vec<NodeId>,
729    /// Open parent child lists (one per nesting level, reused across sibling subtrees).
730    pending_children: Vec<Vec<NodeId>>,
731    attrs: Vec<ArenaAttr>,
732    strings: String,
733    /// Interned XML tag/attribute prefixes and local names stored once in `strings`.
734    interned_names: HashMap<String, StrSpan>,
735    top: Vec<NodeId>,
736    stack: Vec<NodeId>,
737    /// The scope of each open element, in the order of `stack`.
738    scope_stack: Vec<Option<ScopeId>>,
739    scopes: Vec<Scope>,
740    namespaces: Vec<String>,
741    namespace_ids: HashMap<String, NamespaceId>,
742    aliases: HashMap<String, String>,
743    undeclared_prefixes: Vec<String>,
744    undeclared_seen: HashSet<String>,
745    /// The number of bytes before the bytes whose offsets the spans count: those of the
746    /// container of a fragment ([`Document::parse_fragment`]), else 0.
747    offset: u64,
748    /// Constant base offset added to every node span when parsing a slice of a larger part.
749    base_offset: u64,
750    /// The bytes of a byte order mark of UTF-8 at the start, which the reader skips and leaves
751    /// out of its positions.
752    skipped: u64,
753    /// The encoding that the part names when it is not UTF-8.
754    encoding: Option<String>,
755}
756
757impl Builder {
758    fn new(limits: Limits, aliases: &[(&str, &str)]) -> Self {
759        Self {
760            limits,
761            nodes: Vec::new(),
762            children_pool: Vec::new(),
763            pending_children: Vec::new(),
764            attrs: Vec::new(),
765            strings: String::new(),
766            interned_names: HashMap::new(),
767            top: Vec::new(),
768            stack: Vec::new(),
769            scope_stack: Vec::new(),
770            scopes: Vec::new(),
771            namespaces: Vec::new(),
772            namespace_ids: HashMap::new(),
773            aliases: aliases
774                .iter()
775                .map(|(from, to)| ((*from).to_owned(), (*to).to_owned()))
776                .collect(),
777            undeclared_prefixes: Vec::new(),
778            undeclared_seen: HashSet::new(),
779            offset: 0,
780            base_offset: 0,
781            skipped: 0,
782            encoding: None,
783        }
784    }
785
786    fn intern_name(&mut self, name: &str) -> StrSpan {
787        if name.is_empty() {
788            return StrSpan::EMPTY;
789        }
790        if let Some(&span) = self.interned_names.get(name) {
791            return span;
792        }
793        let span = push_str_arena(&mut self.strings, name);
794        self.interned_names.insert(name.to_owned(), span);
795        span
796    }
797
798    fn run(mut self, bytes: &[u8]) -> Result<Document, Error> {
799        u32::try_from(
800            u64::try_from(bytes.len())
801                .unwrap_or(u64::MAX)
802                .saturating_add(self.base_offset),
803        )
804        .map_err(|_| Error::TooLarge)?;
805        // A byte order mark of UTF-16 names the encoding before any declaration.
806        if bytes.starts_with(&[0xFF, 0xFE]) || bytes.starts_with(&[0xFE, 0xFF]) {
807            self.encoding = Some("UTF-16".to_owned());
808        }
809        if bytes.starts_with(&UTF8_MARK) {
810            self.skipped = UTF8_MARK.len() as u64;
811        }
812        let mut reader = NsReader::from_reader(bytes);
813        reader.config_mut().check_end_names = true;
814        let est_nodes = (bytes.len() / 64).min(self.limits.max_nodes);
815        self.nodes.reserve(est_nodes);
816        self.children_pool.reserve(est_nodes);
817        self.attrs.reserve(est_nodes);
818        self.strings.reserve(bytes.len() / 2);
819        let mut buf = Vec::new();
820        loop {
821            buf.clear();
822            let start = self.position(&reader)?;
823            let (resolved, event) = reader
824                .read_resolved_event_into(&mut buf)
825                .map_err(|error| Error::Syntax(error.to_string()))?;
826            let namespace = self.resolve(&resolved);
827            let span = Span {
828                start,
829                end: self.position(&reader)?,
830            };
831            match event {
832                Event::Eof => break,
833                Event::Start(tag) => {
834                    let id = self.start_element(&reader, &tag, namespace, span)?;
835                    self.open(id)?;
836                }
837                Event::Empty(tag) => {
838                    self.start_element(&reader, &tag, namespace, span)?;
839                }
840                Event::End(_) => {
841                    self.close(span.end);
842                }
843                other => self.leaf(other, span)?,
844            }
845        }
846        if self.stack.is_empty() {
847            Ok(Document {
848                nodes: self.nodes,
849                children_pool: self.children_pool,
850                attrs: self.attrs,
851                strings: self.strings,
852                top: self.top,
853                namespaces: self.namespaces,
854                scopes: self.scopes,
855                undeclared_prefixes: self.undeclared_prefixes,
856                encoding: self.encoding,
857            })
858        } else {
859            Err(Error::Syntax("unclosed element".to_owned()))
860        }
861    }
862
863    /// The offset that the reader has reached, counted from the bytes after [`Self::offset`],
864    /// shifted by [`Self::base_offset`].
865    fn position(&self, reader: &NsReader<&[u8]>) -> Result<u32, Error> {
866        let position = (reader.buffer_position() + self.skipped)
867            .saturating_sub(self.offset)
868            .saturating_add(self.base_offset);
869        u32::try_from(position).map_err(|_| Error::TooLarge)
870    }
871
872    fn leaf(&mut self, event: Event<'_>, span: Span) -> Result<(), Error> {
873        match event {
874            Event::Text(text) => self.add_text(&text.xml10_content(), span),
875            Event::CData(data) => self.add_text(&data.into_inner(), span),
876            Event::GeneralRef(reference) => self.add_text(&resolve_reference(&reference)?, span),
877            Event::DocType(_) => Err(Error::DocType),
878            Event::Comment(comment) => {
879                let raw = comment.into_inner();
880                let start = u32::try_from(self.strings.len()).unwrap_or(u32::MAX);
881                self.strings.push_str("<!--");
882                self.strings.push_str(&raw);
883                self.strings.push_str("-->");
884                let len = u32::try_from(self.strings.len()).unwrap_or(u32::MAX) - start;
885                self.add(ArenaKind::Other(StrSpan { start, len }), span)
886                    .map(|_| ())
887            }
888            Event::Decl(declaration) => {
889                if self.encoding.is_none() {
890                    self.encoding = declared_encoding(&declaration);
891                }
892                self.add(ArenaKind::Other(StrSpan::EMPTY), span).map(|_| ())
893            }
894            Event::PI(_) => self.add(ArenaKind::Other(StrSpan::EMPTY), span).map(|_| ()),
895            Event::Start(_) | Event::Empty(_) | Event::End(_) | Event::Eof => Ok(()),
896        }
897    }
898
899    fn resolve(&mut self, resolved: &ResolveResult<'_>) -> Option<NamespaceId> {
900        match resolved {
901            ResolveResult::Bound(namespace) => Some(self.intern(namespace.as_ref())),
902            ResolveResult::Unbound => None,
903            ResolveResult::Unknown(prefix) => {
904                if self.undeclared_seen.insert(prefix.clone()) {
905                    self.undeclared_prefixes.push(prefix.clone());
906                }
907                None
908            }
909        }
910    }
911
912    fn intern(&mut self, uri: &str) -> NamespaceId {
913        let uri = self.aliases.get(uri).map_or(uri, String::as_str);
914        if let Some(id) = self.namespace_ids.get(uri) {
915            return *id;
916        }
917        let id = NamespaceId(u32::try_from(self.namespaces.len()).unwrap_or(u32::MAX));
918        let owned = uri.to_owned();
919        self.namespaces.push(owned.clone());
920        self.namespace_ids.insert(owned, id);
921        id
922    }
923
924    fn start_element(
925        &mut self,
926        reader: &NsReader<&[u8]>,
927        start: &BytesStart<'_>,
928        namespace: Option<NamespaceId>,
929        span: Span,
930    ) -> Result<NodeId, Error> {
931        let (prefix, local) = self.split_name(start.name());
932        let attr_start = u32::try_from(self.attrs.len()).unwrap_or(u32::MAX);
933        for attribute in start.attributes() {
934            let attribute = attribute.map_err(|error| Error::Syntax(error.to_string()))?;
935            let (resolved, _) = reader.resolver().resolve_attribute(attribute.key);
936            let attr_ns = self.resolve(&resolved);
937            let (attr_prefix, attr_local) = self.split_name(attribute.key);
938            let value = attribute
939                .normalized_value(XmlVersion::Implicit1_0)
940                .map_err(|error| Error::Syntax(error.to_string()))?;
941            let value_span = push_str_arena(&mut self.strings, &value);
942            self.attrs.push(ArenaAttr {
943                prefix: attr_prefix,
944                local: attr_local,
945                namespace: attr_ns,
946                value: value_span,
947            });
948        }
949        let attr_len = u32::try_from(self.attrs.len())
950            .unwrap_or(u32::MAX)
951            .saturating_sub(attr_start);
952        let attrs = SliceRange {
953            start: attr_start,
954            len: attr_len,
955        };
956        let scope = self.scope_of(attrs)?;
957        let id = self.add(
958            ArenaKind::Element {
959                prefix,
960                local,
961                namespace,
962                attrs,
963            },
964            span,
965        )?;
966        if let Some(node) = self.nodes.get_mut(id.0 as usize) {
967            node.scope = scope;
968        }
969        Ok(id)
970    }
971
972    fn split_name(&mut self, name: QName<'_>) -> (Option<StrSpan>, StrSpan) {
973        let local = self.intern_name(name.local_name().as_ref());
974        let prefix = name
975            .prefix()
976            .map(|prefix| self.intern_name(prefix.as_ref()));
977        (prefix, local)
978    }
979
980    /// The scope of an element with the attributes `attrs`: a new scope when they declare
981    /// a namespace, else the scope of the open element.
982    fn scope_of(&mut self, attrs: SliceRange) -> Result<Option<ScopeId>, Error> {
983        let outer = self.scope_stack.last().copied().flatten();
984        let declared: Vec<(String, String)> = self
985            .attrs
986            .get(attrs.bounds())
987            .unwrap_or(&[])
988            .iter()
989            .filter_map(|attribute| {
990                let prefix_str = attribute.prefix.map(|span| span.slice(&self.strings));
991                let local_str = attribute.local.slice(&self.strings);
992                let binding_prefix = match prefix_str {
993                    Some("xmlns") => local_str.to_owned(),
994                    None if local_str == "xmlns" => String::new(),
995                    _ => return None,
996                };
997                Some((
998                    binding_prefix,
999                    attribute.value.slice(&self.strings).to_owned(),
1000                ))
1001            })
1002            .collect();
1003        if declared.is_empty() {
1004            return Ok(outer);
1005        }
1006        let bindings = declared
1007            .into_iter()
1008            .map(|(prefix, uri)| (prefix, self.intern(&uri)))
1009            .collect();
1010        let id = ScopeId(u32::try_from(self.scopes.len()).map_err(|_| Error::TooManyNodes)?);
1011        self.scopes.push(Scope { outer, bindings });
1012        Ok(Some(id))
1013    }
1014
1015    /// Adds text, joined to a text node just before it, whose span then reaches to the end of
1016    /// `span`.
1017    fn add_text(&mut self, text: &str, span: Span) -> Result<(), Error> {
1018        let last = self.siblings().last().copied();
1019        if let Some(last_id) = last
1020            && let Some(Node {
1021                kind: ArenaKind::Text(prev_span),
1022                ..
1023            }) = self.nodes.get(last_id.0 as usize).copied()
1024        {
1025            let prev_end = (prev_span.start as usize).saturating_add(prev_span.len as usize);
1026            let new_span = if prev_end == self.strings.len() {
1027                self.strings.push_str(text);
1028                StrSpan {
1029                    start: prev_span.start,
1030                    len: prev_span
1031                        .len
1032                        .saturating_add(u32::try_from(text.len()).unwrap_or(u32::MAX)),
1033                }
1034            } else {
1035                let prev_text = prev_span.slice(&self.strings).to_owned();
1036                let start = u32::try_from(self.strings.len()).unwrap_or(u32::MAX);
1037                self.strings.push_str(&prev_text);
1038                self.strings.push_str(text);
1039                let len = u32::try_from(self.strings.len()).unwrap_or(u32::MAX) - start;
1040                StrSpan { start, len }
1041            };
1042            if let Some(node) = self.nodes.get_mut(last_id.0 as usize) {
1043                node.kind = ArenaKind::Text(new_span);
1044                node.span.end = span.end;
1045            }
1046            return Ok(());
1047        }
1048        let text_span = push_str_arena(&mut self.strings, text);
1049        self.add(ArenaKind::Text(text_span), span).map(|_| ())
1050    }
1051
1052    fn siblings(&self) -> &[NodeId] {
1053        let depth = self.stack.len();
1054        if depth == 0 {
1055            &self.top
1056        } else {
1057            self.pending_children
1058                .get(depth - 1)
1059                .map_or(&[], Vec::as_slice)
1060        }
1061    }
1062
1063    fn add(&mut self, kind: ArenaKind, span: Span) -> Result<NodeId, Error> {
1064        if self.nodes.len() >= self.limits.max_nodes {
1065            return Err(Error::TooManyNodes);
1066        }
1067        let id = NodeId(u32::try_from(self.nodes.len()).map_err(|_| Error::TooManyNodes)?);
1068        self.nodes.push(Node {
1069            kind,
1070            children: SliceRange::EMPTY,
1071            scope: None,
1072            span,
1073        });
1074        let depth = self.stack.len();
1075        if depth == 0 {
1076            self.top.push(id);
1077        } else if let Some(slot) = self.pending_children.get_mut(depth - 1) {
1078            slot.push(id);
1079        }
1080        Ok(id)
1081    }
1082
1083    fn open(&mut self, id: NodeId) -> Result<(), Error> {
1084        if self.stack.len() >= self.limits.max_depth {
1085            return Err(Error::TooDeep);
1086        }
1087        let depth = self.stack.len();
1088        if depth == self.pending_children.len() {
1089            self.pending_children.push(Vec::new());
1090        } else if let Some(slot) = self.pending_children.get_mut(depth) {
1091            slot.clear();
1092        }
1093        self.stack.push(id);
1094        let scope = self.nodes.get(id.0 as usize).and_then(|node| node.scope);
1095        self.scope_stack.push(scope);
1096        Ok(())
1097    }
1098
1099    fn close(&mut self, end: u32) {
1100        let Some(parent_id) = self.stack.pop() else {
1101            return;
1102        };
1103        let depth = self.stack.len();
1104        let range = if let Some(slot) = self.pending_children.get_mut(depth) {
1105            if slot.is_empty() {
1106                SliceRange::EMPTY
1107            } else {
1108                let start = u32::try_from(self.children_pool.len()).unwrap_or(u32::MAX);
1109                let len = u32::try_from(slot.len()).unwrap_or(u32::MAX);
1110                self.children_pool.extend_from_slice(slot);
1111                slot.clear();
1112                SliceRange { start, len }
1113            }
1114        } else {
1115            SliceRange::EMPTY
1116        };
1117        if let Some(node) = self.nodes.get_mut(parent_id.0 as usize) {
1118            node.span.end = end;
1119            node.children = range;
1120        }
1121        self.scope_stack.pop();
1122    }
1123}
1124
1125/// The encoding that an XML declaration names, when it names one other than UTF-8.
1126fn declared_encoding(declaration: &BytesDecl<'_>) -> Option<String> {
1127    let name = declaration.encoding()?.ok()?;
1128    let utf8 = name.eq_ignore_ascii_case("utf-8") || name.eq_ignore_ascii_case("utf8");
1129    (!utf8).then(|| name.into_owned())
1130}
1131
1132fn resolve_reference(reference: &BytesRef<'_>) -> Result<Cow<'static, str>, Error> {
1133    if let Some(ch) = reference
1134        .resolve_char_ref()
1135        .map_err(|error| Error::Syntax(error.to_string()))?
1136    {
1137        return Ok(Cow::Owned(ch.to_string()));
1138    }
1139    let name: &str = reference.as_ref();
1140    let text = match name {
1141        "lt" => "<",
1142        "gt" => ">",
1143        "amp" => "&",
1144        "apos" => "'",
1145        "quot" => "\"",
1146        other => return Err(Error::Syntax(format!("unknown entity &{other};"))),
1147    };
1148    Ok(Cow::Borrowed(text))
1149}
1150
1151#[cfg(test)]
1152mod tests {
1153    use super::{Document, Error, Limits, NodeKind};
1154
1155    const W: &str = "http://schemas.openxmlformats.org/wordprocessingml/2006/main";
1156
1157    fn parse(xml: &str) -> Result<Document, Error> {
1158        Document::parse(xml.as_bytes(), &Limits::default())
1159    }
1160
1161    #[test]
1162    fn reads_elements_attributes_and_text() {
1163        let doc = parse(&format!(
1164            r#"<?xml version="1.0"?><w:document xmlns:w="{W}"><w:p><w:r><w:t xml:space="preserve"> a &amp; b &#x41;</w:t></w:r><w:jc w:val="both"/></w:p></w:document>"#
1165        ))
1166        .unwrap();
1167        let root = doc.root().unwrap();
1168        assert!(doc.is(root, W, "document"));
1169        let p = doc.child(root, W, "p").unwrap();
1170        let t = doc.child(doc.child(p, W, "r").unwrap(), W, "t").unwrap();
1171        assert_eq!(doc.text_content(t), " a & b A");
1172        let jc = doc.child(p, W, "jc").unwrap();
1173        assert_eq!(doc.attribute(jc, Some(W), "val"), Some("both"));
1174        assert_eq!(doc.attribute(jc, None, "val"), None);
1175        let element = doc.element(jc).unwrap();
1176        assert_eq!(element.name.prefix, Some("w"));
1177        assert_eq!(doc.namespace_uri(element.name.namespace.unwrap()), W);
1178    }
1179
1180    #[test]
1181    fn sets_the_children_of_a_node() {
1182        let mut doc = parse("<a><b>x</b><c/><d/></a>").unwrap();
1183        let root = doc.root().unwrap();
1184        let [b, c, d] = [0, 1, 2].map(|i| doc.children(root)[i]);
1185        let x = doc.children(b)[0];
1186        doc.set_children(root, vec![d, x, b]);
1187        doc.set_children(b, Vec::new());
1188        assert_eq!(doc.children(root), [d, x, b]);
1189        assert_eq!(doc.text_content(root), "x");
1190        assert_eq!(doc.children(c), []);
1191        let mut other = parse("<a/>").unwrap();
1192        other.set_children(d, vec![d]);
1193        assert_eq!(other.children(d), []);
1194    }
1195
1196    #[test]
1197    fn sets_an_attribute_of_an_element() {
1198        let mut doc = parse(&format!(r#"<w:r xmlns:w="{W}" w:rsidR="00AB">x</w:r>"#)).unwrap();
1199        let root = doc.root().unwrap();
1200        doc.set_attribute(root, Some("urn:note"), "change", "3");
1201        doc.set_attribute(root, Some(W), "rsidR", "00CD");
1202        doc.set_attribute(root, Some("urn:note"), "change", "4");
1203        assert_eq!(doc.attribute(root, Some("urn:note"), "change"), Some("4"));
1204        assert_eq!(doc.attribute(root, Some(W), "rsidR"), Some("00CD"));
1205        let text = doc.children(root)[0];
1206        doc.set_attribute(text, None, "a", "b");
1207        assert_eq!(doc.attribute(text, None, "a"), None);
1208    }
1209
1210    #[test]
1211    fn keeps_unprefixed_attributes_and_comments() {
1212        let doc = parse(r#"<Relationships><!-- note --><Relationship Id="rId1" Target="a.xml"/></Relationships>"#).unwrap();
1213        let root = doc.root().unwrap();
1214        let rel = doc.child_elements(root).next().unwrap();
1215        assert_eq!(doc.attribute(rel, None, "Id"), Some("rId1"));
1216        let comment = doc.children(root)[0];
1217        assert_eq!(doc.kind(comment), Some(NodeKind::Other("<!-- note -->")));
1218        assert!(doc.text(comment).is_none());
1219        assert!(doc.element(comment).is_none());
1220    }
1221
1222    #[test]
1223    fn joins_text_around_references_and_cdata() {
1224        let doc = parse("<a>x&lt;y<![CDATA[<z>]]>&gt;&apos;&quot;</a>").unwrap();
1225        let root = doc.root().unwrap();
1226        assert_eq!(doc.children(root).len(), 1);
1227        assert_eq!(doc.text_content(root), "x<y<z>>'\"");
1228    }
1229
1230    #[test]
1231    fn refuses_doctype_and_unknown_entities() {
1232        assert_eq!(parse("<!DOCTYPE a><a/>").unwrap_err(), Error::DocType);
1233        assert!(matches!(parse("<a>&bogus;</a>"), Err(Error::Syntax(_))));
1234        assert_eq!(
1235            parse("<!-- only -->").unwrap().root().unwrap_err(),
1236            Error::NoRoot
1237        );
1238    }
1239
1240    #[test]
1241    fn refuses_bad_nesting() {
1242        assert!(matches!(parse("<a><b></a>"), Err(Error::Syntax(_))));
1243        assert!(matches!(parse("<a>"), Err(Error::Syntax(_))));
1244    }
1245
1246    fn undeclared() -> Document {
1247        parse(&format!(
1248            r#"<w:document xmlns:w="{W}" xml:space="preserve"><p:a q:b="1" w:c="2"/><p:d></p:d><w:e p:f="3"/></w:document>"#
1249        ))
1250        .unwrap()
1251    }
1252
1253    #[test]
1254    fn lists_each_undeclared_prefix_once_and_gives_its_elements_no_namespace() {
1255        let doc = undeclared();
1256        assert_eq!(doc.undeclared_prefixes(), ["p", "q"]);
1257        let root = doc.root().unwrap();
1258        let [a, _, e] = [0, 1, 2].map(|i| doc.children(root)[i]);
1259        let element = doc.element(a).unwrap();
1260        assert_eq!(element.name.prefix, Some("p"));
1261        assert_eq!(element.name.namespace, None);
1262        assert!(doc.is(e, W, "e"));
1263        let declared = parse(&format!(r#"<w:a xmlns:w="{W}" xml:space="preserve"/>"#)).unwrap();
1264        assert_eq!(declared.undeclared_prefixes(), [] as [&str; 0]);
1265    }
1266
1267    #[test]
1268    fn reads_an_attribute_of_an_undeclared_prefix_as_one_without_a_prefix() {
1269        let doc = undeclared();
1270        let root = doc.root().unwrap();
1271        let [a, e] = [0, 2].map(|i| doc.children(root)[i]);
1272        assert_eq!(doc.attribute(a, None, "b"), Some("1"));
1273        assert_eq!(doc.attribute(a, Some(W), "c"), Some("2"));
1274        assert_eq!(doc.attribute(e, None, "f"), Some("3"));
1275    }
1276
1277    #[test]
1278    fn resolves_namespace_aliases() {
1279        let xml = r#"<s:document xmlns:s="urn:strict"><s:body s:val="1"/></s:document>"#;
1280        let doc =
1281            Document::parse_with_aliases(xml.as_bytes(), &Limits::default(), &[("urn:strict", W)])
1282                .unwrap();
1283        let root = doc.root().unwrap();
1284        assert!(doc.is(root, W, "document"));
1285        let body = doc.child(root, W, "body").unwrap();
1286        assert_eq!(doc.attribute(body, Some(W), "val"), Some("1"));
1287        let plain = Document::parse(xml.as_bytes(), &Limits::default()).unwrap();
1288        assert!(!plain.is(plain.root().unwrap(), W, "document"));
1289    }
1290
1291    #[test]
1292    fn binds_a_prefix_by_the_nearest_declaration_in_scope() {
1293        let doc = parse(concat!(
1294            r#"<a xmlns:p="urn:outer" xmlns="urn:default">"#,
1295            r#"<b xmlns:p="urn:inner" xmlns:q="urn:q"><c/></b><d/><e xmlns=""/>t</a>"#,
1296        ))
1297        .unwrap();
1298        let root = doc.root().unwrap();
1299        let [b, d, e, text] = [0, 1, 2, 3].map(|i| doc.children(root)[i]);
1300        let c = doc.children(b)[0];
1301        let cases = [
1302            (root, "p", Some("urn:outer")),
1303            (c, "p", Some("urn:inner")),
1304            (c, "q", Some("urn:q")),
1305            (d, "p", Some("urn:outer")),
1306            (d, "q", None),
1307            (c, "", Some("urn:default")),
1308            (e, "", None),
1309            (e, "xml", Some(super::XML_NAMESPACE)),
1310            (text, "p", None),
1311            (text, "xml", None),
1312        ];
1313        for (node, prefix, namespace) in cases {
1314            assert_eq!(
1315                doc.prefix_namespace(node, prefix),
1316                namespace,
1317                "{node:?} {prefix}"
1318            );
1319        }
1320    }
1321
1322    #[test]
1323    fn binds_a_prefix_to_its_alias() {
1324        let xml = r#"<a xmlns:s="urn:strict"><b/></a>"#;
1325        let doc =
1326            Document::parse_with_aliases(xml.as_bytes(), &Limits::default(), &[("urn:strict", W)])
1327                .unwrap();
1328        let b = doc.children(doc.root().unwrap())[0];
1329        assert_eq!(doc.prefix_namespace(b, "s"), Some(W));
1330    }
1331
1332    #[test]
1333    fn enforces_limits() {
1334        let deep = Limits {
1335            max_depth: 2,
1336            max_nodes: 100,
1337        };
1338        assert_eq!(
1339            Document::parse(b"<a><b><c/></b></a>", &deep).map(|_| ()),
1340            Ok(())
1341        );
1342        assert_eq!(
1343            Document::parse(b"<a><b><c></c></b></a>", &deep).unwrap_err(),
1344            Error::TooDeep
1345        );
1346        let few = Limits {
1347            max_depth: 10,
1348            max_nodes: 2,
1349        };
1350        assert_eq!(
1351            Document::parse(b"<a><b/><c/></a>", &few).unwrap_err(),
1352            Error::TooManyNodes
1353        );
1354    }
1355
1356    #[test]
1357    fn errors_display() {
1358        for error in [
1359            Error::Syntax("x".into()),
1360            Error::DocType,
1361            Error::TooDeep,
1362            Error::TooManyNodes,
1363            Error::NoRoot,
1364        ] {
1365            assert_ne!(error.to_string(), "");
1366        }
1367    }
1368}