indexmap/
map.rs

1//! [`IndexMap`] is a hash table where the iteration order of the key-value
2//! pairs is independent of the hash values of the keys.
3
4mod entry;
5mod iter;
6mod mutable;
7mod slice;
8
9pub mod raw_entry_v1;
10
11#[cfg(feature = "serde")]
12#[cfg_attr(docsrs, doc(cfg(feature = "serde")))]
13pub mod serde_seq;
14
15#[cfg(test)]
16mod tests;
17
18pub use self::entry::{Entry, IndexedEntry};
19pub use crate::inner::{OccupiedEntry, VacantEntry};
20
21pub use self::iter::{
22    Drain, ExtractIf, IntoIter, IntoKeys, IntoValues, Iter, IterMut, IterMut2, Keys, Splice,
23    Values, ValuesMut,
24};
25pub use self::mutable::MutableEntryKey;
26pub use self::mutable::MutableKeys;
27pub use self::raw_entry_v1::RawEntryApiV1;
28pub use self::slice::Slice;
29
30#[cfg(feature = "rayon")]
31pub use crate::rayon::map as rayon;
32
33use alloc::boxed::Box;
34use alloc::vec::Vec;
35use core::cmp::Ordering;
36use core::fmt;
37use core::hash::{BuildHasher, Hash};
38use core::mem;
39use core::ops::{Index, IndexMut, RangeBounds};
40
41#[cfg(feature = "std")]
42use std::hash::RandomState;
43
44use crate::inner::Core;
45use crate::util::{third, try_simplify_range};
46use crate::{Bucket, Equivalent, GetDisjointMutError, HashValue, TryReserveError};
47
48/// A hash table where the iteration order of the key-value pairs is independent
49/// of the hash values of the keys.
50///
51/// The interface is closely compatible with the standard
52/// [`HashMap`][std::collections::HashMap],
53/// but also has additional features.
54///
55/// # Order
56///
57/// The key-value pairs have a consistent order that is determined by
58/// the sequence of insertion and removal calls on the map. The order does
59/// not depend on the keys or the hash function at all.
60///
61/// All iterators traverse the map in *the order*.
62///
63/// The insertion order is preserved, with **notable exceptions** like the
64/// [`.remove()`][Self::remove] or [`.swap_remove()`][Self::swap_remove] methods.
65/// Methods such as [`.sort_by()`][Self::sort_by] of
66/// course result in a new order, depending on the sorting order.
67///
68/// # Indices
69///
70/// The key-value pairs are indexed in a compact range without holes in the
71/// range `0..self.len()`. For example, the method `.get_full` looks up the
72/// index for a key, and the method `.get_index` looks up the key-value pair by
73/// index.
74///
75/// # Examples
76///
77/// ```
78/// use indexmap::IndexMap;
79///
80/// // count the frequency of each letter in a sentence.
81/// let mut letters = IndexMap::new();
82/// for ch in "a short treatise on fungi".chars() {
83///     *letters.entry(ch).or_insert(0) += 1;
84/// }
85///
86/// assert_eq!(letters[&'s'], 2);
87/// assert_eq!(letters[&'t'], 3);
88/// assert_eq!(letters[&'u'], 1);
89/// assert_eq!(letters.get(&'y'), None);
90/// ```
91#[cfg(feature = "std")]
92pub struct IndexMap<K, V, S = RandomState> {
93    pub(crate) core: Core<K, V>,
94    hash_builder: S,
95}
96#[cfg(not(feature = "std"))]
97pub struct IndexMap<K, V, S> {
98    pub(crate) core: Core<K, V>,
99    hash_builder: S,
100}
101
102impl<K, V, S> Clone for IndexMap<K, V, S>
103where
104    K: Clone,
105    V: Clone,
106    S: Clone,
107{
108    fn clone(&self) -> Self {
109        IndexMap {
110            core: self.core.clone(),
111            hash_builder: self.hash_builder.clone(),
112        }
113    }
114
115    fn clone_from(&mut self, other: &Self) {
116        self.core.clone_from(&other.core);
117        self.hash_builder.clone_from(&other.hash_builder);
118    }
119}
120
121impl<K, V, S> fmt::Debug for IndexMap<K, V, S>
122where
123    K: fmt::Debug,
124    V: fmt::Debug,
125{
126    #[cfg(not(feature = "test_debug"))]
127    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
128        f.debug_map().entries(self.iter()).finish()
129    }
130
131    #[cfg(feature = "test_debug")]
132    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
133        // Let the inner `Core` print all of its details
134        f.debug_struct("IndexMap")
135            .field("core", &self.core)
136            .finish()
137    }
138}
139
140#[cfg(feature = "std")]
141#[cfg_attr(docsrs, doc(cfg(feature = "std")))]
142impl<K, V> IndexMap<K, V> {
143    /// Create a new map. (Does not allocate.)
144    #[inline]
145    pub fn new() -> Self {
146        Self::with_capacity(0)
147    }
148
149    /// Create a new map with capacity for `n` key-value pairs. (Does not
150    /// allocate if `n` is zero.)
151    ///
152    /// Computes in **O(n)** time.
153    #[inline]
154    pub fn with_capacity(n: usize) -> Self {
155        Self::with_capacity_and_hasher(n, <_>::default())
156    }
157}
158
159impl<K, V, S> IndexMap<K, V, S> {
160    /// Create a new map with capacity for `n` key-value pairs. (Does not
161    /// allocate if `n` is zero.)
162    ///
163    /// Computes in **O(n)** time.
164    #[inline]
165    pub fn with_capacity_and_hasher(n: usize, hash_builder: S) -> Self {
166        if n == 0 {
167            Self::with_hasher(hash_builder)
168        } else {
169            IndexMap {
170                core: Core::with_capacity(n),
171                hash_builder,
172            }
173        }
174    }
175
176    /// Create a new map with `hash_builder`.
177    ///
178    /// This function is `const`, so it
179    /// can be called in `static` contexts.
180    pub const fn with_hasher(hash_builder: S) -> Self {
181        IndexMap {
182            core: Core::new(),
183            hash_builder,
184        }
185    }
186
187    #[inline]
188    pub(crate) fn into_entries(self) -> Vec<Bucket<K, V>> {
189        self.core.into_entries()
190    }
191
192    #[inline]
193    pub(crate) fn as_entries(&self) -> &[Bucket<K, V>] {
194        self.core.as_entries()
195    }
196
197    #[inline]
198    pub(crate) fn as_entries_mut(&mut self) -> &mut [Bucket<K, V>] {
199        self.core.as_entries_mut()
200    }
201
202    pub(crate) fn with_entries<F>(&mut self, f: F)
203    where
204        F: FnOnce(&mut [Bucket<K, V>]),
205    {
206        self.core.with_entries(f);
207    }
208
209    /// Return the number of elements the map can hold without reallocating.
210    ///
211    /// This number is a lower bound; the map might be able to hold more,
212    /// but is guaranteed to be able to hold at least this many.
213    ///
214    /// Computes in **O(1)** time.
215    pub fn capacity(&self) -> usize {
216        self.core.capacity()
217    }
218
219    /// Return a reference to the map's `BuildHasher`.
220    pub fn hasher(&self) -> &S {
221        &self.hash_builder
222    }
223
224    /// Return the number of key-value pairs in the map.
225    ///
226    /// Computes in **O(1)** time.
227    #[inline]
228    pub fn len(&self) -> usize {
229        self.core.len()
230    }
231
232    /// Returns true if the map contains no elements.
233    ///
234    /// Computes in **O(1)** time.
235    #[inline]
236    pub fn is_empty(&self) -> bool {
237        self.len() == 0
238    }
239
240    /// Return an iterator over the key-value pairs of the map, in their order
241    pub fn iter(&self) -> Iter<'_, K, V> {
242        Iter::new(self.as_entries())
243    }
244
245    /// Return an iterator over the key-value pairs of the map, in their order
246    pub fn iter_mut(&mut self) -> IterMut<'_, K, V> {
247        IterMut::new(self.as_entries_mut())
248    }
249
250    /// Return an iterator over the keys of the map, in their order
251    pub fn keys(&self) -> Keys<'_, K, V> {
252        Keys::new(self.as_entries())
253    }
254
255    /// Return an owning iterator over the keys of the map, in their order
256    pub fn into_keys(self) -> IntoKeys<K, V> {
257        IntoKeys::new(self.into_entries())
258    }
259
260    /// Return an iterator over the values of the map, in their order
261    pub fn values(&self) -> Values<'_, K, V> {
262        Values::new(self.as_entries())
263    }
264
265    /// Return an iterator over mutable references to the values of the map,
266    /// in their order
267    pub fn values_mut(&mut self) -> ValuesMut<'_, K, V> {
268        ValuesMut::new(self.as_entries_mut())
269    }
270
271    /// Return an owning iterator over the values of the map, in their order
272    pub fn into_values(self) -> IntoValues<K, V> {
273        IntoValues::new(self.into_entries())
274    }
275
276    /// Remove all key-value pairs in the map, while preserving its capacity.
277    ///
278    /// Computes in **O(n)** time.
279    pub fn clear(&mut self) {
280        self.core.clear();
281    }
282
283    /// Shortens the map, keeping the first `len` elements and dropping the rest.
284    ///
285    /// If `len` is greater than the map's current length, this has no effect.
286    pub fn truncate(&mut self, len: usize) {
287        self.core.truncate(len);
288    }
289
290    /// Clears the `IndexMap` in the given index range, returning those
291    /// key-value pairs as a drain iterator.
292    ///
293    /// The range may be any type that implements [`RangeBounds<usize>`],
294    /// including all of the `std::ops::Range*` types, or even a tuple pair of
295    /// `Bound` start and end values. To drain the map entirely, use `RangeFull`
296    /// like `map.drain(..)`.
297    ///
298    /// This shifts down all entries following the drained range to fill the
299    /// gap, and keeps the allocated memory for reuse.
300    ///
301    /// ***Panics*** if the starting point is greater than the end point or if
302    /// the end point is greater than the length of the map.
303    #[track_caller]
304    pub fn drain<R>(&mut self, range: R) -> Drain<'_, K, V>
305    where
306        R: RangeBounds<usize>,
307    {
308        Drain::new(self.core.drain(range))
309    }
310
311    /// Creates an iterator which uses a closure to determine if an element should be removed,
312    /// for all elements in the given range.
313    ///
314    /// If the closure returns true, the element is removed from the map and yielded.
315    /// If the closure returns false, or panics, the element remains in the map and will not be
316    /// yielded.
317    ///
318    /// Note that `extract_if` lets you mutate every value in the filter closure, regardless of
319    /// whether you choose to keep or remove it.
320    ///
321    /// The range may be any type that implements [`RangeBounds<usize>`],
322    /// including all of the `std::ops::Range*` types, or even a tuple pair of
323    /// `Bound` start and end values. To check the entire map, use `RangeFull`
324    /// like `map.extract_if(.., predicate)`.
325    ///
326    /// If the returned `ExtractIf` is not exhausted, e.g. because it is dropped without iterating
327    /// or the iteration short-circuits, then the remaining elements will be retained.
328    /// Use [`retain`] with a negated predicate if you do not need the returned iterator.
329    ///
330    /// [`retain`]: IndexMap::retain
331    ///
332    /// ***Panics*** if the starting point is greater than the end point or if
333    /// the end point is greater than the length of the map.
334    ///
335    /// # Examples
336    ///
337    /// Splitting a map into even and odd keys, reusing the original map:
338    ///
339    /// ```
340    /// use indexmap::IndexMap;
341    ///
342    /// let mut map: IndexMap<i32, i32> = (0..8).map(|x| (x, x)).collect();
343    /// let extracted: IndexMap<i32, i32> = map.extract_if(.., |k, _v| k % 2 == 0).collect();
344    ///
345    /// let evens = extracted.keys().copied().collect::<Vec<_>>();
346    /// let odds = map.keys().copied().collect::<Vec<_>>();
347    ///
348    /// assert_eq!(evens, vec![0, 2, 4, 6]);
349    /// assert_eq!(odds, vec![1, 3, 5, 7]);
350    /// ```
351    #[track_caller]
352    pub fn extract_if<F, R>(&mut self, range: R, pred: F) -> ExtractIf<'_, K, V, F>
353    where
354        F: FnMut(&K, &mut V) -> bool,
355        R: RangeBounds<usize>,
356    {
357        ExtractIf::new(&mut self.core, range, pred)
358    }
359
360    /// Splits the collection into two at the given index.
361    ///
362    /// Returns a newly allocated map containing the elements in the range
363    /// `[at, len)`. After the call, the original map will be left containing
364    /// the elements `[0, at)` with its previous capacity unchanged.
365    ///
366    /// ***Panics*** if `at > len`.
367    #[track_caller]
368    pub fn split_off(&mut self, at: usize) -> Self
369    where
370        S: Clone,
371    {
372        Self {
373            core: self.core.split_off(at),
374            hash_builder: self.hash_builder.clone(),
375        }
376    }
377
378    /// Reserve capacity for `additional` more key-value pairs.
379    ///
380    /// Computes in **O(n)** time.
381    pub fn reserve(&mut self, additional: usize) {
382        self.core.reserve(additional);
383    }
384
385    /// Reserve capacity for `additional` more key-value pairs, without over-allocating.
386    ///
387    /// Unlike `reserve`, this does not deliberately over-allocate the entry capacity to avoid
388    /// frequent re-allocations. However, the underlying data structures may still have internal
389    /// capacity requirements, and the allocator itself may give more space than requested, so this
390    /// cannot be relied upon to be precisely minimal.
391    ///
392    /// Computes in **O(n)** time.
393    pub fn reserve_exact(&mut self, additional: usize) {
394        self.core.reserve_exact(additional);
395    }
396
397    /// Try to reserve capacity for `additional` more key-value pairs.
398    ///
399    /// Computes in **O(n)** time.
400    pub fn try_reserve(&mut self, additional: usize) -> Result<(), TryReserveError> {
401        self.core.try_reserve(additional)
402    }
403
404    /// Try to reserve capacity for `additional` more key-value pairs, without over-allocating.
405    ///
406    /// Unlike `try_reserve`, this does not deliberately over-allocate the entry capacity to avoid
407    /// frequent re-allocations. However, the underlying data structures may still have internal
408    /// capacity requirements, and the allocator itself may give more space than requested, so this
409    /// cannot be relied upon to be precisely minimal.
410    ///
411    /// Computes in **O(n)** time.
412    pub fn try_reserve_exact(&mut self, additional: usize) -> Result<(), TryReserveError> {
413        self.core.try_reserve_exact(additional)
414    }
415
416    /// Shrink the capacity of the map as much as possible.
417    ///
418    /// Computes in **O(n)** time.
419    pub fn shrink_to_fit(&mut self) {
420        self.core.shrink_to(0);
421    }
422
423    /// Shrink the capacity of the map with a lower limit.
424    ///
425    /// Computes in **O(n)** time.
426    pub fn shrink_to(&mut self, min_capacity: usize) {
427        self.core.shrink_to(min_capacity);
428    }
429}
430
431impl<K, V, S> IndexMap<K, V, S>
432where
433    K: Hash + Eq,
434    S: BuildHasher,
435{
436    /// Insert a key-value pair in the map.
437    ///
438    /// If an equivalent key already exists in the map: the key remains and
439    /// retains in its place in the order, its corresponding value is updated
440    /// with `value`, and the older value is returned inside `Some(_)`.
441    ///
442    /// If no equivalent key existed in the map: the new key-value pair is
443    /// inserted, last in order, and `None` is returned.
444    ///
445    /// Computes in **O(1)** time (amortized average).
446    ///
447    /// See also [`entry`][Self::entry] if you want to insert *or* modify,
448    /// or [`insert_full`][Self::insert_full] if you need to get the index of
449    /// the corresponding key-value pair.
450    pub fn insert(&mut self, key: K, value: V) -> Option<V> {
451        self.insert_full(key, value).1
452    }
453
454    /// Insert a key-value pair in the map, and get their index.
455    ///
456    /// If an equivalent key already exists in the map: the key remains and
457    /// retains in its place in the order, its corresponding value is updated
458    /// with `value`, and the older value is returned inside `(index, Some(_))`.
459    ///
460    /// If no equivalent key existed in the map: the new key-value pair is
461    /// inserted, last in order, and `(index, None)` is returned.
462    ///
463    /// Computes in **O(1)** time (amortized average).
464    ///
465    /// See also [`entry`][Self::entry] if you want to insert *or* modify.
466    pub fn insert_full(&mut self, key: K, value: V) -> (usize, Option<V>) {
467        let hash = self.hash(&key);
468        self.core.insert_full(hash, key, value)
469    }
470
471    /// Insert a key-value pair in the map at its ordered position among sorted keys.
472    ///
473    /// This is equivalent to finding the position with
474    /// [`binary_search_keys`][Self::binary_search_keys], then either updating
475    /// it or calling [`insert_before`][Self::insert_before] for a new key.
476    ///
477    /// If the sorted key is found in the map, its corresponding value is
478    /// updated with `value`, and the older value is returned inside
479    /// `(index, Some(_))`. Otherwise, the new key-value pair is inserted at
480    /// the sorted position, and `(index, None)` is returned.
481    ///
482    /// If the existing keys are **not** already sorted, then the insertion
483    /// index is unspecified (like [`slice::binary_search`]), but the key-value
484    /// pair is moved to or inserted at that position regardless.
485    ///
486    /// Computes in **O(n)** time (average). Instead of repeating calls to
487    /// `insert_sorted`, it may be faster to call batched [`insert`][Self::insert]
488    /// or [`extend`][Self::extend] and only call [`sort_keys`][Self::sort_keys]
489    /// or [`sort_unstable_keys`][Self::sort_unstable_keys] once.
490    pub fn insert_sorted(&mut self, key: K, value: V) -> (usize, Option<V>)
491    where
492        K: Ord,
493    {
494        match self.binary_search_keys(&key) {
495            Ok(i) => (i, Some(mem::replace(&mut self[i], value))),
496            Err(i) => self.insert_before(i, key, value),
497        }
498    }
499
500    /// Insert a key-value pair in the map at its ordered position among keys
501    /// sorted by `cmp`.
502    ///
503    /// This is equivalent to finding the position with
504    /// [`binary_search_by`][Self::binary_search_by], then calling
505    /// [`insert_before`][Self::insert_before] with the given key and value.
506    ///
507    /// If the existing keys are **not** already sorted, then the insertion
508    /// index is unspecified (like [`slice::binary_search`]), but the key-value
509    /// pair is moved to or inserted at that position regardless.
510    ///
511    /// Computes in **O(n)** time (average).
512    pub fn insert_sorted_by<F>(&mut self, key: K, value: V, mut cmp: F) -> (usize, Option<V>)
513    where
514        F: FnMut(&K, &V, &K, &V) -> Ordering,
515    {
516        let (Ok(i) | Err(i)) = self.binary_search_by(|k, v| cmp(k, v, &key, &value));
517        self.insert_before(i, key, value)
518    }
519
520    /// Insert a key-value pair in the map at its ordered position
521    /// using a sort-key extraction function.
522    ///
523    /// This is equivalent to finding the position with
524    /// [`binary_search_by_key`][Self::binary_search_by_key] with `sort_key(key)`, then
525    /// calling [`insert_before`][Self::insert_before] with the given key and value.
526    ///
527    /// If the existing keys are **not** already sorted, then the insertion
528    /// index is unspecified (like [`slice::binary_search`]), but the key-value
529    /// pair is moved to or inserted at that position regardless.
530    ///
531    /// Computes in **O(n)** time (average).
532    pub fn insert_sorted_by_key<B, F>(
533        &mut self,
534        key: K,
535        value: V,
536        mut sort_key: F,
537    ) -> (usize, Option<V>)
538    where
539        B: Ord,
540        F: FnMut(&K, &V) -> B,
541    {
542        let search_key = sort_key(&key, &value);
543        let (Ok(i) | Err(i)) = self.binary_search_by_key(&search_key, sort_key);
544        self.insert_before(i, key, value)
545    }
546
547    /// Insert a key-value pair in the map before the entry at the given index, or at the end.
548    ///
549    /// If an equivalent key already exists in the map: the key remains and
550    /// is moved to the new position in the map, its corresponding value is updated
551    /// with `value`, and the older value is returned inside `Some(_)`. The returned index
552    /// will either be the given index or one less, depending on how the entry moved.
553    /// (See [`shift_insert`](Self::shift_insert) for different behavior here.)
554    ///
555    /// If no equivalent key existed in the map: the new key-value pair is
556    /// inserted exactly at the given index, and `None` is returned.
557    ///
558    /// ***Panics*** if `index` is out of bounds.
559    /// Valid indices are `0..=map.len()` (inclusive).
560    ///
561    /// Computes in **O(n)** time (average).
562    ///
563    /// See also [`entry`][Self::entry] if you want to insert *or* modify,
564    /// perhaps only using the index for new entries with [`VacantEntry::shift_insert`].
565    ///
566    /// # Examples
567    ///
568    /// ```
569    /// use indexmap::IndexMap;
570    /// let mut map: IndexMap<char, ()> = ('a'..='z').map(|c| (c, ())).collect();
571    ///
572    /// // The new key '*' goes exactly at the given index.
573    /// assert_eq!(map.get_index_of(&'*'), None);
574    /// assert_eq!(map.insert_before(10, '*', ()), (10, None));
575    /// assert_eq!(map.get_index_of(&'*'), Some(10));
576    ///
577    /// // Moving the key 'a' up will shift others down, so this moves *before* 10 to index 9.
578    /// assert_eq!(map.insert_before(10, 'a', ()), (9, Some(())));
579    /// assert_eq!(map.get_index_of(&'a'), Some(9));
580    /// assert_eq!(map.get_index_of(&'*'), Some(10));
581    ///
582    /// // Moving the key 'z' down will shift others up, so this moves to exactly 10.
583    /// assert_eq!(map.insert_before(10, 'z', ()), (10, Some(())));
584    /// assert_eq!(map.get_index_of(&'z'), Some(10));
585    /// assert_eq!(map.get_index_of(&'*'), Some(11));
586    ///
587    /// // Moving or inserting before the endpoint is also valid.
588    /// assert_eq!(map.len(), 27);
589    /// assert_eq!(map.insert_before(map.len(), '*', ()), (26, Some(())));
590    /// assert_eq!(map.get_index_of(&'*'), Some(26));
591    /// assert_eq!(map.insert_before(map.len(), '+', ()), (27, None));
592    /// assert_eq!(map.get_index_of(&'+'), Some(27));
593    /// assert_eq!(map.len(), 28);
594    /// ```
595    #[track_caller]
596    pub fn insert_before(&mut self, mut index: usize, key: K, value: V) -> (usize, Option<V>) {
597        let len = self.len();
598
599        assert!(
600            index <= len,
601            "index out of bounds: the len is {len} but the index is {index}. Expected index <= len"
602        );
603
604        match self.entry(key) {
605            Entry::Occupied(mut entry) => {
606                if index > entry.index() {
607                    // Some entries will shift down when this one moves up,
608                    // so "insert before index" becomes "move to index - 1",
609                    // keeping the entry at the original index unmoved.
610                    index -= 1;
611                }
612                let old = mem::replace(entry.get_mut(), value);
613                entry.move_index(index);
614                (index, Some(old))
615            }
616            Entry::Vacant(entry) => {
617                entry.shift_insert(index, value);
618                (index, None)
619            }
620        }
621    }
622
623    /// Insert a key-value pair in the map at the given index.
624    ///
625    /// If an equivalent key already exists in the map: the key remains and
626    /// is moved to the given index in the map, its corresponding value is updated
627    /// with `value`, and the older value is returned inside `Some(_)`.
628    /// Note that existing entries **cannot** be moved to `index == map.len()`!
629    /// (See [`insert_before`](Self::insert_before) for different behavior here.)
630    ///
631    /// If no equivalent key existed in the map: the new key-value pair is
632    /// inserted at the given index, and `None` is returned.
633    ///
634    /// ***Panics*** if `index` is out of bounds.
635    /// Valid indices are `0..map.len()` (exclusive) when moving an existing entry, or
636    /// `0..=map.len()` (inclusive) when inserting a new key.
637    ///
638    /// Computes in **O(n)** time (average).
639    ///
640    /// See also [`entry`][Self::entry] if you want to insert *or* modify,
641    /// perhaps only using the index for new entries with [`VacantEntry::shift_insert`].
642    ///
643    /// # Examples
644    ///
645    /// ```
646    /// use indexmap::IndexMap;
647    /// let mut map: IndexMap<char, ()> = ('a'..='z').map(|c| (c, ())).collect();
648    ///
649    /// // The new key '*' goes exactly at the given index.
650    /// assert_eq!(map.get_index_of(&'*'), None);
651    /// assert_eq!(map.shift_insert(10, '*', ()), None);
652    /// assert_eq!(map.get_index_of(&'*'), Some(10));
653    ///
654    /// // Moving the key 'a' up to 10 will shift others down, including the '*' that was at 10.
655    /// assert_eq!(map.shift_insert(10, 'a', ()), Some(()));
656    /// assert_eq!(map.get_index_of(&'a'), Some(10));
657    /// assert_eq!(map.get_index_of(&'*'), Some(9));
658    ///
659    /// // Moving the key 'z' down to 9 will shift others up, including the '*' that was at 9.
660    /// assert_eq!(map.shift_insert(9, 'z', ()), Some(()));
661    /// assert_eq!(map.get_index_of(&'z'), Some(9));
662    /// assert_eq!(map.get_index_of(&'*'), Some(10));
663    ///
664    /// // Existing keys can move to len-1 at most, but new keys can insert at the endpoint.
665    /// assert_eq!(map.len(), 27);
666    /// assert_eq!(map.shift_insert(map.len() - 1, '*', ()), Some(()));
667    /// assert_eq!(map.get_index_of(&'*'), Some(26));
668    /// assert_eq!(map.shift_insert(map.len(), '+', ()), None);
669    /// assert_eq!(map.get_index_of(&'+'), Some(27));
670    /// assert_eq!(map.len(), 28);
671    /// ```
672    ///
673    /// ```should_panic
674    /// use indexmap::IndexMap;
675    /// let mut map: IndexMap<char, ()> = ('a'..='z').map(|c| (c, ())).collect();
676    ///
677    /// // This is an invalid index for moving an existing key!
678    /// map.shift_insert(map.len(), 'a', ());
679    /// ```
680    #[track_caller]
681    pub fn shift_insert(&mut self, index: usize, key: K, value: V) -> Option<V> {
682        let len = self.len();
683        match self.entry(key) {
684            Entry::Occupied(mut entry) => {
685                assert!(
686                    index < len,
687                    "index out of bounds: the len is {len} but the index is {index}"
688                );
689
690                let old = mem::replace(entry.get_mut(), value);
691                entry.move_index(index);
692                Some(old)
693            }
694            Entry::Vacant(entry) => {
695                assert!(
696                    index <= len,
697                    "index out of bounds: the len is {len} but the index is {index}. Expected index <= len"
698                );
699
700                entry.shift_insert(index, value);
701                None
702            }
703        }
704    }
705
706    /// Replaces the key at the given index. The new key does not need to be
707    /// equivalent to the one it is replacing, but it must be unique to the rest
708    /// of the map.
709    ///
710    /// Returns `Ok(old_key)` if successful, or `Err((other_index, key))` if an
711    /// equivalent key already exists at a different index. The map will be
712    /// unchanged in the error case.
713    ///
714    /// Direct indexing can be used to change the corresponding value: simply
715    /// `map[index] = value`, or `mem::replace(&mut map[index], value)` to
716    /// retrieve the old value as well.
717    ///
718    /// ***Panics*** if `index` is out of bounds.
719    ///
720    /// Computes in **O(1)** time (average).
721    #[track_caller]
722    pub fn replace_index(&mut self, index: usize, key: K) -> Result<K, (usize, K)> {
723        // If there's a direct match, we don't even need to hash it.
724        let entry = &mut self.as_entries_mut()[index];
725        if key == entry.key {
726            return Ok(mem::replace(&mut entry.key, key));
727        }
728
729        let hash = self.hash(&key);
730        if let Some(i) = self.core.get_index_of(hash, &key) {
731            debug_assert_ne!(i, index);
732            return Err((i, key));
733        }
734        Ok(self.core.replace_index_unique(index, hash, key))
735    }
736
737    /// Get the given key's corresponding entry in the map for insertion and/or
738    /// in-place manipulation.
739    ///
740    /// Computes in **O(1)** time (amortized average).
741    pub fn entry(&mut self, key: K) -> Entry<'_, K, V> {
742        let hash = self.hash(&key);
743        Entry::new(&mut self.core, hash, key)
744    }
745
746    /// Creates a splicing iterator that replaces the specified range in the map
747    /// with the given `replace_with` key-value iterator and yields the removed
748    /// items. `replace_with` does not need to be the same length as `range`.
749    ///
750    /// The `range` is removed even if the iterator is not consumed until the
751    /// end. It is unspecified how many elements are removed from the map if the
752    /// `Splice` value is leaked.
753    ///
754    /// The input iterator `replace_with` is only consumed when the `Splice`
755    /// value is dropped. If a key from the iterator matches an existing entry
756    /// in the map (outside of `range`), then the value will be updated in that
757    /// position. Otherwise, the new key-value pair will be inserted in the
758    /// replaced `range`.
759    ///
760    /// ***Panics*** if the starting point is greater than the end point or if
761    /// the end point is greater than the length of the map.
762    ///
763    /// # Examples
764    ///
765    /// ```
766    /// use indexmap::IndexMap;
767    ///
768    /// let mut map = IndexMap::from([(0, '_'), (1, 'a'), (2, 'b'), (3, 'c'), (4, 'd')]);
769    /// let new = [(5, 'E'), (4, 'D'), (3, 'C'), (2, 'B'), (1, 'A')];
770    /// let removed: Vec<_> = map.splice(2..4, new).collect();
771    ///
772    /// // 1 and 4 got new values, while 5, 3, and 2 were newly inserted.
773    /// assert!(map.into_iter().eq([(0, '_'), (1, 'A'), (5, 'E'), (3, 'C'), (2, 'B'), (4, 'D')]));
774    /// assert_eq!(removed, &[(2, 'b'), (3, 'c')]);
775    /// ```
776    #[track_caller]
777    pub fn splice<R, I>(&mut self, range: R, replace_with: I) -> Splice<'_, I::IntoIter, K, V, S>
778    where
779        R: RangeBounds<usize>,
780        I: IntoIterator<Item = (K, V)>,
781    {
782        Splice::new(self, range, replace_with.into_iter())
783    }
784
785    /// Moves all key-value pairs from `other` into `self`, leaving `other` empty.
786    ///
787    /// This is equivalent to calling [`insert`][Self::insert] for each
788    /// key-value pair from `other` in order, which means that for keys that
789    /// already exist in `self`, their value is updated in the current position.
790    ///
791    /// # Examples
792    ///
793    /// ```
794    /// use indexmap::IndexMap;
795    ///
796    /// // Note: Key (3) is present in both maps.
797    /// let mut a = IndexMap::from([(3, "c"), (2, "b"), (1, "a")]);
798    /// let mut b = IndexMap::from([(3, "d"), (4, "e"), (5, "f")]);
799    /// let old_capacity = b.capacity();
800    ///
801    /// a.append(&mut b);
802    ///
803    /// assert_eq!(a.len(), 5);
804    /// assert_eq!(b.len(), 0);
805    /// assert_eq!(b.capacity(), old_capacity);
806    ///
807    /// assert!(a.keys().eq(&[3, 2, 1, 4, 5]));
808    /// assert_eq!(a[&3], "d"); // "c" was overwritten.
809    /// ```
810    pub fn append<S2>(&mut self, other: &mut IndexMap<K, V, S2>) {
811        self.extend(other.drain(..));
812    }
813}
814
815impl<K, V, S> IndexMap<K, V, S>
816where
817    S: BuildHasher,
818{
819    pub(crate) fn hash<Q: ?Sized + Hash>(&self, key: &Q) -> HashValue {
820        let h = self.hash_builder.hash_one(key);
821        HashValue(h as usize)
822    }
823
824    /// Return `true` if an equivalent to `key` exists in the map.
825    ///
826    /// Computes in **O(1)** time (average).
827    pub fn contains_key<Q>(&self, key: &Q) -> bool
828    where
829        Q: ?Sized + Hash + Equivalent<K>,
830    {
831        self.get_index_of(key).is_some()
832    }
833
834    /// Return a reference to the stored value for `key`, if it is present,
835    /// else `None`.
836    ///
837    /// Computes in **O(1)** time (average).
838    pub fn get<Q>(&self, key: &Q) -> Option<&V>
839    where
840        Q: ?Sized + Hash + Equivalent<K>,
841    {
842        if let Some(i) = self.get_index_of(key) {
843            let entry = &self.as_entries()[i];
844            Some(&entry.value)
845        } else {
846            None
847        }
848    }
849
850    /// Return references to the stored key-value pair for the lookup `key`,
851    /// if it is present, else `None`.
852    ///
853    /// Computes in **O(1)** time (average).
854    pub fn get_key_value<Q>(&self, key: &Q) -> Option<(&K, &V)>
855    where
856        Q: ?Sized + Hash + Equivalent<K>,
857    {
858        if let Some(i) = self.get_index_of(key) {
859            let entry = &self.as_entries()[i];
860            Some((&entry.key, &entry.value))
861        } else {
862            None
863        }
864    }
865
866    /// Return the index with references to the stored key-value pair for the
867    /// lookup `key`, if it is present, else `None`.
868    ///
869    /// Computes in **O(1)** time (average).
870    pub fn get_full<Q>(&self, key: &Q) -> Option<(usize, &K, &V)>
871    where
872        Q: ?Sized + Hash + Equivalent<K>,
873    {
874        if let Some(i) = self.get_index_of(key) {
875            let entry = &self.as_entries()[i];
876            Some((i, &entry.key, &entry.value))
877        } else {
878            None
879        }
880    }
881
882    /// Return the item index for `key`, if it is present, else `None`.
883    ///
884    /// Computes in **O(1)** time (average).
885    pub fn get_index_of<Q>(&self, key: &Q) -> Option<usize>
886    where
887        Q: ?Sized + Hash + Equivalent<K>,
888    {
889        match self.as_entries() {
890            [] => None,
891            [x] => key.equivalent(&x.key).then_some(0),
892            _ => {
893                let hash = self.hash(key);
894                self.core.get_index_of(hash, key)
895            }
896        }
897    }
898
899    /// Return a mutable reference to the stored value for `key`,
900    /// if it is present, else `None`.
901    ///
902    /// Computes in **O(1)** time (average).
903    pub fn get_mut<Q>(&mut self, key: &Q) -> Option<&mut V>
904    where
905        Q: ?Sized + Hash + Equivalent<K>,
906    {
907        if let Some(i) = self.get_index_of(key) {
908            let entry = &mut self.as_entries_mut()[i];
909            Some(&mut entry.value)
910        } else {
911            None
912        }
913    }
914
915    /// Return a reference and mutable references to the stored key-value pair
916    /// for the lookup `key`, if it is present, else `None`.
917    ///
918    /// Computes in **O(1)** time (average).
919    pub fn get_key_value_mut<Q>(&mut self, key: &Q) -> Option<(&K, &mut V)>
920    where
921        Q: ?Sized + Hash + Equivalent<K>,
922    {
923        if let Some(i) = self.get_index_of(key) {
924            let entry = &mut self.as_entries_mut()[i];
925            Some((&entry.key, &mut entry.value))
926        } else {
927            None
928        }
929    }
930
931    /// Return the index with a reference and mutable reference to the stored
932    /// key-value pair for the lookup `key`, if it is present, else `None`.
933    ///
934    /// Computes in **O(1)** time (average).
935    pub fn get_full_mut<Q>(&mut self, key: &Q) -> Option<(usize, &K, &mut V)>
936    where
937        Q: ?Sized + Hash + Equivalent<K>,
938    {
939        if let Some(i) = self.get_index_of(key) {
940            let entry = &mut self.as_entries_mut()[i];
941            Some((i, &entry.key, &mut entry.value))
942        } else {
943            None
944        }
945    }
946
947    /// Return the values for `N` keys. If any key is duplicated, this function will panic.
948    ///
949    /// # Examples
950    ///
951    /// ```
952    /// let mut map = indexmap::IndexMap::from([(1, 'a'), (3, 'b'), (2, 'c')]);
953    /// assert_eq!(map.get_disjoint_mut([&2, &1]), [Some(&mut 'c'), Some(&mut 'a')]);
954    /// ```
955    pub fn get_disjoint_mut<Q, const N: usize>(&mut self, keys: [&Q; N]) -> [Option<&mut V>; N]
956    where
957        Q: ?Sized + Hash + Equivalent<K>,
958    {
959        let indices = keys.map(|key| self.get_index_of(key));
960        match self.as_mut_slice().get_disjoint_opt_mut(indices) {
961            Err(GetDisjointMutError::IndexOutOfBounds) => {
962                unreachable!(
963                    "Internal error: indices should never be OOB as we got them from get_index_of"
964                );
965            }
966            Err(GetDisjointMutError::OverlappingIndices) => {
967                panic!("duplicate keys found");
968            }
969            Ok(key_values) => key_values.map(|kv_opt| kv_opt.map(|kv| kv.1)),
970        }
971    }
972
973    /// Remove the key-value pair equivalent to `key` and return
974    /// its value.
975    ///
976    /// **NOTE:** This is equivalent to [`.swap_remove(key)`][Self::swap_remove], replacing this
977    /// entry's position with the last element, and it is deprecated in favor of calling that
978    /// explicitly. If you need to preserve the relative order of the keys in the map, use
979    /// [`.shift_remove(key)`][Self::shift_remove] instead.
980    #[deprecated(note = "`remove` disrupts the map order -- \
981        use `swap_remove` or `shift_remove` for explicit behavior.")]
982    pub fn remove<Q>(&mut self, key: &Q) -> Option<V>
983    where
984        Q: ?Sized + Hash + Equivalent<K>,
985    {
986        self.swap_remove(key)
987    }
988
989    /// Remove and return the key-value pair equivalent to `key`.
990    ///
991    /// **NOTE:** This is equivalent to [`.swap_remove_entry(key)`][Self::swap_remove_entry],
992    /// replacing this entry's position with the last element, and it is deprecated in favor of
993    /// calling that explicitly. If you need to preserve the relative order of the keys in the map,
994    /// use [`.shift_remove_entry(key)`][Self::shift_remove_entry] instead.
995    #[deprecated(note = "`remove_entry` disrupts the map order -- \
996        use `swap_remove_entry` or `shift_remove_entry` for explicit behavior.")]
997    pub fn remove_entry<Q>(&mut self, key: &Q) -> Option<(K, V)>
998    where
999        Q: ?Sized + Hash + Equivalent<K>,
1000    {
1001        self.swap_remove_entry(key)
1002    }
1003
1004    /// Remove the key-value pair equivalent to `key` and return
1005    /// its value.
1006    ///
1007    /// Like [`Vec::swap_remove`], the pair is removed by swapping it with the
1008    /// last element of the map and popping it off. **This perturbs
1009    /// the position of what used to be the last element!**
1010    ///
1011    /// Return `None` if `key` is not in map.
1012    ///
1013    /// Computes in **O(1)** time (average).
1014    pub fn swap_remove<Q>(&mut self, key: &Q) -> Option<V>
1015    where
1016        Q: ?Sized + Hash + Equivalent<K>,
1017    {
1018        self.swap_remove_full(key).map(third)
1019    }
1020
1021    /// Remove and return the key-value pair equivalent to `key`.
1022    ///
1023    /// Like [`Vec::swap_remove`], the pair is removed by swapping it with the
1024    /// last element of the map and popping it off. **This perturbs
1025    /// the position of what used to be the last element!**
1026    ///
1027    /// Return `None` if `key` is not in map.
1028    ///
1029    /// Computes in **O(1)** time (average).
1030    pub fn swap_remove_entry<Q>(&mut self, key: &Q) -> Option<(K, V)>
1031    where
1032        Q: ?Sized + Hash + Equivalent<K>,
1033    {
1034        match self.swap_remove_full(key) {
1035            Some((_, key, value)) => Some((key, value)),
1036            None => None,
1037        }
1038    }
1039
1040    /// Remove the key-value pair equivalent to `key` and return it and
1041    /// the index it had.
1042    ///
1043    /// Like [`Vec::swap_remove`], the pair is removed by swapping it with the
1044    /// last element of the map and popping it off. **This perturbs
1045    /// the position of what used to be the last element!**
1046    ///
1047    /// Return `None` if `key` is not in map.
1048    ///
1049    /// Computes in **O(1)** time (average).
1050    pub fn swap_remove_full<Q>(&mut self, key: &Q) -> Option<(usize, K, V)>
1051    where
1052        Q: ?Sized + Hash + Equivalent<K>,
1053    {
1054        match self.as_entries() {
1055            [x] if key.equivalent(&x.key) => {
1056                let (k, v) = self.core.pop()?;
1057                Some((0, k, v))
1058            }
1059            [_] | [] => None,
1060            _ => {
1061                let hash = self.hash(key);
1062                self.core.swap_remove_full(hash, key)
1063            }
1064        }
1065    }
1066
1067    /// Remove the key-value pair equivalent to `key` and return
1068    /// its value.
1069    ///
1070    /// Like [`Vec::remove`], the pair is removed by shifting all of the
1071    /// elements that follow it, preserving their relative order.
1072    /// **This perturbs the index of all of those elements!**
1073    ///
1074    /// Return `None` if `key` is not in map.
1075    ///
1076    /// Computes in **O(n)** time (average).
1077    pub fn shift_remove<Q>(&mut self, key: &Q) -> Option<V>
1078    where
1079        Q: ?Sized + Hash + Equivalent<K>,
1080    {
1081        self.shift_remove_full(key).map(third)
1082    }
1083
1084    /// Remove and return the key-value pair equivalent to `key`.
1085    ///
1086    /// Like [`Vec::remove`], the pair is removed by shifting all of the
1087    /// elements that follow it, preserving their relative order.
1088    /// **This perturbs the index of all of those elements!**
1089    ///
1090    /// Return `None` if `key` is not in map.
1091    ///
1092    /// Computes in **O(n)** time (average).
1093    pub fn shift_remove_entry<Q>(&mut self, key: &Q) -> Option<(K, V)>
1094    where
1095        Q: ?Sized + Hash + Equivalent<K>,
1096    {
1097        match self.shift_remove_full(key) {
1098            Some((_, key, value)) => Some((key, value)),
1099            None => None,
1100        }
1101    }
1102
1103    /// Remove the key-value pair equivalent to `key` and return it and
1104    /// the index it had.
1105    ///
1106    /// Like [`Vec::remove`], the pair is removed by shifting all of the
1107    /// elements that follow it, preserving their relative order.
1108    /// **This perturbs the index of all of those elements!**
1109    ///
1110    /// Return `None` if `key` is not in map.
1111    ///
1112    /// Computes in **O(n)** time (average).
1113    pub fn shift_remove_full<Q>(&mut self, key: &Q) -> Option<(usize, K, V)>
1114    where
1115        Q: ?Sized + Hash + Equivalent<K>,
1116    {
1117        match self.as_entries() {
1118            [x] if key.equivalent(&x.key) => {
1119                let (k, v) = self.core.pop()?;
1120                Some((0, k, v))
1121            }
1122            [_] | [] => None,
1123            _ => {
1124                let hash = self.hash(key);
1125                self.core.shift_remove_full(hash, key)
1126            }
1127        }
1128    }
1129}
1130
1131impl<K, V, S> IndexMap<K, V, S> {
1132    /// Remove the last key-value pair
1133    ///
1134    /// This preserves the order of the remaining elements.
1135    ///
1136    /// Computes in **O(1)** time (average).
1137    #[doc(alias = "pop_last")] // like `BTreeMap`
1138    pub fn pop(&mut self) -> Option<(K, V)> {
1139        self.core.pop()
1140    }
1141
1142    /// Removes and returns the last key-value pair from a map if the predicate
1143    /// returns `true`, or [`None`] if the predicate returns false or the map
1144    /// is empty (the predicate will not be called in that case).
1145    ///
1146    /// This preserves the order of the remaining elements.
1147    ///
1148    /// Computes in **O(1)** time (average).
1149    ///
1150    /// # Examples
1151    ///
1152    /// ```
1153    /// use indexmap::IndexMap;
1154    ///
1155    /// let init = [(1, 'a'), (2, 'b'), (3, 'c'), (4, 'd')];
1156    /// let mut map = IndexMap::from(init);
1157    /// let pred = |key: &i32, _value: &mut char| *key % 2 == 0;
1158    ///
1159    /// assert_eq!(map.pop_if(pred), Some((4, 'd')));
1160    /// assert_eq!(map.as_slice(), &init[..3]);
1161    /// assert_eq!(map.pop_if(pred), None);
1162    /// ```
1163    pub fn pop_if(&mut self, predicate: impl FnOnce(&K, &mut V) -> bool) -> Option<(K, V)> {
1164        let (last_key, last_value) = self.last_mut()?;
1165        if predicate(last_key, last_value) {
1166            self.core.pop()
1167        } else {
1168            None
1169        }
1170    }
1171
1172    /// Scan through each key-value pair in the map and keep those where the
1173    /// closure `keep` returns `true`.
1174    ///
1175    /// The elements are visited in order, and remaining elements keep their
1176    /// order.
1177    ///
1178    /// Computes in **O(n)** time (average).
1179    pub fn retain<F>(&mut self, mut keep: F)
1180    where
1181        F: FnMut(&K, &mut V) -> bool,
1182    {
1183        self.core.retain_in_order(move |k, v| keep(k, v));
1184    }
1185
1186    /// Sort the map's key-value pairs by the default ordering of the keys.
1187    ///
1188    /// This is a stable sort -- but equivalent keys should not normally coexist in
1189    /// a map at all, so [`sort_unstable_keys`][Self::sort_unstable_keys] is preferred
1190    /// because it is generally faster and doesn't allocate auxiliary memory.
1191    ///
1192    /// See [`sort_by`](Self::sort_by) for details.
1193    pub fn sort_keys(&mut self)
1194    where
1195        K: Ord,
1196    {
1197        self.with_entries(move |entries| {
1198            entries.sort_by(move |a, b| K::cmp(&a.key, &b.key));
1199        });
1200    }
1201
1202    /// Sort the map's key-value pairs in place using the comparison
1203    /// function `cmp`.
1204    ///
1205    /// The comparison function receives two key and value pairs to compare (you
1206    /// can sort by keys or values or their combination as needed).
1207    ///
1208    /// Computes in **O(n log n + c)** time and **O(n)** space where *n* is
1209    /// the length of the map and *c* the capacity. The sort is stable.
1210    pub fn sort_by<F>(&mut self, mut cmp: F)
1211    where
1212        F: FnMut(&K, &V, &K, &V) -> Ordering,
1213    {
1214        self.with_entries(move |entries| {
1215            entries.sort_by(move |a, b| cmp(&a.key, &a.value, &b.key, &b.value));
1216        });
1217    }
1218
1219    /// Sort the key-value pairs of the map and return a by-value iterator of
1220    /// the key-value pairs with the result.
1221    ///
1222    /// The sort is stable.
1223    pub fn sorted_by<F>(self, mut cmp: F) -> IntoIter<K, V>
1224    where
1225        F: FnMut(&K, &V, &K, &V) -> Ordering,
1226    {
1227        let mut entries = self.into_entries();
1228        entries.sort_by(move |a, b| cmp(&a.key, &a.value, &b.key, &b.value));
1229        IntoIter::new(entries)
1230    }
1231
1232    /// Sort the map's key-value pairs in place using a sort-key extraction function.
1233    ///
1234    /// Computes in **O(n log n + c)** time and **O(n)** space where *n* is
1235    /// the length of the map and *c* the capacity. The sort is stable.
1236    pub fn sort_by_key<T, F>(&mut self, mut sort_key: F)
1237    where
1238        T: Ord,
1239        F: FnMut(&K, &V) -> T,
1240    {
1241        self.with_entries(move |entries| {
1242            entries.sort_by_key(move |a| sort_key(&a.key, &a.value));
1243        });
1244    }
1245
1246    /// Sort the map's key-value pairs by the default ordering of the keys, but
1247    /// may not preserve the order of equal elements.
1248    ///
1249    /// See [`sort_unstable_by`](Self::sort_unstable_by) for details.
1250    pub fn sort_unstable_keys(&mut self)
1251    where
1252        K: Ord,
1253    {
1254        self.with_entries(move |entries| {
1255            entries.sort_unstable_by(move |a, b| K::cmp(&a.key, &b.key));
1256        });
1257    }
1258
1259    /// Sort the map's key-value pairs in place using the comparison function `cmp`, but
1260    /// may not preserve the order of equal elements.
1261    ///
1262    /// The comparison function receives two key and value pairs to compare (you
1263    /// can sort by keys or values or their combination as needed).
1264    ///
1265    /// Computes in **O(n log n + c)** time where *n* is
1266    /// the length of the map and *c* is the capacity. The sort is unstable.
1267    pub fn sort_unstable_by<F>(&mut self, mut cmp: F)
1268    where
1269        F: FnMut(&K, &V, &K, &V) -> Ordering,
1270    {
1271        self.with_entries(move |entries| {
1272            entries.sort_unstable_by(move |a, b| cmp(&a.key, &a.value, &b.key, &b.value));
1273        });
1274    }
1275
1276    /// Sort the key-value pairs of the map and return a by-value iterator of
1277    /// the key-value pairs with the result.
1278    ///
1279    /// The sort is unstable.
1280    #[inline]
1281    pub fn sorted_unstable_by<F>(self, mut cmp: F) -> IntoIter<K, V>
1282    where
1283        F: FnMut(&K, &V, &K, &V) -> Ordering,
1284    {
1285        let mut entries = self.into_entries();
1286        entries.sort_unstable_by(move |a, b| cmp(&a.key, &a.value, &b.key, &b.value));
1287        IntoIter::new(entries)
1288    }
1289
1290    /// Sort the map's key-value pairs in place using a sort-key extraction function.
1291    ///
1292    /// Computes in **O(n log n + c)** time where *n* is
1293    /// the length of the map and *c* is the capacity. The sort is unstable.
1294    pub fn sort_unstable_by_key<T, F>(&mut self, mut sort_key: F)
1295    where
1296        T: Ord,
1297        F: FnMut(&K, &V) -> T,
1298    {
1299        self.with_entries(move |entries| {
1300            entries.sort_unstable_by_key(move |a| sort_key(&a.key, &a.value));
1301        });
1302    }
1303
1304    /// Sort the map's key-value pairs in place using a sort-key extraction function.
1305    ///
1306    /// During sorting, the function is called at most once per entry, by using temporary storage
1307    /// to remember the results of its evaluation. The order of calls to the function is
1308    /// unspecified and may change between versions of `indexmap` or the standard library.
1309    ///
1310    /// Computes in **O(m n + n log n + c)** time () and **O(n)** space, where the function is
1311    /// **O(m)**, *n* is the length of the map, and *c* the capacity. The sort is stable.
1312    pub fn sort_by_cached_key<T, F>(&mut self, mut sort_key: F)
1313    where
1314        T: Ord,
1315        F: FnMut(&K, &V) -> T,
1316    {
1317        self.with_entries(move |entries| {
1318            entries.sort_by_cached_key(move |a| sort_key(&a.key, &a.value));
1319        });
1320    }
1321
1322    /// Search over a sorted map for a key.
1323    ///
1324    /// Returns the position where that key is present, or the position where it can be inserted to
1325    /// maintain the sort. See [`slice::binary_search`] for more details.
1326    ///
1327    /// Computes in **O(log(n))** time, which is notably less scalable than looking the key up
1328    /// using [`get_index_of`][IndexMap::get_index_of], but this can also position missing keys.
1329    pub fn binary_search_keys(&self, x: &K) -> Result<usize, usize>
1330    where
1331        K: Ord,
1332    {
1333        self.as_slice().binary_search_keys(x)
1334    }
1335
1336    /// Search over a sorted map with a comparator function.
1337    ///
1338    /// Returns the position where that value is present, or the position where it can be inserted
1339    /// to maintain the sort. See [`slice::binary_search_by`] for more details.
1340    ///
1341    /// Computes in **O(log(n))** time.
1342    #[inline]
1343    pub fn binary_search_by<'a, F>(&'a self, f: F) -> Result<usize, usize>
1344    where
1345        F: FnMut(&'a K, &'a V) -> Ordering,
1346    {
1347        self.as_slice().binary_search_by(f)
1348    }
1349
1350    /// Search over a sorted map with an extraction function.
1351    ///
1352    /// Returns the position where that value is present, or the position where it can be inserted
1353    /// to maintain the sort. See [`slice::binary_search_by_key`] for more details.
1354    ///
1355    /// Computes in **O(log(n))** time.
1356    #[inline]
1357    pub fn binary_search_by_key<'a, B, F>(&'a self, b: &B, f: F) -> Result<usize, usize>
1358    where
1359        F: FnMut(&'a K, &'a V) -> B,
1360        B: Ord,
1361    {
1362        self.as_slice().binary_search_by_key(b, f)
1363    }
1364
1365    /// Checks if the keys of this map are sorted.
1366    #[inline]
1367    pub fn is_sorted(&self) -> bool
1368    where
1369        K: PartialOrd,
1370    {
1371        self.as_slice().is_sorted()
1372    }
1373
1374    /// Checks if this map is sorted using the given comparator function.
1375    #[inline]
1376    pub fn is_sorted_by<'a, F>(&'a self, cmp: F) -> bool
1377    where
1378        F: FnMut(&'a K, &'a V, &'a K, &'a V) -> bool,
1379    {
1380        self.as_slice().is_sorted_by(cmp)
1381    }
1382
1383    /// Checks if this map is sorted using the given sort-key function.
1384    #[inline]
1385    pub fn is_sorted_by_key<'a, F, T>(&'a self, sort_key: F) -> bool
1386    where
1387        F: FnMut(&'a K, &'a V) -> T,
1388        T: PartialOrd,
1389    {
1390        self.as_slice().is_sorted_by_key(sort_key)
1391    }
1392
1393    /// Returns the index of the partition point of a sorted map according to the given predicate
1394    /// (the index of the first element of the second partition).
1395    ///
1396    /// See [`slice::partition_point`] for more details.
1397    ///
1398    /// Computes in **O(log(n))** time.
1399    #[must_use]
1400    pub fn partition_point<P>(&self, pred: P) -> usize
1401    where
1402        P: FnMut(&K, &V) -> bool,
1403    {
1404        self.as_slice().partition_point(pred)
1405    }
1406
1407    /// Reverses the order of the map's key-value pairs in place.
1408    ///
1409    /// Computes in **O(n)** time and **O(1)** space.
1410    pub fn reverse(&mut self) {
1411        self.core.reverse()
1412    }
1413
1414    /// Returns a slice of all the key-value pairs in the map.
1415    ///
1416    /// Computes in **O(1)** time.
1417    pub fn as_slice(&self) -> &Slice<K, V> {
1418        Slice::from_slice(self.as_entries())
1419    }
1420
1421    /// Returns a mutable slice of all the key-value pairs in the map.
1422    ///
1423    /// Computes in **O(1)** time.
1424    pub fn as_mut_slice(&mut self) -> &mut Slice<K, V> {
1425        Slice::from_mut_slice(self.as_entries_mut())
1426    }
1427
1428    /// Converts into a boxed slice of all the key-value pairs in the map.
1429    ///
1430    /// Note that this will drop the inner hash table and any excess capacity.
1431    pub fn into_boxed_slice(self) -> Box<Slice<K, V>> {
1432        Slice::from_boxed(self.into_entries().into_boxed_slice())
1433    }
1434
1435    /// Get a key-value pair by index
1436    ///
1437    /// Valid indices are `0 <= index < self.len()`.
1438    ///
1439    /// Computes in **O(1)** time.
1440    pub fn get_index(&self, index: usize) -> Option<(&K, &V)> {
1441        self.as_entries().get(index).map(Bucket::refs)
1442    }
1443
1444    /// Get a key-value pair by index
1445    ///
1446    /// Valid indices are `0 <= index < self.len()`.
1447    ///
1448    /// Computes in **O(1)** time.
1449    pub fn get_index_mut(&mut self, index: usize) -> Option<(&K, &mut V)> {
1450        self.as_entries_mut().get_mut(index).map(Bucket::ref_mut)
1451    }
1452
1453    /// Get an entry in the map by index for in-place manipulation.
1454    ///
1455    /// Valid indices are `0 <= index < self.len()`.
1456    ///
1457    /// Computes in **O(1)** time.
1458    pub fn get_index_entry(&mut self, index: usize) -> Option<IndexedEntry<'_, K, V>> {
1459        IndexedEntry::new(&mut self.core, index)
1460    }
1461
1462    /// Get an array of `N` key-value pairs by `N` indices
1463    ///
1464    /// Valid indices are *0 <= index < self.len()* and each index needs to be unique.
1465    ///
1466    /// # Examples
1467    ///
1468    /// ```
1469    /// let mut map = indexmap::IndexMap::from([(1, 'a'), (3, 'b'), (2, 'c')]);
1470    /// assert_eq!(map.get_disjoint_indices_mut([2, 0]), Ok([(&2, &mut 'c'), (&1, &mut 'a')]));
1471    /// ```
1472    pub fn get_disjoint_indices_mut<const N: usize>(
1473        &mut self,
1474        indices: [usize; N],
1475    ) -> Result<[(&K, &mut V); N], GetDisjointMutError> {
1476        self.as_mut_slice().get_disjoint_mut(indices)
1477    }
1478
1479    /// Returns a slice of key-value pairs in the given range of indices.
1480    ///
1481    /// Valid indices are `0 <= index < self.len()`.
1482    ///
1483    /// Computes in **O(1)** time.
1484    pub fn get_range<R: RangeBounds<usize>>(&self, range: R) -> Option<&Slice<K, V>> {
1485        let entries = self.as_entries();
1486        let range = try_simplify_range(range, entries.len())?;
1487        entries.get(range).map(Slice::from_slice)
1488    }
1489
1490    /// Returns a mutable slice of key-value pairs in the given range of indices.
1491    ///
1492    /// Valid indices are `0 <= index < self.len()`.
1493    ///
1494    /// Computes in **O(1)** time.
1495    pub fn get_range_mut<R: RangeBounds<usize>>(&mut self, range: R) -> Option<&mut Slice<K, V>> {
1496        let entries = self.as_entries_mut();
1497        let range = try_simplify_range(range, entries.len())?;
1498        entries.get_mut(range).map(Slice::from_mut_slice)
1499    }
1500
1501    /// Get the first key-value pair
1502    ///
1503    /// Computes in **O(1)** time.
1504    #[doc(alias = "first_key_value")] // like `BTreeMap`
1505    pub fn first(&self) -> Option<(&K, &V)> {
1506        self.as_entries().first().map(Bucket::refs)
1507    }
1508
1509    /// Get the first key-value pair, with mutable access to the value
1510    ///
1511    /// Computes in **O(1)** time.
1512    pub fn first_mut(&mut self) -> Option<(&K, &mut V)> {
1513        self.as_entries_mut().first_mut().map(Bucket::ref_mut)
1514    }
1515
1516    /// Get the first entry in the map for in-place manipulation.
1517    ///
1518    /// Computes in **O(1)** time.
1519    pub fn first_entry(&mut self) -> Option<IndexedEntry<'_, K, V>> {
1520        self.get_index_entry(0)
1521    }
1522
1523    /// Get the last key-value pair
1524    ///
1525    /// Computes in **O(1)** time.
1526    #[doc(alias = "last_key_value")] // like `BTreeMap`
1527    pub fn last(&self) -> Option<(&K, &V)> {
1528        self.as_entries().last().map(Bucket::refs)
1529    }
1530
1531    /// Get the last key-value pair, with mutable access to the value
1532    ///
1533    /// Computes in **O(1)** time.
1534    pub fn last_mut(&mut self) -> Option<(&K, &mut V)> {
1535        self.as_entries_mut().last_mut().map(Bucket::ref_mut)
1536    }
1537
1538    /// Get the last entry in the map for in-place manipulation.
1539    ///
1540    /// Computes in **O(1)** time.
1541    pub fn last_entry(&mut self) -> Option<IndexedEntry<'_, K, V>> {
1542        self.get_index_entry(self.len().checked_sub(1)?)
1543    }
1544
1545    /// Remove the key-value pair by index
1546    ///
1547    /// Valid indices are `0 <= index < self.len()`.
1548    ///
1549    /// Like [`Vec::swap_remove`], the pair is removed by swapping it with the
1550    /// last element of the map and popping it off. **This perturbs
1551    /// the position of what used to be the last element!**
1552    ///
1553    /// Computes in **O(1)** time (average).
1554    pub fn swap_remove_index(&mut self, index: usize) -> Option<(K, V)> {
1555        self.core.swap_remove_index(index)
1556    }
1557
1558    /// Remove the key-value pair by index
1559    ///
1560    /// Valid indices are `0 <= index < self.len()`.
1561    ///
1562    /// Like [`Vec::remove`], the pair is removed by shifting all of the
1563    /// elements that follow it, preserving their relative order.
1564    /// **This perturbs the index of all of those elements!**
1565    ///
1566    /// Computes in **O(n)** time (average).
1567    pub fn shift_remove_index(&mut self, index: usize) -> Option<(K, V)> {
1568        self.core.shift_remove_index(index)
1569    }
1570
1571    /// Moves the position of a key-value pair from one index to another
1572    /// by shifting all other pairs in-between.
1573    ///
1574    /// * If `from < to`, the other pairs will shift down while the targeted pair moves up.
1575    /// * If `from > to`, the other pairs will shift up while the targeted pair moves down.
1576    ///
1577    /// ***Panics*** if `from` or `to` are out of bounds.
1578    ///
1579    /// Computes in **O(n)** time (average).
1580    #[track_caller]
1581    pub fn move_index(&mut self, from: usize, to: usize) {
1582        self.core.move_index(from, to)
1583    }
1584
1585    /// Swaps the position of two key-value pairs in the map.
1586    ///
1587    /// ***Panics*** if `a` or `b` are out of bounds.
1588    ///
1589    /// Computes in **O(1)** time (average).
1590    #[track_caller]
1591    pub fn swap_indices(&mut self, a: usize, b: usize) {
1592        self.core.swap_indices(a, b)
1593    }
1594}
1595
1596/// Access [`IndexMap`] values corresponding to a key.
1597///
1598/// # Examples
1599///
1600/// ```
1601/// use indexmap::IndexMap;
1602///
1603/// let mut map = IndexMap::new();
1604/// for word in "Lorem ipsum dolor sit amet".split_whitespace() {
1605///     map.insert(word.to_lowercase(), word.to_uppercase());
1606/// }
1607/// assert_eq!(map["lorem"], "LOREM");
1608/// assert_eq!(map["ipsum"], "IPSUM");
1609/// ```
1610///
1611/// ```should_panic
1612/// use indexmap::IndexMap;
1613///
1614/// let mut map = IndexMap::new();
1615/// map.insert("foo", 1);
1616/// println!("{:?}", map["bar"]); // panics!
1617/// ```
1618impl<K, V, Q: ?Sized, S> Index<&Q> for IndexMap<K, V, S>
1619where
1620    Q: Hash + Equivalent<K>,
1621    S: BuildHasher,
1622{
1623    type Output = V;
1624
1625    /// Returns a reference to the value corresponding to the supplied `key`.
1626    ///
1627    /// ***Panics*** if `key` is not present in the map.
1628    fn index(&self, key: &Q) -> &V {
1629        self.get(key).expect("no entry found for key")
1630    }
1631}
1632
1633/// Access [`IndexMap`] values corresponding to a key.
1634///
1635/// Mutable indexing allows changing / updating values of key-value
1636/// pairs that are already present.
1637///
1638/// You can **not** insert new pairs with index syntax, use `.insert()`.
1639///
1640/// # Examples
1641///
1642/// ```
1643/// use indexmap::IndexMap;
1644///
1645/// let mut map = IndexMap::new();
1646/// for word in "Lorem ipsum dolor sit amet".split_whitespace() {
1647///     map.insert(word.to_lowercase(), word.to_string());
1648/// }
1649/// let lorem = &mut map["lorem"];
1650/// assert_eq!(lorem, "Lorem");
1651/// lorem.retain(char::is_lowercase);
1652/// assert_eq!(map["lorem"], "orem");
1653/// ```
1654///
1655/// ```should_panic
1656/// use indexmap::IndexMap;
1657///
1658/// let mut map = IndexMap::new();
1659/// map.insert("foo", 1);
1660/// map["bar"] = 1; // panics!
1661/// ```
1662impl<K, V, Q: ?Sized, S> IndexMut<&Q> for IndexMap<K, V, S>
1663where
1664    Q: Hash + Equivalent<K>,
1665    S: BuildHasher,
1666{
1667    /// Returns a mutable reference to the value corresponding to the supplied `key`.
1668    ///
1669    /// ***Panics*** if `key` is not present in the map.
1670    fn index_mut(&mut self, key: &Q) -> &mut V {
1671        self.get_mut(key).expect("no entry found for key")
1672    }
1673}
1674
1675/// Access [`IndexMap`] values at indexed positions.
1676///
1677/// See [`Index<usize> for Keys`][keys] to access a map's keys instead.
1678///
1679/// [keys]: Keys#impl-Index<usize>-for-Keys<'a,+K,+V>
1680///
1681/// # Examples
1682///
1683/// ```
1684/// use indexmap::IndexMap;
1685///
1686/// let mut map = IndexMap::new();
1687/// for word in "Lorem ipsum dolor sit amet".split_whitespace() {
1688///     map.insert(word.to_lowercase(), word.to_uppercase());
1689/// }
1690/// assert_eq!(map[0], "LOREM");
1691/// assert_eq!(map[1], "IPSUM");
1692/// map.reverse();
1693/// assert_eq!(map[0], "AMET");
1694/// assert_eq!(map[1], "SIT");
1695/// map.sort_keys();
1696/// assert_eq!(map[0], "AMET");
1697/// assert_eq!(map[1], "DOLOR");
1698/// ```
1699///
1700/// ```should_panic
1701/// use indexmap::IndexMap;
1702///
1703/// let mut map = IndexMap::new();
1704/// map.insert("foo", 1);
1705/// println!("{:?}", map[10]); // panics!
1706/// ```
1707impl<K, V, S> Index<usize> for IndexMap<K, V, S> {
1708    type Output = V;
1709
1710    /// Returns a reference to the value at the supplied `index`.
1711    ///
1712    /// ***Panics*** if `index` is out of bounds.
1713    fn index(&self, index: usize) -> &V {
1714        if let Some((_, value)) = self.get_index(index) {
1715            value
1716        } else {
1717            panic!(
1718                "index out of bounds: the len is {len} but the index is {index}",
1719                len = self.len()
1720            );
1721        }
1722    }
1723}
1724
1725/// Access [`IndexMap`] values at indexed positions.
1726///
1727/// Mutable indexing allows changing / updating indexed values
1728/// that are already present.
1729///
1730/// You can **not** insert new values with index syntax -- use [`.insert()`][IndexMap::insert].
1731///
1732/// # Examples
1733///
1734/// ```
1735/// use indexmap::IndexMap;
1736///
1737/// let mut map = IndexMap::new();
1738/// for word in "Lorem ipsum dolor sit amet".split_whitespace() {
1739///     map.insert(word.to_lowercase(), word.to_string());
1740/// }
1741/// let lorem = &mut map[0];
1742/// assert_eq!(lorem, "Lorem");
1743/// lorem.retain(char::is_lowercase);
1744/// assert_eq!(map["lorem"], "orem");
1745/// ```
1746///
1747/// ```should_panic
1748/// use indexmap::IndexMap;
1749///
1750/// let mut map = IndexMap::new();
1751/// map.insert("foo", 1);
1752/// map[10] = 1; // panics!
1753/// ```
1754impl<K, V, S> IndexMut<usize> for IndexMap<K, V, S> {
1755    /// Returns a mutable reference to the value at the supplied `index`.
1756    ///
1757    /// ***Panics*** if `index` is out of bounds.
1758    fn index_mut(&mut self, index: usize) -> &mut V {
1759        let len: usize = self.len();
1760
1761        if let Some((_, value)) = self.get_index_mut(index) {
1762            value
1763        } else {
1764            panic!("index out of bounds: the len is {len} but the index is {index}");
1765        }
1766    }
1767}
1768
1769impl<K, V, S> FromIterator<(K, V)> for IndexMap<K, V, S>
1770where
1771    K: Hash + Eq,
1772    S: BuildHasher + Default,
1773{
1774    /// Create an `IndexMap` from the sequence of key-value pairs in the
1775    /// iterable.
1776    ///
1777    /// `from_iter` uses the same logic as `extend`. See
1778    /// [`extend`][IndexMap::extend] for more details.
1779    fn from_iter<I: IntoIterator<Item = (K, V)>>(iterable: I) -> Self {
1780        let iter = iterable.into_iter();
1781        let (low, _) = iter.size_hint();
1782        let mut map = Self::with_capacity_and_hasher(low, <_>::default());
1783        map.extend(iter);
1784        map
1785    }
1786}
1787
1788#[cfg(feature = "std")]
1789#[cfg_attr(docsrs, doc(cfg(feature = "std")))]
1790impl<K, V, const N: usize> From<[(K, V); N]> for IndexMap<K, V, RandomState>
1791where
1792    K: Hash + Eq,
1793{
1794    /// # Examples
1795    ///
1796    /// ```
1797    /// use indexmap::IndexMap;
1798    ///
1799    /// let map1 = IndexMap::from([(1, 2), (3, 4)]);
1800    /// let map2: IndexMap<_, _> = [(1, 2), (3, 4)].into();
1801    /// assert_eq!(map1, map2);
1802    /// ```
1803    fn from(arr: [(K, V); N]) -> Self {
1804        Self::from_iter(arr)
1805    }
1806}
1807
1808impl<K, V, S> Extend<(K, V)> for IndexMap<K, V, S>
1809where
1810    K: Hash + Eq,
1811    S: BuildHasher,
1812{
1813    /// Extend the map with all key-value pairs in the iterable.
1814    ///
1815    /// This is equivalent to calling [`insert`][IndexMap::insert] for each of
1816    /// them in order, which means that for keys that already existed
1817    /// in the map, their value is updated but it keeps the existing order.
1818    ///
1819    /// New keys are inserted in the order they appear in the sequence. If
1820    /// equivalents of a key occur more than once, the last corresponding value
1821    /// prevails.
1822    fn extend<I: IntoIterator<Item = (K, V)>>(&mut self, iterable: I) {
1823        // (Note: this is a copy of `std`/`hashbrown`'s reservation logic.)
1824        // Keys may be already present or show multiple times in the iterator.
1825        // Reserve the entire hint lower bound if the map is empty.
1826        // Otherwise reserve half the hint (rounded up), so the map
1827        // will only resize twice in the worst case.
1828        let iter = iterable.into_iter();
1829        let (lower_len, _) = iter.size_hint();
1830        let reserve = if self.is_empty() {
1831            lower_len
1832        } else {
1833            lower_len.div_ceil(2)
1834        };
1835        self.reserve(reserve);
1836        iter.for_each(move |(k, v)| {
1837            self.insert(k, v);
1838        });
1839    }
1840}
1841
1842impl<'a, K, V, S> Extend<(&'a K, &'a V)> for IndexMap<K, V, S>
1843where
1844    K: Hash + Eq + Copy,
1845    V: Copy,
1846    S: BuildHasher,
1847{
1848    /// Extend the map with all key-value pairs in the iterable.
1849    ///
1850    /// See the first extend method for more details.
1851    fn extend<I: IntoIterator<Item = (&'a K, &'a V)>>(&mut self, iterable: I) {
1852        self.extend(iterable.into_iter().map(|(&key, &value)| (key, value)));
1853    }
1854}
1855
1856impl<K, V, S> Default for IndexMap<K, V, S>
1857where
1858    S: Default,
1859{
1860    /// Return an empty [`IndexMap`]
1861    fn default() -> Self {
1862        Self::with_capacity_and_hasher(0, S::default())
1863    }
1864}
1865
1866impl<K, V1, S1, V2, S2> PartialEq<IndexMap<K, V2, S2>> for IndexMap<K, V1, S1>
1867where
1868    K: Hash + Eq,
1869    V1: PartialEq<V2>,
1870    S1: BuildHasher,
1871    S2: BuildHasher,
1872{
1873    fn eq(&self, other: &IndexMap<K, V2, S2>) -> bool {
1874        if self.len() != other.len() {
1875            return false;
1876        }
1877
1878        self.iter()
1879            .all(|(key, value)| other.get(key).map_or(false, |v| *value == *v))
1880    }
1881}
1882
1883impl<K, V, S> Eq for IndexMap<K, V, S>
1884where
1885    K: Eq + Hash,
1886    V: Eq,
1887    S: BuildHasher,
1888{
1889}