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