@@ -445,12 +445,52 @@ where
445
445
}
446
446
}
447
447
448
+ /// Insert a key-value pair in the map before the entry at the given index, or at the end.
449
+ ///
450
+ /// If an equivalent key already exists in the map: the key remains and
451
+ /// is moved to the new position in the map, its corresponding value is updated
452
+ /// with `value`, and the older value is returned inside `Some(_)`. The returned index
453
+ /// will either be the given index or one less, depending on how the entry moved.
454
+ /// (See [`shift_insert`](Self::shift_insert) for different behavior here.)
455
+ ///
456
+ /// If no equivalent key existed in the map: the new key-value pair is
457
+ /// inserted exactly at the given index, and `None` is returned.
458
+ ///
459
+ /// ***Panics*** if `index` is out of bounds.
460
+ /// Valid indices are `0..=map.len()` (inclusive).
461
+ ///
462
+ /// Computes in **O(n)** time (average).
463
+ ///
464
+ /// See also [`entry`][Self::entry] if you want to insert *or* modify,
465
+ /// perhaps only using the index for new entries with [`VacantEntry::shift_insert`].
466
+ pub fn insert_before ( & mut self , mut index : usize , key : K , value : V ) -> ( usize , Option < V > ) {
467
+ assert ! ( index <= self . len( ) , "index out of bounds" ) ;
468
+ match self . entry ( key) {
469
+ Entry :: Occupied ( mut entry) => {
470
+ if index > entry. index ( ) {
471
+ // Some entries will shift down when this one moves up,
472
+ // so "insert before index" becomes "move to index - 1",
473
+ // keeping the entry at the original index unmoved.
474
+ index -= 1 ;
475
+ }
476
+ let old = mem:: replace ( entry. get_mut ( ) , value) ;
477
+ entry. move_index ( index) ;
478
+ ( index, Some ( old) )
479
+ }
480
+ Entry :: Vacant ( entry) => {
481
+ entry. shift_insert ( index, value) ;
482
+ ( index, None )
483
+ }
484
+ }
485
+ }
486
+
448
487
/// Insert a key-value pair in the map at the given index.
449
488
///
450
489
/// If an equivalent key already exists in the map: the key remains and
451
490
/// is moved to the given index in the map, its corresponding value is updated
452
491
/// with `value`, and the older value is returned inside `Some(_)`.
453
492
/// Note that existing entries **cannot** be moved to `index == map.len()`!
493
+ /// (See [`insert_before`](Self::insert_before) for different behavior here.)
454
494
///
455
495
/// If no equivalent key existed in the map: the new key-value pair is
456
496
/// inserted at the given index, and `None` is returned.
0 commit comments