@@ -414,6 +414,35 @@ where
414414 self . core . insert_full ( hash, key, value)
415415 }
416416
417+ /// Insert a key-value pair in the map at its ordered position among sorted keys.
418+ ///
419+ /// This is equivalent to finding the position with
420+ /// [`binary_search_keys`][Self::binary_search_keys], then either updating
421+ /// it or calling [`shift_insert`][Self::shift_insert] for a new key.
422+ ///
423+ /// If the sorted key is found in the map, its corresponding value is
424+ /// updated with `value`, and the older value is returned inside
425+ /// `(index, Some(_))`. Otherwise, the new key-value pair is inserted at
426+ /// the sorted position, and `(index, None)` is returned.
427+ ///
428+ /// If the existing keys are **not** already sorted, then the insertion
429+ /// index is unspecified (like [`slice::binary_search`]), but the key-value
430+ /// pair is moved to or inserted at that position regardless.
431+ ///
432+ /// Computes in **O(n)** time (average). Instead of repeating calls to
433+ /// `insert_sorted`, it may be faster to call batched [`insert`][Self::insert]
434+ /// or [`extend`][Self::extend] and only call [`sort_keys`][Self::sort_keys]
435+ /// or [`sort_unstable_keys`][Self::sort_unstable_keys] once.
436+ pub fn insert_sorted ( & mut self , key : K , value : V ) -> ( usize , Option < V > )
437+ where
438+ K : Ord ,
439+ {
440+ match self . binary_search_keys ( & key) {
441+ Ok ( i) => ( i, Some ( mem:: replace ( & mut self [ i] , value) ) ) ,
442+ Err ( i) => ( i, self . shift_insert ( i, key, value) ) ,
443+ }
444+ }
445+
417446 /// Insert a key-value pair in the map at the given index.
418447 ///
419448 /// If an equivalent key already exists in the map: the key remains and
@@ -788,6 +817,10 @@ impl<K, V, S> IndexMap<K, V, S> {
788817
789818 /// Sort the map’s key-value pairs by the default ordering of the keys.
790819 ///
820+ /// This is a stable sort -- but equivalent keys should not normally coexist in
821+ /// a map at all, so [`sort_unstable_keys`][Self::sort_unstable_keys] is preferred
822+ /// because it is generally faster and doesn't allocate auxiliary memory.
823+ ///
791824 /// See [`sort_by`](Self::sort_by) for details.
792825 pub fn sort_keys ( & mut self )
793826 where
0 commit comments