Skip to main content

f_office_xml/
compare.rs

1//! Whether two nodes, of one document or of two, hold the same XML ([`Document::same_tree`]).
2
3use crate::{Attribute, Document, Element, Name, NodeId, NodeKind};
4
5#[cfg(test)]
6mod tests;
7
8/// How [`Document::same_tree`] compares two nodes. Both compare text, comments and processing
9/// instructions exactly, as the reader holds them, and the children in order.
10#[derive(Clone, Copy, Debug, PartialEq, Eq)]
11#[non_exhaustive]
12pub enum Equality {
13    /// As written: each name with its prefix, local name and namespace URI, and the attributes
14    /// in order, the namespace declarations among them. The bytes of an element's span read
15    /// back so.
16    AsWritten,
17    /// By meaning: each name by its namespace URI and local name, or by its prefix and local
18    /// name when it has no namespace; the attributes in any order, without the namespace
19    /// declarations. Two spellings of one element, with other prefixes, quotes or attribute
20    /// order, compare so as equal.
21    ByNamespace,
22}
23
24impl Document {
25    /// Whether the node `id` of this document and the node `other_id` of `other` hold the same
26    /// XML under `equality`, with all their content.
27    #[must_use]
28    pub fn same_tree(
29        &self,
30        id: NodeId,
31        (other, other_id): (&Self, NodeId),
32        equality: Equality,
33    ) -> bool {
34        let kinds_match = match (self.kind(id), other.kind(other_id)) {
35            (Some(NodeKind::Element(left)), Some(NodeKind::Element(right))) => {
36                same_element((self, left), (other, right), equality)
37            }
38            (Some(NodeKind::Text(left)), Some(NodeKind::Text(right)))
39            | (Some(NodeKind::Other(left)), Some(NodeKind::Other(right))) => left == right,
40            _ => false,
41        };
42        let (children, other_children) = (self.children(id), other.children(other_id));
43        kinds_match
44            && children.len() == other_children.len()
45            && children
46                .iter()
47                .zip(other_children)
48                .all(|(child, other_child)| self.same_tree(*child, (other, *other_child), equality))
49    }
50}
51
52/// Whether two elements have the same name and attributes under `equality`.
53fn same_element(
54    (a, left): (&Document, Element<'_>),
55    (b, right): (&Document, Element<'_>),
56    equality: Equality,
57) -> bool {
58    let names = |left: &Name<'_>, right: &Name<'_>| same_name((a, left), (b, right), equality);
59    match equality {
60        Equality::AsWritten => {
61            names(&left.name, &right.name)
62                && left.attributes.len() == right.attributes.len()
63                && left
64                    .attributes
65                    .iter()
66                    .zip(right.attributes.iter())
67                    .all(|(l, r)| names(&l.name, &r.name) && l.value == r.value)
68        }
69        Equality::ByNamespace => {
70            let (left_attributes, right_attributes) = (plain(left), plain(right));
71            names(&left.name, &right.name)
72                && left_attributes.len() == right_attributes.len()
73                && left_attributes.iter().all(|l| {
74                    right_attributes
75                        .iter()
76                        .any(|r| names(&l.name, &r.name) && l.value == r.value)
77                })
78        }
79    }
80}
81
82/// Whether two names are the same under `equality`.
83fn same_name(
84    (a, left): (&Document, &Name<'_>),
85    (b, right): (&Document, &Name<'_>),
86    equality: Equality,
87) -> bool {
88    let left_uri = left.namespace.map(|ns| a.namespace_uri(ns));
89    let right_uri = right.namespace.map(|ns| b.namespace_uri(ns));
90    let prefixes_count = equality == Equality::AsWritten || left_uri.is_none();
91    left.local == right.local
92        && left_uri == right_uri
93        && (!prefixes_count || left.prefix == right.prefix)
94}
95
96/// The attributes of `element` that declare no namespace.
97fn plain(element: Element<'_>) -> Vec<Attribute<'_>> {
98    element
99        .attributes
100        .iter()
101        .filter(|attribute| !declares(attribute))
102        .collect()
103}
104
105/// Whether an attribute declares a namespace: `xmlns` or `xmlns:p`.
106fn declares(attribute: &Attribute<'_>) -> bool {
107    match attribute.name.prefix {
108        Some(prefix) => prefix == "xmlns",
109        None => attribute.name.local == "xmlns",
110    }
111}