Skip to content

Commit

Permalink
Merge pull request #72 from hecrj/fix/partial-eq
Browse files Browse the repository at this point in the history
Fix `PartialEq`, `PartialOrd`, and `Ord` implementations for `RangeMap` (and `RangeSet`)
  • Loading branch information
jeffparsons committed Sep 18, 2023
2 parents ea9b2e3 + 432dcb3 commit ca38f2c
Showing 1 changed file with 59 additions and 3 deletions.
62 changes: 59 additions & 3 deletions src/map.rs
Original file line number Diff line number Diff line change
Expand Up @@ -40,7 +40,7 @@ where
V: PartialEq,
{
fn eq(&self, other: &RangeMap<K, V>) -> bool {
self.btm == other.btm
self.expanded_iter().eq(other.expanded_iter())
}
}

Expand All @@ -51,7 +51,7 @@ where
{
#[inline]
fn partial_cmp(&self, other: &RangeMap<K, V>) -> Option<Ordering> {
self.btm.partial_cmp(&other.btm)
self.expanded_iter().partial_cmp(other.expanded_iter())
}
}

Expand All @@ -62,7 +62,7 @@ where
{
#[inline]
fn cmp(&self, other: &RangeMap<K, V>) -> Ordering {
self.btm.cmp(&other.btm)
self.expanded_iter().cmp(other.expanded_iter())
}
}

Expand Down Expand Up @@ -114,6 +114,13 @@ impl<K, V> RangeMap<K, V> {
pub fn is_empty(&self) -> bool {
self.btm.is_empty()
}

/// Returns an iterator that includes both ends of the key range.
///
/// Mainly used for comparisons.
fn expanded_iter(&self) -> impl Iterator<Item = (&K, &K, &V)> {
self.btm.iter().map(|(k, v)| (&k.start, &k.end, v))
}
}

impl<K, V> RangeMap<K, V>
Expand Down Expand Up @@ -1470,6 +1477,55 @@ mod tests {
assert_eq!(cloned, consumed);
}

// Equality
#[test]
fn eq() {
let mut a: RangeMap<u32, bool> = RangeMap::new();
a.insert(1..3, false);

let mut b: RangeMap<u32, bool> = RangeMap::new();
b.insert(1..4, false);

let mut c: RangeMap<u32, bool> = RangeMap::new();
c.insert(1..3, false);

assert_ne!(a, b);
assert_ne!(b, a);

assert_eq!(a, c);
assert_eq!(c, a);
assert_eq!(a, a);
}

// Ord
#[test]
fn partial_ord() {
let mut a: RangeMap<u32, bool> = RangeMap::new();
a.insert(1..3, false);

let mut b: RangeMap<u32, bool> = RangeMap::new();
b.insert(1..4, false);

assert_eq!(a.partial_cmp(&a), Some(Ordering::Equal));

assert_eq!(a.partial_cmp(&b), Some(Ordering::Less));
assert_eq!(b.partial_cmp(&a), Some(Ordering::Greater));
}

#[test]
fn ord() {
let mut a: RangeMap<u32, bool> = RangeMap::new();
a.insert(1..3, false);

let mut b: RangeMap<u32, bool> = RangeMap::new();
b.insert(1..4, false);

assert_eq!(a.cmp(&a), Ordering::Equal);

assert_eq!(a.cmp(&b), Ordering::Less);
assert_eq!(b.cmp(&a), Ordering::Greater);
}

// impl Serialize

#[cfg(feature = "serde1")]
Expand Down

0 comments on commit ca38f2c

Please sign in to comment.