|
1 | 1 | use super::{equivalent, Entries, IndexMapCore, RefMut};
|
2 | 2 | use crate::HashValue;
|
| 3 | +use core::cmp::Ordering; |
3 | 4 | use core::{fmt, mem};
|
4 | 5 | use hashbrown::hash_table;
|
5 | 6 |
|
@@ -402,6 +403,45 @@ impl<'a, K, V> VacantEntry<'a, K, V> {
|
402 | 403 | (i, self.shift_insert(i, value))
|
403 | 404 | }
|
404 | 405 |
|
| 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 | + |
405 | 445 | /// Inserts the entry's key and the given value into the map at the given index,
|
406 | 446 | /// shifting others to the right, and returns a mutable reference to the value.
|
407 | 447 | ///
|
|
0 commit comments