Skip to content

Commit

Permalink
Support RangeBounds for T: Comparable
Browse files Browse the repository at this point in the history
  • Loading branch information
al8n committed Oct 15, 2024
1 parent 8a56bf0 commit 86cdc16
Show file tree
Hide file tree
Showing 2 changed files with 40 additions and 2 deletions.
4 changes: 2 additions & 2 deletions Cargo.toml
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
[package]
name = "equivalent"
version = "1.0.1"
rust-version = "1.6"
version = "1.1.0"
rust-version = "1.28"
license = "Apache-2.0 OR MIT"
description = "Traits for key comparison in maps."
repository = "https://github.com/cuviper/equivalent"
Expand Down
38 changes: 38 additions & 0 deletions src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -56,13 +56,19 @@
//! assert_eq!(q1.compare(&key), Ordering::Equal);
//! assert_eq!(q2.compare(&key), Ordering::Less);
//! assert_eq!(q3.compare(&key), Ordering::Greater);
//!
//! // You cannot do this with the `RangeBounds::contains` method.
//! // assert!((q1..q3).contains(key));
//! // But you can do this with the `ComparableRangeBounds::compare_contains` method.
//! assert!((q1..q3).compare_contains(&key));
//! }
//! ```
#![no_std]

use core::borrow::Borrow;
use core::cmp::Ordering;
use core::ops::{Bound, RangeBounds};

/// Key equivalence trait.
///
Expand Down Expand Up @@ -111,3 +117,35 @@ where
Ord::cmp(self, key.borrow())
}
}

/// `ComparableRangeBounds` is implemented as an extention to `RangeBounds` to
/// allow for comparison of items with range bounds.
pub trait ComparableRangeBounds<Q: ?Sized>: RangeBounds<Q> {
/// Returns `true` if `item` is contained in the range.
///
/// # Examples
///
/// See the [crate-level documentation](crate).
fn compare_contains<K>(&self, item: &K) -> bool
where
Q: Comparable<K>,
K: ?Sized,
{
(match self.start_bound() {
Bound::Included(start) => start.compare(item) != Ordering::Greater,
Bound::Excluded(start) => start.compare(item) == Ordering::Less,
Bound::Unbounded => true,
}) && (match self.end_bound() {
Bound::Included(end) => end.compare(item) != Ordering::Less,
Bound::Excluded(end) => end.compare(item) == Ordering::Greater,
Bound::Unbounded => true,
})
}
}

impl<R, T> ComparableRangeBounds<T> for R
where
R: ?Sized + RangeBounds<T>,
T: ?Sized,
{
}

0 comments on commit 86cdc16

Please sign in to comment.