use crate::{Attribute, Document, Element, Name, NodeId, NodeKind};
#[cfg(test)]
mod tests;
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
#[non_exhaustive]
pub enum Equality {
AsWritten,
ByNamespace,
}
impl Document {
#[must_use]
pub fn same_tree(
&self,
id: NodeId,
(other, other_id): (&Self, NodeId),
equality: Equality,
) -> bool {
let kinds_match = match (self.kind(id), other.kind(other_id)) {
(Some(NodeKind::Element(left)), Some(NodeKind::Element(right))) => {
same_element((self, left), (other, right), equality)
}
(Some(NodeKind::Text(left)), Some(NodeKind::Text(right)))
| (Some(NodeKind::Other(left)), Some(NodeKind::Other(right))) => left == right,
_ => false,
};
let (children, other_children) = (self.children(id), other.children(other_id));
kinds_match
&& children.len() == other_children.len()
&& children
.iter()
.zip(other_children)
.all(|(child, other_child)| self.same_tree(*child, (other, *other_child), equality))
}
}
fn same_element(
(a, left): (&Document, Element<'_>),
(b, right): (&Document, Element<'_>),
equality: Equality,
) -> bool {
let names = |left: &Name<'_>, right: &Name<'_>| same_name((a, left), (b, right), equality);
match equality {
Equality::AsWritten => {
names(&left.name, &right.name)
&& left.attributes.len() == right.attributes.len()
&& left
.attributes
.iter()
.zip(right.attributes.iter())
.all(|(l, r)| names(&l.name, &r.name) && l.value == r.value)
}
Equality::ByNamespace => {
let (left_attributes, right_attributes) = (plain(left), plain(right));
names(&left.name, &right.name)
&& left_attributes.len() == right_attributes.len()
&& left_attributes.iter().all(|l| {
right_attributes
.iter()
.any(|r| names(&l.name, &r.name) && l.value == r.value)
})
}
}
}
fn same_name(
(a, left): (&Document, &Name<'_>),
(b, right): (&Document, &Name<'_>),
equality: Equality,
) -> bool {
let left_uri = left.namespace.map(|ns| a.namespace_uri(ns));
let right_uri = right.namespace.map(|ns| b.namespace_uri(ns));
let prefixes_count = equality == Equality::AsWritten || left_uri.is_none();
left.local == right.local
&& left_uri == right_uri
&& (!prefixes_count || left.prefix == right.prefix)
}
fn plain(element: Element<'_>) -> Vec<Attribute<'_>> {
element
.attributes
.iter()
.filter(|attribute| !declares(attribute))
.collect()
}
fn declares(attribute: &Attribute<'_>) -> bool {
match attribute.name.prefix {
Some(prefix) => prefix == "xmlns",
None => attribute.name.local == "xmlns",
}
}