Skip to content

Commit 3dbb123

Browse files
committed
Add VacantEntry::insert_sorted_by{,_key}
1 parent 9cd1212 commit 3dbb123

File tree

1 file changed

+40
-0
lines changed

1 file changed

+40
-0
lines changed

src/map/core/entry.rs

Lines changed: 40 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,6 @@
11
use super::{equivalent, Entries, IndexMapCore, RefMut};
22
use crate::HashValue;
3+
use core::cmp::Ordering;
34
use core::{fmt, mem};
45
use hashbrown::hash_table;
56

@@ -402,6 +403,45 @@ impl<'a, K, V> VacantEntry<'a, K, V> {
402403
(i, self.shift_insert(i, value))
403404
}
404405

406+
/// Inserts the entry's key and the given value into the map at its ordered
407+
/// position among keys sorted by `cmp`, and returns the new index and a
408+
/// mutable reference to the value.
409+
///
410+
/// If the existing keys are **not** already sorted, then the insertion
411+
/// index is unspecified (like [`slice::binary_search`]), but the key-value
412+
/// pair is inserted at that position regardless.
413+
///
414+
/// Computes in **O(n)** time (average).
415+
pub fn insert_sorted_by<F>(self, value: V, cmp: F) -> (usize, &'a mut V)
416+
where
417+
K: Ord,
418+
F: FnMut(&K, &V) -> Ordering,
419+
{
420+
let slice = crate::map::Slice::from_slice(self.map.entries);
421+
let (Ok(i) | Err(i)) = slice.binary_search_by(cmp);
422+
(i, self.shift_insert(i, value))
423+
}
424+
425+
/// Inserts the entry's key and the given value into the map at its ordered
426+
/// position using a sort-key extraction function, and returns the new index
427+
/// and a mutable reference to the value.
428+
///
429+
/// If the existing keys are **not** already sorted, then the insertion
430+
/// index is unspecified (like [`slice::binary_search`]), but the key-value
431+
/// pair is inserted at that position regardless.
432+
///
433+
/// Computes in **O(n)** time (average).
434+
pub fn insert_sorted_by_key<B, F>(self, value: V, mut sort_key: F) -> (usize, &'a mut V)
435+
where
436+
B: Ord,
437+
F: FnMut(&K, &V) -> B,
438+
{
439+
let search_key = sort_key(&self.key, &value);
440+
let slice = crate::map::Slice::from_slice(self.map.entries);
441+
let (Ok(i) | Err(i)) = slice.binary_search_by_key(&search_key, sort_key);
442+
(i, self.shift_insert(i, value))
443+
}
444+
405445
/// Inserts the entry's key and the given value into the map at the given index,
406446
/// shifting others to the right, and returns a mutable reference to the value.
407447
///

0 commit comments

Comments
 (0)