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