From 0d0c4b76eb674f02aa4cdccd3f3a9a8d466926d0 Mon Sep 17 00:00:00 2001 From: Eijebong Date: Mon, 24 Apr 2017 20:06:21 +0200 Subject: [PATCH] Fix the PartialEq implementation for Element The order of attributes in an `Element` doesn't matter anymore. `` and `` are now correctly considered equal. For that I had to derive `PartialOrd` and `Ord` for `Attribute`. This allows us to sort cloned vectors of `Attribute` in the `PartialEq` implementation and compare them instead of the struct `attributes`. Fixes #3 --- src/attribute.rs | 2 +- src/element.rs | 16 +++++++++++++++- src/tests.rs | 11 +++++++++++ 3 files changed, 27 insertions(+), 2 deletions(-) diff --git a/src/attribute.rs b/src/attribute.rs index 57373a0..10e0e3d 100644 --- a/src/attribute.rs +++ b/src/attribute.rs @@ -9,7 +9,7 @@ use std::fmt; /// This is of the form: `name`="`value`" /// /// This does not support prefixed/namespaced attributes yet. -#[derive(Clone, Debug, PartialEq, Eq)] +#[derive(Clone, Debug, PartialEq, Eq, Ord, PartialOrd)] pub struct Attribute { /// The name of the attribute. pub name: String, diff --git a/src/element.rs b/src/element.rs index 13c8baf..197d9ed 100644 --- a/src/element.rs +++ b/src/element.rs @@ -20,7 +20,7 @@ use std::slice; use convert::{IntoElements, IntoAttributeValue, ElementEmitter}; -#[derive(Clone, PartialEq, Eq)] +#[derive(Clone, Eq)] /// A struct representing a DOM Element. pub struct Element { name: String, @@ -29,6 +29,20 @@ pub struct Element { children: Vec, } +impl PartialEq for Element { + fn eq(&self, other: &Element) -> bool { + let mut my_attr = self.attributes.clone(); + my_attr.sort(); + let mut other_attr = other.attributes.clone(); + other_attr.sort(); + + self.name == other.name && + self.namespace == other.namespace && + my_attr == other_attr && + self.children == other.children + } +} + impl fmt::Debug for Element { fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result { write!(fmt, "<{}", self.name)?; diff --git a/src/tests.rs b/src/tests.rs index b926344..44fef37 100644 --- a/src/tests.rs +++ b/src/tests.rs @@ -94,3 +94,14 @@ fn namespace_propagation_works() { .get_child("grandchild", "root_ns").unwrap() .ns(), root.ns()); } + +#[test] +fn two_elements_with_same_arguments_different_order_are_equal() { + let elem1: Element = "".parse().unwrap(); + let elem2: Element = "".parse().unwrap(); + assert_eq!(elem1, elem2); + + let elem1: Element = "".parse().unwrap(); + let elem2: Element = "".parse().unwrap(); + assert_ne!(elem1, elem2); +}