Skip to content

Commit 7767ef2

Browse files
Allow Ranges::contains to accept (e.g.) &str for Ranges<String> (#35) (#301)
## Summary This PR borrows a trick from [HashMap](https://doc.rust-lang.org/std/collections/struct.HashMap.html#method.contains_key) to enable users to pass (e.g.) `&str` to `Ranges::contains`, given `Ranges<String>`. Co-authored-by: Charlie Marsh <crmarsh416@gmail.com>
1 parent 3bef331 commit 7767ef2

File tree

1 file changed

+16
-8
lines changed

1 file changed

+16
-8
lines changed

version-ranges/src/lib.rs

Lines changed: 16 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -229,7 +229,11 @@ impl<V: Ord> Ranges<V> {
229229
}
230230

231231
/// Returns true if self contains the specified value.
232-
pub fn contains(&self, version: &V) -> bool {
232+
pub fn contains<Q>(&self, version: &Q) -> bool
233+
where
234+
V: Borrow<Q>,
235+
Q: ?Sized + PartialOrd,
236+
{
233237
self.segments
234238
.binary_search_by(|segment| {
235239
// We have to reverse because we need the segment wrt to the version, while
@@ -470,19 +474,23 @@ impl<V: Ord> Ord for Ranges<V> {
470474
/// ^ ^ ^
471475
/// less equal greater
472476
/// ```
473-
fn within_bounds<V: PartialOrd>(version: &V, segment: &Interval<V>) -> Ordering {
477+
fn within_bounds<Q, V>(version: &Q, segment: &Interval<V>) -> Ordering
478+
where
479+
V: Borrow<Q>,
480+
Q: ?Sized + PartialOrd,
481+
{
474482
let below_lower_bound = match segment {
475-
(Excluded(start), _) => version <= start,
476-
(Included(start), _) => version < start,
483+
(Excluded(start), _) => version <= start.borrow(),
484+
(Included(start), _) => version < start.borrow(),
477485
(Unbounded, _) => false,
478486
};
479487
if below_lower_bound {
480488
return Ordering::Less;
481489
}
482490
let below_upper_bound = match segment {
483491
(_, Unbounded) => true,
484-
(_, Included(end)) => version <= end,
485-
(_, Excluded(end)) => version < end,
492+
(_, Included(end)) => version <= end.borrow(),
493+
(_, Excluded(end)) => version < end.borrow(),
486494
};
487495
if below_upper_bound {
488496
return Ordering::Equal;
@@ -1304,7 +1312,7 @@ pub mod tests {
13041312

13051313
#[test]
13061314
fn always_contains_exact(version in version_strat()) {
1307-
assert!(Ranges::singleton(version).contains(&version));
1315+
assert!(Ranges::<u32>::singleton(version).contains(&version));
13081316
}
13091317

13101318
#[test]
@@ -1326,7 +1334,7 @@ pub mod tests {
13261334

13271335
#[test]
13281336
fn from_range_bounds(range in any::<(Bound<u32>, Bound<u32>)>(), version in version_strat()) {
1329-
let rv: Ranges<_> = Ranges::from_range_bounds(range);
1337+
let rv: Ranges<_> = Ranges::<u32>::from_range_bounds(range);
13301338
assert_eq!(range.contains(&version), rv.contains(&version));
13311339
}
13321340

0 commit comments

Comments
 (0)