1use crate::{Attribute, Document, Element, Name, NodeId, NodeKind};
4
5#[cfg(test)]
6mod tests;
7
8#[derive(Clone, Copy, Debug, PartialEq, Eq)]
11#[non_exhaustive]
12pub enum Equality {
13 AsWritten,
17 ByNamespace,
22}
23
24impl Document {
25 #[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
52fn 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
82fn 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
96fn plain(element: Element<'_>) -> Vec<Attribute<'_>> {
98 element
99 .attributes
100 .iter()
101 .filter(|attribute| !declares(attribute))
102 .collect()
103}
104
105fn declares(attribute: &Attribute<'_>) -> bool {
107 match attribute.name.prefix {
108 Some(prefix) => prefix == "xmlns",
109 None => attribute.name.local == "xmlns",
110 }
111}