Skip to content

Commit b889598

Browse files
authored
Rollup merge of rust-lang#114152 - ttsugriy:master, r=WaffleLapkin
[rustc][data_structures] Simplify binary_search_slice. Instead of using `binary_search_by_key`, it's possible to use `partition_point` to find the lower bound. This avoids the need to locate the leftmost matching entry separately. It's also possible to use `partition_point` to find the upper bound, so I plan to send a separate PR for your consideration.
2 parents fa94851 + 31fadf6 commit b889598

File tree

1 file changed

+7
-31
lines changed
  • compiler/rustc_data_structures/src/binary_search_util

1 file changed

+7
-31
lines changed

compiler/rustc_data_structures/src/binary_search_util/mod.rs

+7-31
Original file line numberDiff line numberDiff line change
@@ -10,41 +10,17 @@ pub fn binary_search_slice<'d, E, K>(data: &'d [E], key_fn: impl Fn(&E) -> K, ke
1010
where
1111
K: Ord,
1212
{
13-
let Ok(mid) = data.binary_search_by_key(key, &key_fn) else {
13+
let size = data.len();
14+
let start = data.partition_point(|x| key_fn(x) < *key);
15+
// At this point `start` either points at the first entry with equal or
16+
// greater key or is equal to `size` in case all elements have smaller keys
17+
if start == size || key_fn(&data[start]) != *key {
1418
return &[];
1519
};
16-
let size = data.len();
17-
18-
// We get back *some* element with the given key -- so do
19-
// a galloping search backwards to find the *first* one.
20-
let mut start = mid;
21-
let mut previous = mid;
22-
let mut step = 1;
23-
loop {
24-
start = start.saturating_sub(step);
25-
if start == 0 || key_fn(&data[start]) != *key {
26-
break;
27-
}
28-
previous = start;
29-
step *= 2;
30-
}
31-
step = previous - start;
32-
while step > 1 {
33-
let half = step / 2;
34-
let mid = start + half;
35-
if key_fn(&data[mid]) != *key {
36-
start = mid;
37-
}
38-
step -= half;
39-
}
40-
// adjust by one if we have overshot
41-
if start < size && key_fn(&data[start]) != *key {
42-
start += 1;
43-
}
4420

4521
// Now search forward to find the *last* one.
46-
let mut end = mid;
47-
let mut previous = mid;
22+
let mut end = start;
23+
let mut previous = start;
4824
let mut step = 1;
4925
loop {
5026
end = end.saturating_add(step).min(size);

0 commit comments

Comments
 (0)