|
56 | 56 | //! assert_eq!(q1.compare(&key), Ordering::Equal);
|
57 | 57 | //! assert_eq!(q2.compare(&key), Ordering::Less);
|
58 | 58 | //! 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)); |
59 | 64 | //! }
|
60 | 65 | //! ```
|
61 | 66 |
|
62 | 67 | #![no_std]
|
63 | 68 |
|
64 | 69 | use core::borrow::Borrow;
|
65 | 70 | use core::cmp::Ordering;
|
| 71 | +use core::ops::{Bound, RangeBounds}; |
66 | 72 |
|
67 | 73 | /// Key equivalence trait.
|
68 | 74 | ///
|
@@ -111,3 +117,35 @@ where
|
111 | 117 | Ord::cmp(self, key.borrow())
|
112 | 118 | }
|
113 | 119 | }
|
| 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