feat: add lookup_index_by_key to Rust Vector for index-based search (#8959)

* feat: add lookup_index_by_key to Rust Vector for index-based binary search

* fix: remove duplicated code
This commit is contained in:
statxc
2026-03-11 04:15:21 +02:00
committed by GitHub
parent de3b97355d
commit a7fed2ce67
2 changed files with 165 additions and 1 deletions

View File

@@ -107,6 +107,20 @@ impl<'a, T: Follow<'a> + 'a> Vector<'a, T> {
key: K,
f: fn(&<T as Follow<'a>>::Inner, &K) -> Ordering,
) -> Option<T::Inner> {
self.lookup_index_by_key(key, f).map(|idx| self.get(idx))
}
/// Binary search by key, returning the index of the matching element.
///
/// This is similar to `lookup_by_key`, but returns the index of the found
/// element rather than the element itself. This is useful when you need
/// to reference elements by their position in the vector.
#[inline(always)]
pub fn lookup_index_by_key<K: Ord>(
&self,
key: K,
f: fn(&<T as Follow<'a>>::Inner, &K) -> Ordering,
) -> Option<usize> {
if self.is_empty() {
return None;
}
@@ -118,7 +132,7 @@ impl<'a, T: Follow<'a> + 'a> Vector<'a, T> {
let mid = (left + right) / 2;
let value = self.get(mid);
match f(&value, &key) {
Ordering::Equal => return Some(value),
Ordering::Equal => return Some(mid),
Ordering::Less => left = mid + 1,
Ordering::Greater => {
if mid == 0 {