Skip to content

Commit

Permalink
Simplify contains
Browse files Browse the repository at this point in the history
  • Loading branch information
konstin committed Mar 7, 2024
1 parent c0e306f commit d198313
Showing 1 changed file with 16 additions and 23 deletions.
39 changes: 16 additions & 23 deletions src/range.rs
Original file line number Diff line number Diff line change
Expand Up @@ -202,27 +202,14 @@ impl<V: Ord> Range<V> {
}

/// Returns true if this Range contains the specified value.
pub fn contains(&self, v: &V) -> bool {
pub fn contains(&self, version: &V) -> bool {
self.segments
.binary_search_by(|segment| {
let lower_bound_greater = match segment {
(Excluded(start), _) => v <= start,
(Included(start), _) => v < start,
(Unbounded, _) => false,
};
if lower_bound_greater {
return Ordering::Greater;
}
let upper_bound_greater = match segment {
(_, Unbounded) => true,
(_, Included(end)) => v <= end,
(_, Excluded(end)) => v < end,
};
if upper_bound_greater {
return Ordering::Equal;
}
Ordering::Less
// We have to reverse because we need the segment wrt to the version, while
// within bounds tells us the version wrt to the segment.
within_bounds(version, segment).reverse()
})
// An equal interval is one that contains the version
.is_ok()
}

Expand Down Expand Up @@ -308,19 +295,25 @@ impl<V: Ord> Range<V> {
}
}

fn within_bounds<V: PartialOrd>(v: &V, segment: &Interval<V>) -> Ordering {
/// The ordering of the version wrt to the interval.
/// ```text
/// |-------|
/// ^ ^ ^
/// less equal greater
/// ```
fn within_bounds<V: PartialOrd>(version: &V, segment: &Interval<V>) -> Ordering {
let below_lower_bound = match segment {
(Excluded(start), _) => v <= start,
(Included(start), _) => v < start,
(Excluded(start), _) => version <= start,
(Included(start), _) => version < start,
(Unbounded, _) => false,
};
if below_lower_bound {
return Ordering::Less;
}
let below_upper_bound = match segment {
(_, Unbounded) => true,
(_, Included(end)) => v <= end,
(_, Excluded(end)) => v < end,
(_, Included(end)) => version <= end,
(_, Excluded(end)) => version < end,
};
if below_upper_bound {
return Ordering::Equal;
Expand Down

0 comments on commit d198313

Please sign in to comment.