Skip to main content

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