Skip to content

Commit 86cdc16

Browse files
committed
Support RangeBounds for T: Comparable
1 parent 8a56bf0 commit 86cdc16

File tree

2 files changed

+40
-2
lines changed

2 files changed

+40
-2
lines changed

Cargo.toml

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,7 @@
11
[package]
22
name = "equivalent"
3-
version = "1.0.1"
4-
rust-version = "1.6"
3+
version = "1.1.0"
4+
rust-version = "1.28"
55
license = "Apache-2.0 OR MIT"
66
description = "Traits for key comparison in maps."
77
repository = "https://github.com/cuviper/equivalent"

src/lib.rs

Lines changed: 38 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -56,13 +56,19 @@
5656
//! assert_eq!(q1.compare(&key), Ordering::Equal);
5757
//! assert_eq!(q2.compare(&key), Ordering::Less);
5858
//! assert_eq!(q3.compare(&key), Ordering::Greater);
59+
//!
60+
//! // You cannot do this with the `RangeBounds::contains` method.
61+
//! // assert!((q1..q3).contains(key));
62+
//! // But you can do this with the `ComparableRangeBounds::compare_contains` method.
63+
//! assert!((q1..q3).compare_contains(&key));
5964
//! }
6065
//! ```
6166
6267
#![no_std]
6368

6469
use core::borrow::Borrow;
6570
use core::cmp::Ordering;
71+
use core::ops::{Bound, RangeBounds};
6672

6773
/// Key equivalence trait.
6874
///
@@ -111,3 +117,35 @@ where
111117
Ord::cmp(self, key.borrow())
112118
}
113119
}
120+
121+
/// `ComparableRangeBounds` is implemented as an extention to `RangeBounds` to
122+
/// allow for comparison of items with range bounds.
123+
pub trait ComparableRangeBounds<Q: ?Sized>: RangeBounds<Q> {
124+
/// Returns `true` if `item` is contained in the range.
125+
///
126+
/// # Examples
127+
///
128+
/// See the [crate-level documentation](crate).
129+
fn compare_contains<K>(&self, item: &K) -> bool
130+
where
131+
Q: Comparable<K>,
132+
K: ?Sized,
133+
{
134+
(match self.start_bound() {
135+
Bound::Included(start) => start.compare(item) != Ordering::Greater,
136+
Bound::Excluded(start) => start.compare(item) == Ordering::Less,
137+
Bound::Unbounded => true,
138+
}) && (match self.end_bound() {
139+
Bound::Included(end) => end.compare(item) != Ordering::Less,
140+
Bound::Excluded(end) => end.compare(item) == Ordering::Greater,
141+
Bound::Unbounded => true,
142+
})
143+
}
144+
}
145+
146+
impl<R, T> ComparableRangeBounds<T> for R
147+
where
148+
R: ?Sized + RangeBounds<T>,
149+
T: ?Sized,
150+
{
151+
}

0 commit comments

Comments
 (0)