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