Skip to content

Commit edc6fc1

Browse files
committed
Auto merge of #3028 - ttsugriy:range-map-find-offset, r=RalfJung
Replace hand-written binary search with Vec::binary_search_by. It's similar to rust-lang/miri#3021 and should improve maintainability.
2 parents e08baec + 0711c01 commit edc6fc1

File tree

1 file changed

+15
-20
lines changed

1 file changed

+15
-20
lines changed

src/tools/miri/src/range_map.rs

+15-20
Original file line numberDiff line numberDiff line change
@@ -36,26 +36,21 @@ impl<T> RangeMap<T> {
3636

3737
/// Finds the index containing the given offset.
3838
fn find_offset(&self, offset: u64) -> usize {
39-
// We do a binary search.
40-
let mut left = 0usize; // inclusive
41-
let mut right = self.v.len(); // exclusive
42-
loop {
43-
debug_assert!(left < right, "find_offset: offset {offset} is out-of-bounds");
44-
let candidate = left.checked_add(right).unwrap() / 2;
45-
let elem = &self.v[candidate];
46-
if offset < elem.range.start {
47-
// We are too far right (offset is further left).
48-
debug_assert!(candidate < right); // we are making progress
49-
right = candidate;
50-
} else if offset >= elem.range.end {
51-
// We are too far left (offset is further right).
52-
debug_assert!(candidate >= left); // we are making progress
53-
left = candidate + 1;
54-
} else {
55-
// This is it!
56-
return candidate;
57-
}
58-
}
39+
self.v
40+
.binary_search_by(|elem| -> std::cmp::Ordering {
41+
if offset < elem.range.start {
42+
// We are too far right (offset is further left).
43+
// (`Greater` means that `elem` is greater than the desired target.)
44+
std::cmp::Ordering::Greater
45+
} else if offset >= elem.range.end {
46+
// We are too far left (offset is further right).
47+
std::cmp::Ordering::Less
48+
} else {
49+
// This is it!
50+
std::cmp::Ordering::Equal
51+
}
52+
})
53+
.unwrap()
5954
}
6055

6156
/// Provides read-only iteration over everything in the given range. This does

0 commit comments

Comments
 (0)