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)
.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 uri = |document: &Document, name: &Name| {
name.namespace
.map(|namespace| document.namespace_uri(namespace).to_owned())
};
let (left_uri, right_uri) = (uri(a, left), uri(b, right));
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.as_deref() {
Some(prefix) => prefix == "xmlns",
None => attribute.name.local == "xmlns",
}
}