indexmap/map.rs
1//! [`IndexMap`] is a hash table where the iteration order of the key-value
2//! pairs is independent of the hash values of the keys.
3
4mod core;
5mod iter;
6mod mutable;
7mod slice;
8
9#[cfg(feature = "serde")]
10#[cfg_attr(docsrs, doc(cfg(feature = "serde")))]
11pub mod serde_seq;
12
13#[cfg(test)]
14mod tests;
15
16pub use self::core::raw_entry_v1::{self, RawEntryApiV1};
17pub use self::core::{Entry, IndexedEntry, OccupiedEntry, VacantEntry};
18pub use self::iter::{
19 Drain, ExtractIf, IntoIter, IntoKeys, IntoValues, Iter, IterMut, IterMut2, Keys, Splice,
20 Values, ValuesMut,
21};
22pub use self::mutable::MutableEntryKey;
23pub use self::mutable::MutableKeys;
24pub use self::slice::Slice;
25
26#[cfg(feature = "rayon")]
27pub use crate::rayon::map as rayon;
28
29use ::core::cmp::Ordering;
30use ::core::fmt;
31use ::core::hash::{BuildHasher, Hash, Hasher};
32use ::core::mem;
33use ::core::ops::{Index, IndexMut, RangeBounds};
34use alloc::boxed::Box;
35use alloc::vec::Vec;
36
37#[cfg(feature = "std")]
38use std::collections::hash_map::RandomState;
39
40pub(crate) use self::core::{ExtractCore, IndexMapCore};
41use crate::util::{third, try_simplify_range};
42use crate::{Bucket, Equivalent, GetDisjointMutError, HashValue, TryReserveError};
43
44/// A hash table where the iteration order of the key-value pairs is independent
45/// of the hash values of the keys.
46///
47/// The interface is closely compatible with the standard
48/// [`HashMap`][std::collections::HashMap],
49/// but also has additional features.
50///
51/// # Order
52///
53/// The key-value pairs have a consistent order that is determined by
54/// the sequence of insertion and removal calls on the map. The order does
55/// not depend on the keys or the hash function at all.
56///
57/// All iterators traverse the map in *the order*.
58///
59/// The insertion order is preserved, with **notable exceptions** like the
60/// [`.remove()`][Self::remove] or [`.swap_remove()`][Self::swap_remove] methods.
61/// Methods such as [`.sort_by()`][Self::sort_by] of
62/// course result in a new order, depending on the sorting order.
63///
64/// # Indices
65///
66/// The key-value pairs are indexed in a compact range without holes in the
67/// range `0..self.len()`. For example, the method `.get_full` looks up the
68/// index for a key, and the method `.get_index` looks up the key-value pair by
69/// index.
70///
71/// # Examples
72///
73/// ```
74/// use indexmap::IndexMap;
75///
76/// // count the frequency of each letter in a sentence.
77/// let mut letters = IndexMap::new();
78/// for ch in "a short treatise on fungi".chars() {
79/// *letters.entry(ch).or_insert(0) += 1;
80/// }
81///
82/// assert_eq!(letters[&'s'], 2);
83/// assert_eq!(letters[&'t'], 3);
84/// assert_eq!(letters[&'u'], 1);
85/// assert_eq!(letters.get(&'y'), None);
86/// ```
87#[cfg(feature = "std")]
88pub struct IndexMap<K, V, S = RandomState> {
89 pub(crate) core: IndexMapCore<K, V>,
90 hash_builder: S,
91}
92#[cfg(not(feature = "std"))]
93pub struct IndexMap<K, V, S> {
94 pub(crate) core: IndexMapCore<K, V>,
95 hash_builder: S,
96}
97
98impl<K, V, S> Clone for IndexMap<K, V, S>
99where
100 K: Clone,
101 V: Clone,
102 S: Clone,
103{
104 fn clone(&self) -> Self {
105 IndexMap {
106 core: self.core.clone(),
107 hash_builder: self.hash_builder.clone(),
108 }
109 }
110
111 fn clone_from(&mut self, other: &Self) {
112 self.core.clone_from(&other.core);
113 self.hash_builder.clone_from(&other.hash_builder);
114 }
115}
116
117impl<K, V, S> fmt::Debug for IndexMap<K, V, S>
118where
119 K: fmt::Debug,
120 V: fmt::Debug,
121{
122 #[cfg(not(feature = "test_debug"))]
123 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
124 f.debug_map().entries(self.iter()).finish()
125 }
126
127 #[cfg(feature = "test_debug")]
128 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
129 // Let the inner `IndexMapCore` print all of its details
130 f.debug_struct("IndexMap")
131 .field("core", &self.core)
132 .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: IndexMapCore::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: IndexMapCore::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 K: Ord,
511 F: FnMut(&K, &V, &K, &V) -> Ordering,
512 {
513 let (Ok(i) | Err(i)) = self.binary_search_by(|k, v| cmp(k, v, &key, &value));
514 self.insert_before(i, key, value)
515 }
516
517 /// Insert a key-value pair in the map at its ordered position
518 /// using a sort-key extraction function.
519 ///
520 /// This is equivalent to finding the position with
521 /// [`binary_search_by_key`][Self::binary_search_by_key] with `sort_key(key)`, then
522 /// calling [`insert_before`][Self::insert_before] with the given key and value.
523 ///
524 /// If the existing keys are **not** already sorted, then the insertion
525 /// index is unspecified (like [`slice::binary_search`]), but the key-value
526 /// pair is moved to or inserted at that position regardless.
527 ///
528 /// Computes in **O(n)** time (average).
529 pub fn insert_sorted_by_key<B, F>(
530 &mut self,
531 key: K,
532 value: V,
533 mut sort_key: F,
534 ) -> (usize, Option<V>)
535 where
536 B: Ord,
537 F: FnMut(&K, &V) -> B,
538 {
539 let search_key = sort_key(&key, &value);
540 let (Ok(i) | Err(i)) = self.binary_search_by_key(&search_key, sort_key);
541 self.insert_before(i, key, value)
542 }
543
544 /// Insert a key-value pair in the map before the entry at the given index, or at the end.
545 ///
546 /// If an equivalent key already exists in the map: the key remains and
547 /// is moved to the new position in the map, its corresponding value is updated
548 /// with `value`, and the older value is returned inside `Some(_)`. The returned index
549 /// will either be the given index or one less, depending on how the entry moved.
550 /// (See [`shift_insert`](Self::shift_insert) for different behavior here.)
551 ///
552 /// If no equivalent key existed in the map: the new key-value pair is
553 /// inserted exactly at the given index, and `None` is returned.
554 ///
555 /// ***Panics*** if `index` is out of bounds.
556 /// Valid indices are `0..=map.len()` (inclusive).
557 ///
558 /// Computes in **O(n)** time (average).
559 ///
560 /// See also [`entry`][Self::entry] if you want to insert *or* modify,
561 /// perhaps only using the index for new entries with [`VacantEntry::shift_insert`].
562 ///
563 /// # Examples
564 ///
565 /// ```
566 /// use indexmap::IndexMap;
567 /// let mut map: IndexMap<char, ()> = ('a'..='z').map(|c| (c, ())).collect();
568 ///
569 /// // The new key '*' goes exactly at the given index.
570 /// assert_eq!(map.get_index_of(&'*'), None);
571 /// assert_eq!(map.insert_before(10, '*', ()), (10, None));
572 /// assert_eq!(map.get_index_of(&'*'), Some(10));
573 ///
574 /// // Moving the key 'a' up will shift others down, so this moves *before* 10 to index 9.
575 /// assert_eq!(map.insert_before(10, 'a', ()), (9, Some(())));
576 /// assert_eq!(map.get_index_of(&'a'), Some(9));
577 /// assert_eq!(map.get_index_of(&'*'), Some(10));
578 ///
579 /// // Moving the key 'z' down will shift others up, so this moves to exactly 10.
580 /// assert_eq!(map.insert_before(10, 'z', ()), (10, Some(())));
581 /// assert_eq!(map.get_index_of(&'z'), Some(10));
582 /// assert_eq!(map.get_index_of(&'*'), Some(11));
583 ///
584 /// // Moving or inserting before the endpoint is also valid.
585 /// assert_eq!(map.len(), 27);
586 /// assert_eq!(map.insert_before(map.len(), '*', ()), (26, Some(())));
587 /// assert_eq!(map.get_index_of(&'*'), Some(26));
588 /// assert_eq!(map.insert_before(map.len(), '+', ()), (27, None));
589 /// assert_eq!(map.get_index_of(&'+'), Some(27));
590 /// assert_eq!(map.len(), 28);
591 /// ```
592 #[track_caller]
593 pub fn insert_before(&mut self, mut index: usize, key: K, value: V) -> (usize, Option<V>) {
594 let len = self.len();
595
596 assert!(
597 index <= len,
598 "index out of bounds: the len is {len} but the index is {index}. Expected index <= len"
599 );
600
601 match self.entry(key) {
602 Entry::Occupied(mut entry) => {
603 if index > entry.index() {
604 // Some entries will shift down when this one moves up,
605 // so "insert before index" becomes "move to index - 1",
606 // keeping the entry at the original index unmoved.
607 index -= 1;
608 }
609 let old = mem::replace(entry.get_mut(), value);
610 entry.move_index(index);
611 (index, Some(old))
612 }
613 Entry::Vacant(entry) => {
614 entry.shift_insert(index, value);
615 (index, None)
616 }
617 }
618 }
619
620 /// Insert a key-value pair in the map at the given index.
621 ///
622 /// If an equivalent key already exists in the map: the key remains and
623 /// is moved to the given index in the map, its corresponding value is updated
624 /// with `value`, and the older value is returned inside `Some(_)`.
625 /// Note that existing entries **cannot** be moved to `index == map.len()`!
626 /// (See [`insert_before`](Self::insert_before) for different behavior here.)
627 ///
628 /// If no equivalent key existed in the map: the new key-value pair is
629 /// inserted at the given index, and `None` is returned.
630 ///
631 /// ***Panics*** if `index` is out of bounds.
632 /// Valid indices are `0..map.len()` (exclusive) when moving an existing entry, or
633 /// `0..=map.len()` (inclusive) when inserting a new key.
634 ///
635 /// Computes in **O(n)** time (average).
636 ///
637 /// See also [`entry`][Self::entry] if you want to insert *or* modify,
638 /// perhaps only using the index for new entries with [`VacantEntry::shift_insert`].
639 ///
640 /// # Examples
641 ///
642 /// ```
643 /// use indexmap::IndexMap;
644 /// let mut map: IndexMap<char, ()> = ('a'..='z').map(|c| (c, ())).collect();
645 ///
646 /// // The new key '*' goes exactly at the given index.
647 /// assert_eq!(map.get_index_of(&'*'), None);
648 /// assert_eq!(map.shift_insert(10, '*', ()), None);
649 /// assert_eq!(map.get_index_of(&'*'), Some(10));
650 ///
651 /// // Moving the key 'a' up to 10 will shift others down, including the '*' that was at 10.
652 /// assert_eq!(map.shift_insert(10, 'a', ()), Some(()));
653 /// assert_eq!(map.get_index_of(&'a'), Some(10));
654 /// assert_eq!(map.get_index_of(&'*'), Some(9));
655 ///
656 /// // Moving the key 'z' down to 9 will shift others up, including the '*' that was at 9.
657 /// assert_eq!(map.shift_insert(9, 'z', ()), Some(()));
658 /// assert_eq!(map.get_index_of(&'z'), Some(9));
659 /// assert_eq!(map.get_index_of(&'*'), Some(10));
660 ///
661 /// // Existing keys can move to len-1 at most, but new keys can insert at the endpoint.
662 /// assert_eq!(map.len(), 27);
663 /// assert_eq!(map.shift_insert(map.len() - 1, '*', ()), Some(()));
664 /// assert_eq!(map.get_index_of(&'*'), Some(26));
665 /// assert_eq!(map.shift_insert(map.len(), '+', ()), None);
666 /// assert_eq!(map.get_index_of(&'+'), Some(27));
667 /// assert_eq!(map.len(), 28);
668 /// ```
669 ///
670 /// ```should_panic
671 /// use indexmap::IndexMap;
672 /// let mut map: IndexMap<char, ()> = ('a'..='z').map(|c| (c, ())).collect();
673 ///
674 /// // This is an invalid index for moving an existing key!
675 /// map.shift_insert(map.len(), 'a', ());
676 /// ```
677 #[track_caller]
678 pub fn shift_insert(&mut self, index: usize, key: K, value: V) -> Option<V> {
679 let len = self.len();
680 match self.entry(key) {
681 Entry::Occupied(mut entry) => {
682 assert!(
683 index < len,
684 "index out of bounds: the len is {len} but the index is {index}"
685 );
686
687 let old = mem::replace(entry.get_mut(), value);
688 entry.move_index(index);
689 Some(old)
690 }
691 Entry::Vacant(entry) => {
692 assert!(
693 index <= len,
694 "index out of bounds: the len is {len} but the index is {index}. Expected index <= len"
695 );
696
697 entry.shift_insert(index, value);
698 None
699 }
700 }
701 }
702
703 /// Replaces the key at the given index. The new key does not need to be
704 /// equivalent to the one it is replacing, but it must be unique to the rest
705 /// of the map.
706 ///
707 /// Returns `Ok(old_key)` if successful, or `Err((other_index, key))` if an
708 /// equivalent key already exists at a different index. The map will be
709 /// unchanged in the error case.
710 ///
711 /// Direct indexing can be used to change the corresponding value: simply
712 /// `map[index] = value`, or `mem::replace(&mut map[index], value)` to
713 /// retrieve the old value as well.
714 ///
715 /// ***Panics*** if `index` is out of bounds.
716 ///
717 /// Computes in **O(1)** time (average).
718 #[track_caller]
719 pub fn replace_index(&mut self, index: usize, key: K) -> Result<K, (usize, K)> {
720 // If there's a direct match, we don't even need to hash it.
721 let entry = &mut self.as_entries_mut()[index];
722 if key == entry.key {
723 return Ok(mem::replace(&mut entry.key, key));
724 }
725
726 let hash = self.hash(&key);
727 if let Some(i) = self.core.get_index_of(hash, &key) {
728 debug_assert_ne!(i, index);
729 return Err((i, key));
730 }
731 Ok(self.core.replace_index_unique(index, hash, key))
732 }
733
734 /// Get the given key's corresponding entry in the map for insertion and/or
735 /// in-place manipulation.
736 ///
737 /// Computes in **O(1)** time (amortized average).
738 pub fn entry(&mut self, key: K) -> Entry<'_, K, V> {
739 let hash = self.hash(&key);
740 self.core.entry(hash, key)
741 }
742
743 /// Creates a splicing iterator that replaces the specified range in the map
744 /// with the given `replace_with` key-value iterator and yields the removed
745 /// items. `replace_with` does not need to be the same length as `range`.
746 ///
747 /// The `range` is removed even if the iterator is not consumed until the
748 /// end. It is unspecified how many elements are removed from the map if the
749 /// `Splice` value is leaked.
750 ///
751 /// The input iterator `replace_with` is only consumed when the `Splice`
752 /// value is dropped. If a key from the iterator matches an existing entry
753 /// in the map (outside of `range`), then the value will be updated in that
754 /// position. Otherwise, the new key-value pair will be inserted in the
755 /// replaced `range`.
756 ///
757 /// ***Panics*** if the starting point is greater than the end point or if
758 /// the end point is greater than the length of the map.
759 ///
760 /// # Examples
761 ///
762 /// ```
763 /// use indexmap::IndexMap;
764 ///
765 /// let mut map = IndexMap::from([(0, '_'), (1, 'a'), (2, 'b'), (3, 'c'), (4, 'd')]);
766 /// let new = [(5, 'E'), (4, 'D'), (3, 'C'), (2, 'B'), (1, 'A')];
767 /// let removed: Vec<_> = map.splice(2..4, new).collect();
768 ///
769 /// // 1 and 4 got new values, while 5, 3, and 2 were newly inserted.
770 /// assert!(map.into_iter().eq([(0, '_'), (1, 'A'), (5, 'E'), (3, 'C'), (2, 'B'), (4, 'D')]));
771 /// assert_eq!(removed, &[(2, 'b'), (3, 'c')]);
772 /// ```
773 #[track_caller]
774 pub fn splice<R, I>(&mut self, range: R, replace_with: I) -> Splice<'_, I::IntoIter, K, V, S>
775 where
776 R: RangeBounds<usize>,
777 I: IntoIterator<Item = (K, V)>,
778 {
779 Splice::new(self, range, replace_with.into_iter())
780 }
781
782 /// Moves all key-value pairs from `other` into `self`, leaving `other` empty.
783 ///
784 /// This is equivalent to calling [`insert`][Self::insert] for each
785 /// key-value pair from `other` in order, which means that for keys that
786 /// already exist in `self`, their value is updated in the current position.
787 ///
788 /// # Examples
789 ///
790 /// ```
791 /// use indexmap::IndexMap;
792 ///
793 /// // Note: Key (3) is present in both maps.
794 /// let mut a = IndexMap::from([(3, "c"), (2, "b"), (1, "a")]);
795 /// let mut b = IndexMap::from([(3, "d"), (4, "e"), (5, "f")]);
796 /// let old_capacity = b.capacity();
797 ///
798 /// a.append(&mut b);
799 ///
800 /// assert_eq!(a.len(), 5);
801 /// assert_eq!(b.len(), 0);
802 /// assert_eq!(b.capacity(), old_capacity);
803 ///
804 /// assert!(a.keys().eq(&[3, 2, 1, 4, 5]));
805 /// assert_eq!(a[&3], "d"); // "c" was overwritten.
806 /// ```
807 pub fn append<S2>(&mut self, other: &mut IndexMap<K, V, S2>) {
808 self.extend(other.drain(..));
809 }
810}
811
812impl<K, V, S> IndexMap<K, V, S>
813where
814 S: BuildHasher,
815{
816 pub(crate) fn hash<Q: ?Sized + Hash>(&self, key: &Q) -> HashValue {
817 let mut h = self.hash_builder.build_hasher();
818 key.hash(&mut h);
819 HashValue(h.finish() as usize)
820 }
821
822 /// Return `true` if an equivalent to `key` exists in the map.
823 ///
824 /// Computes in **O(1)** time (average).
825 pub fn contains_key<Q>(&self, key: &Q) -> bool
826 where
827 Q: ?Sized + Hash + Equivalent<K>,
828 {
829 self.get_index_of(key).is_some()
830 }
831
832 /// Return a reference to the value stored for `key`, if it is present,
833 /// else `None`.
834 ///
835 /// Computes in **O(1)** time (average).
836 pub fn get<Q>(&self, key: &Q) -> Option<&V>
837 where
838 Q: ?Sized + Hash + Equivalent<K>,
839 {
840 if let Some(i) = self.get_index_of(key) {
841 let entry = &self.as_entries()[i];
842 Some(&entry.value)
843 } else {
844 None
845 }
846 }
847
848 /// Return references to the key-value pair stored for `key`,
849 /// if it is present, else `None`.
850 ///
851 /// Computes in **O(1)** time (average).
852 pub fn get_key_value<Q>(&self, key: &Q) -> Option<(&K, &V)>
853 where
854 Q: ?Sized + Hash + Equivalent<K>,
855 {
856 if let Some(i) = self.get_index_of(key) {
857 let entry = &self.as_entries()[i];
858 Some((&entry.key, &entry.value))
859 } else {
860 None
861 }
862 }
863
864 /// Return item index, key and value
865 pub fn get_full<Q>(&self, key: &Q) -> Option<(usize, &K, &V)>
866 where
867 Q: ?Sized + Hash + Equivalent<K>,
868 {
869 if let Some(i) = self.get_index_of(key) {
870 let entry = &self.as_entries()[i];
871 Some((i, &entry.key, &entry.value))
872 } else {
873 None
874 }
875 }
876
877 /// Return item index, if it exists in the map
878 ///
879 /// Computes in **O(1)** time (average).
880 pub fn get_index_of<Q>(&self, key: &Q) -> Option<usize>
881 where
882 Q: ?Sized + Hash + Equivalent<K>,
883 {
884 match self.as_entries() {
885 [] => None,
886 [x] => key.equivalent(&x.key).then_some(0),
887 _ => {
888 let hash = self.hash(key);
889 self.core.get_index_of(hash, key)
890 }
891 }
892 }
893
894 pub fn get_mut<Q>(&mut self, key: &Q) -> Option<&mut V>
895 where
896 Q: ?Sized + Hash + Equivalent<K>,
897 {
898 if let Some(i) = self.get_index_of(key) {
899 let entry = &mut self.as_entries_mut()[i];
900 Some(&mut entry.value)
901 } else {
902 None
903 }
904 }
905
906 pub fn get_full_mut<Q>(&mut self, key: &Q) -> Option<(usize, &K, &mut V)>
907 where
908 Q: ?Sized + Hash + Equivalent<K>,
909 {
910 if let Some(i) = self.get_index_of(key) {
911 let entry = &mut self.as_entries_mut()[i];
912 Some((i, &entry.key, &mut entry.value))
913 } else {
914 None
915 }
916 }
917
918 /// Return the values for `N` keys. If any key is duplicated, this function will panic.
919 ///
920 /// # Examples
921 ///
922 /// ```
923 /// let mut map = indexmap::IndexMap::from([(1, 'a'), (3, 'b'), (2, 'c')]);
924 /// assert_eq!(map.get_disjoint_mut([&2, &1]), [Some(&mut 'c'), Some(&mut 'a')]);
925 /// ```
926 pub fn get_disjoint_mut<Q, const N: usize>(&mut self, keys: [&Q; N]) -> [Option<&mut V>; N]
927 where
928 Q: ?Sized + Hash + Equivalent<K>,
929 {
930 let indices = keys.map(|key| self.get_index_of(key));
931 match self.as_mut_slice().get_disjoint_opt_mut(indices) {
932 Err(GetDisjointMutError::IndexOutOfBounds) => {
933 unreachable!(
934 "Internal error: indices should never be OOB as we got them from get_index_of"
935 );
936 }
937 Err(GetDisjointMutError::OverlappingIndices) => {
938 panic!("duplicate keys found");
939 }
940 Ok(key_values) => key_values.map(|kv_opt| kv_opt.map(|kv| kv.1)),
941 }
942 }
943
944 /// Remove the key-value pair equivalent to `key` and return
945 /// its value.
946 ///
947 /// **NOTE:** This is equivalent to [`.swap_remove(key)`][Self::swap_remove], replacing this
948 /// entry's position with the last element, and it is deprecated in favor of calling that
949 /// explicitly. If you need to preserve the relative order of the keys in the map, use
950 /// [`.shift_remove(key)`][Self::shift_remove] instead.
951 #[deprecated(note = "`remove` disrupts the map order -- \
952 use `swap_remove` or `shift_remove` for explicit behavior.")]
953 pub fn remove<Q>(&mut self, key: &Q) -> Option<V>
954 where
955 Q: ?Sized + Hash + Equivalent<K>,
956 {
957 self.swap_remove(key)
958 }
959
960 /// Remove and return the key-value pair equivalent to `key`.
961 ///
962 /// **NOTE:** This is equivalent to [`.swap_remove_entry(key)`][Self::swap_remove_entry],
963 /// replacing this entry's position with the last element, and it is deprecated in favor of
964 /// calling that explicitly. If you need to preserve the relative order of the keys in the map,
965 /// use [`.shift_remove_entry(key)`][Self::shift_remove_entry] instead.
966 #[deprecated(note = "`remove_entry` disrupts the map order -- \
967 use `swap_remove_entry` or `shift_remove_entry` for explicit behavior.")]
968 pub fn remove_entry<Q>(&mut self, key: &Q) -> Option<(K, V)>
969 where
970 Q: ?Sized + Hash + Equivalent<K>,
971 {
972 self.swap_remove_entry(key)
973 }
974
975 /// Remove the key-value pair equivalent to `key` and return
976 /// its value.
977 ///
978 /// Like [`Vec::swap_remove`], the pair is removed by swapping it with the
979 /// last element of the map and popping it off. **This perturbs
980 /// the position of what used to be the last element!**
981 ///
982 /// Return `None` if `key` is not in map.
983 ///
984 /// Computes in **O(1)** time (average).
985 pub fn swap_remove<Q>(&mut self, key: &Q) -> Option<V>
986 where
987 Q: ?Sized + Hash + Equivalent<K>,
988 {
989 self.swap_remove_full(key).map(third)
990 }
991
992 /// Remove and return the key-value pair equivalent to `key`.
993 ///
994 /// Like [`Vec::swap_remove`], the pair is removed by swapping it with the
995 /// last element of the map and popping it off. **This perturbs
996 /// the position of what used to be the last element!**
997 ///
998 /// Return `None` if `key` is not in map.
999 ///
1000 /// Computes in **O(1)** time (average).
1001 pub fn swap_remove_entry<Q>(&mut self, key: &Q) -> Option<(K, V)>
1002 where
1003 Q: ?Sized + Hash + Equivalent<K>,
1004 {
1005 match self.swap_remove_full(key) {
1006 Some((_, key, value)) => Some((key, value)),
1007 None => None,
1008 }
1009 }
1010
1011 /// Remove the key-value pair equivalent to `key` and return it and
1012 /// the index it had.
1013 ///
1014 /// Like [`Vec::swap_remove`], the pair is removed by swapping it with the
1015 /// last element of the map and popping it off. **This perturbs
1016 /// the position of what used to be the last element!**
1017 ///
1018 /// Return `None` if `key` is not in map.
1019 ///
1020 /// Computes in **O(1)** time (average).
1021 pub fn swap_remove_full<Q>(&mut self, key: &Q) -> Option<(usize, K, V)>
1022 where
1023 Q: ?Sized + Hash + Equivalent<K>,
1024 {
1025 match self.as_entries() {
1026 [x] if key.equivalent(&x.key) => {
1027 let (k, v) = self.core.pop()?;
1028 Some((0, k, v))
1029 }
1030 [_] | [] => None,
1031 _ => {
1032 let hash = self.hash(key);
1033 self.core.swap_remove_full(hash, key)
1034 }
1035 }
1036 }
1037
1038 /// Remove the key-value pair equivalent to `key` and return
1039 /// its value.
1040 ///
1041 /// Like [`Vec::remove`], the pair is removed by shifting all of the
1042 /// elements that follow it, preserving their relative order.
1043 /// **This perturbs the index of all of those elements!**
1044 ///
1045 /// Return `None` if `key` is not in map.
1046 ///
1047 /// Computes in **O(n)** time (average).
1048 pub fn shift_remove<Q>(&mut self, key: &Q) -> Option<V>
1049 where
1050 Q: ?Sized + Hash + Equivalent<K>,
1051 {
1052 self.shift_remove_full(key).map(third)
1053 }
1054
1055 /// Remove and return the key-value pair equivalent to `key`.
1056 ///
1057 /// Like [`Vec::remove`], the pair is removed by shifting all of the
1058 /// elements that follow it, preserving their relative order.
1059 /// **This perturbs the index of all of those elements!**
1060 ///
1061 /// Return `None` if `key` is not in map.
1062 ///
1063 /// Computes in **O(n)** time (average).
1064 pub fn shift_remove_entry<Q>(&mut self, key: &Q) -> Option<(K, V)>
1065 where
1066 Q: ?Sized + Hash + Equivalent<K>,
1067 {
1068 match self.shift_remove_full(key) {
1069 Some((_, key, value)) => Some((key, value)),
1070 None => None,
1071 }
1072 }
1073
1074 /// Remove the key-value pair equivalent to `key` and return it and
1075 /// the index it had.
1076 ///
1077 /// Like [`Vec::remove`], the pair is removed by shifting all of the
1078 /// elements that follow it, preserving their relative order.
1079 /// **This perturbs the index of all of those elements!**
1080 ///
1081 /// Return `None` if `key` is not in map.
1082 ///
1083 /// Computes in **O(n)** time (average).
1084 pub fn shift_remove_full<Q>(&mut self, key: &Q) -> Option<(usize, K, V)>
1085 where
1086 Q: ?Sized + Hash + Equivalent<K>,
1087 {
1088 match self.as_entries() {
1089 [x] if key.equivalent(&x.key) => {
1090 let (k, v) = self.core.pop()?;
1091 Some((0, k, v))
1092 }
1093 [_] | [] => None,
1094 _ => {
1095 let hash = self.hash(key);
1096 self.core.shift_remove_full(hash, key)
1097 }
1098 }
1099 }
1100}
1101
1102impl<K, V, S> IndexMap<K, V, S> {
1103 /// Remove the last key-value pair
1104 ///
1105 /// This preserves the order of the remaining elements.
1106 ///
1107 /// Computes in **O(1)** time (average).
1108 #[doc(alias = "pop_last")] // like `BTreeMap`
1109 pub fn pop(&mut self) -> Option<(K, V)> {
1110 self.core.pop()
1111 }
1112
1113 /// Scan through each key-value pair in the map and keep those where the
1114 /// closure `keep` returns `true`.
1115 ///
1116 /// The elements are visited in order, and remaining elements keep their
1117 /// order.
1118 ///
1119 /// Computes in **O(n)** time (average).
1120 pub fn retain<F>(&mut self, mut keep: F)
1121 where
1122 F: FnMut(&K, &mut V) -> bool,
1123 {
1124 self.core.retain_in_order(move |k, v| keep(k, v));
1125 }
1126
1127 /// Sort the map's key-value pairs by the default ordering of the keys.
1128 ///
1129 /// This is a stable sort -- but equivalent keys should not normally coexist in
1130 /// a map at all, so [`sort_unstable_keys`][Self::sort_unstable_keys] is preferred
1131 /// because it is generally faster and doesn't allocate auxiliary memory.
1132 ///
1133 /// See [`sort_by`](Self::sort_by) for details.
1134 pub fn sort_keys(&mut self)
1135 where
1136 K: Ord,
1137 {
1138 self.with_entries(move |entries| {
1139 entries.sort_by(move |a, b| K::cmp(&a.key, &b.key));
1140 });
1141 }
1142
1143 /// Sort the map's key-value pairs in place using the comparison
1144 /// function `cmp`.
1145 ///
1146 /// The comparison function receives two key and value pairs to compare (you
1147 /// can sort by keys or values or their combination as needed).
1148 ///
1149 /// Computes in **O(n log n + c)** time and **O(n)** space where *n* is
1150 /// the length of the map and *c* the capacity. The sort is stable.
1151 pub fn sort_by<F>(&mut self, mut cmp: F)
1152 where
1153 F: FnMut(&K, &V, &K, &V) -> Ordering,
1154 {
1155 self.with_entries(move |entries| {
1156 entries.sort_by(move |a, b| cmp(&a.key, &a.value, &b.key, &b.value));
1157 });
1158 }
1159
1160 /// Sort the key-value pairs of the map and return a by-value iterator of
1161 /// the key-value pairs with the result.
1162 ///
1163 /// The sort is stable.
1164 pub fn sorted_by<F>(self, mut cmp: F) -> IntoIter<K, V>
1165 where
1166 F: FnMut(&K, &V, &K, &V) -> Ordering,
1167 {
1168 let mut entries = self.into_entries();
1169 entries.sort_by(move |a, b| cmp(&a.key, &a.value, &b.key, &b.value));
1170 IntoIter::new(entries)
1171 }
1172
1173 /// Sort the map's key-value pairs in place using a sort-key extraction function.
1174 ///
1175 /// Computes in **O(n log n + c)** time and **O(n)** space where *n* is
1176 /// the length of the map and *c* the capacity. The sort is stable.
1177 pub fn sort_by_key<T, F>(&mut self, mut sort_key: F)
1178 where
1179 T: Ord,
1180 F: FnMut(&K, &V) -> T,
1181 {
1182 self.with_entries(move |entries| {
1183 entries.sort_by_key(move |a| sort_key(&a.key, &a.value));
1184 });
1185 }
1186
1187 /// Sort the map's key-value pairs by the default ordering of the keys, but
1188 /// may not preserve the order of equal elements.
1189 ///
1190 /// See [`sort_unstable_by`](Self::sort_unstable_by) for details.
1191 pub fn sort_unstable_keys(&mut self)
1192 where
1193 K: Ord,
1194 {
1195 self.with_entries(move |entries| {
1196 entries.sort_unstable_by(move |a, b| K::cmp(&a.key, &b.key));
1197 });
1198 }
1199
1200 /// Sort the map's key-value pairs in place using the comparison function `cmp`, but
1201 /// may not preserve the order of equal elements.
1202 ///
1203 /// The comparison function receives two key and value pairs to compare (you
1204 /// can sort by keys or values or their combination as needed).
1205 ///
1206 /// Computes in **O(n log n + c)** time where *n* is
1207 /// the length of the map and *c* is the capacity. The sort is unstable.
1208 pub fn sort_unstable_by<F>(&mut self, mut cmp: F)
1209 where
1210 F: FnMut(&K, &V, &K, &V) -> Ordering,
1211 {
1212 self.with_entries(move |entries| {
1213 entries.sort_unstable_by(move |a, b| cmp(&a.key, &a.value, &b.key, &b.value));
1214 });
1215 }
1216
1217 /// Sort the key-value pairs of the map and return a by-value iterator of
1218 /// the key-value pairs with the result.
1219 ///
1220 /// The sort is unstable.
1221 #[inline]
1222 pub fn sorted_unstable_by<F>(self, mut cmp: F) -> IntoIter<K, V>
1223 where
1224 F: FnMut(&K, &V, &K, &V) -> Ordering,
1225 {
1226 let mut entries = self.into_entries();
1227 entries.sort_unstable_by(move |a, b| cmp(&a.key, &a.value, &b.key, &b.value));
1228 IntoIter::new(entries)
1229 }
1230
1231 /// Sort the map's key-value pairs in place using a sort-key extraction function.
1232 ///
1233 /// Computes in **O(n log n + c)** time where *n* is
1234 /// the length of the map and *c* is the capacity. The sort is unstable.
1235 pub fn sort_unstable_by_key<T, F>(&mut self, mut sort_key: F)
1236 where
1237 T: Ord,
1238 F: FnMut(&K, &V) -> T,
1239 {
1240 self.with_entries(move |entries| {
1241 entries.sort_unstable_by_key(move |a| sort_key(&a.key, &a.value));
1242 });
1243 }
1244
1245 /// Sort the map's key-value pairs in place using a sort-key extraction function.
1246 ///
1247 /// During sorting, the function is called at most once per entry, by using temporary storage
1248 /// to remember the results of its evaluation. The order of calls to the function is
1249 /// unspecified and may change between versions of `indexmap` or the standard library.
1250 ///
1251 /// Computes in **O(m n + n log n + c)** time () and **O(n)** space, where the function is
1252 /// **O(m)**, *n* is the length of the map, and *c* the capacity. The sort is stable.
1253 pub fn sort_by_cached_key<T, F>(&mut self, mut sort_key: F)
1254 where
1255 T: Ord,
1256 F: FnMut(&K, &V) -> T,
1257 {
1258 self.with_entries(move |entries| {
1259 entries.sort_by_cached_key(move |a| sort_key(&a.key, &a.value));
1260 });
1261 }
1262
1263 /// Search over a sorted map for a key.
1264 ///
1265 /// Returns the position where that key is present, or the position where it can be inserted to
1266 /// maintain the sort. See [`slice::binary_search`] for more details.
1267 ///
1268 /// Computes in **O(log(n))** time, which is notably less scalable than looking the key up
1269 /// using [`get_index_of`][IndexMap::get_index_of], but this can also position missing keys.
1270 pub fn binary_search_keys(&self, x: &K) -> Result<usize, usize>
1271 where
1272 K: Ord,
1273 {
1274 self.as_slice().binary_search_keys(x)
1275 }
1276
1277 /// Search over a sorted map with a comparator function.
1278 ///
1279 /// Returns the position where that value is present, or the position where it can be inserted
1280 /// to maintain the sort. See [`slice::binary_search_by`] for more details.
1281 ///
1282 /// Computes in **O(log(n))** time.
1283 #[inline]
1284 pub fn binary_search_by<'a, F>(&'a self, f: F) -> Result<usize, usize>
1285 where
1286 F: FnMut(&'a K, &'a V) -> Ordering,
1287 {
1288 self.as_slice().binary_search_by(f)
1289 }
1290
1291 /// Search over a sorted map with an extraction function.
1292 ///
1293 /// Returns the position where that value is present, or the position where it can be inserted
1294 /// to maintain the sort. See [`slice::binary_search_by_key`] for more details.
1295 ///
1296 /// Computes in **O(log(n))** time.
1297 #[inline]
1298 pub fn binary_search_by_key<'a, B, F>(&'a self, b: &B, f: F) -> Result<usize, usize>
1299 where
1300 F: FnMut(&'a K, &'a V) -> B,
1301 B: Ord,
1302 {
1303 self.as_slice().binary_search_by_key(b, f)
1304 }
1305
1306 /// Checks if the keys of this map are sorted.
1307 #[inline]
1308 pub fn is_sorted(&self) -> bool
1309 where
1310 K: PartialOrd,
1311 {
1312 self.as_slice().is_sorted()
1313 }
1314
1315 /// Checks if this map is sorted using the given comparator function.
1316 #[inline]
1317 pub fn is_sorted_by<'a, F>(&'a self, cmp: F) -> bool
1318 where
1319 F: FnMut(&'a K, &'a V, &'a K, &'a V) -> bool,
1320 {
1321 self.as_slice().is_sorted_by(cmp)
1322 }
1323
1324 /// Checks if this map is sorted using the given sort-key function.
1325 #[inline]
1326 pub fn is_sorted_by_key<'a, F, T>(&'a self, sort_key: F) -> bool
1327 where
1328 F: FnMut(&'a K, &'a V) -> T,
1329 T: PartialOrd,
1330 {
1331 self.as_slice().is_sorted_by_key(sort_key)
1332 }
1333
1334 /// Returns the index of the partition point of a sorted map according to the given predicate
1335 /// (the index of the first element of the second partition).
1336 ///
1337 /// See [`slice::partition_point`] for more details.
1338 ///
1339 /// Computes in **O(log(n))** time.
1340 #[must_use]
1341 pub fn partition_point<P>(&self, pred: P) -> usize
1342 where
1343 P: FnMut(&K, &V) -> bool,
1344 {
1345 self.as_slice().partition_point(pred)
1346 }
1347
1348 /// Reverses the order of the map's key-value pairs in place.
1349 ///
1350 /// Computes in **O(n)** time and **O(1)** space.
1351 pub fn reverse(&mut self) {
1352 self.core.reverse()
1353 }
1354
1355 /// Returns a slice of all the key-value pairs in the map.
1356 ///
1357 /// Computes in **O(1)** time.
1358 pub fn as_slice(&self) -> &Slice<K, V> {
1359 Slice::from_slice(self.as_entries())
1360 }
1361
1362 /// Returns a mutable slice of all the key-value pairs in the map.
1363 ///
1364 /// Computes in **O(1)** time.
1365 pub fn as_mut_slice(&mut self) -> &mut Slice<K, V> {
1366 Slice::from_mut_slice(self.as_entries_mut())
1367 }
1368
1369 /// Converts into a boxed slice of all the key-value pairs in the map.
1370 ///
1371 /// Note that this will drop the inner hash table and any excess capacity.
1372 pub fn into_boxed_slice(self) -> Box<Slice<K, V>> {
1373 Slice::from_boxed(self.into_entries().into_boxed_slice())
1374 }
1375
1376 /// Get a key-value pair by index
1377 ///
1378 /// Valid indices are `0 <= index < self.len()`.
1379 ///
1380 /// Computes in **O(1)** time.
1381 pub fn get_index(&self, index: usize) -> Option<(&K, &V)> {
1382 self.as_entries().get(index).map(Bucket::refs)
1383 }
1384
1385 /// Get a key-value pair by index
1386 ///
1387 /// Valid indices are `0 <= index < self.len()`.
1388 ///
1389 /// Computes in **O(1)** time.
1390 pub fn get_index_mut(&mut self, index: usize) -> Option<(&K, &mut V)> {
1391 self.as_entries_mut().get_mut(index).map(Bucket::ref_mut)
1392 }
1393
1394 /// Get an entry in the map by index for in-place manipulation.
1395 ///
1396 /// Valid indices are `0 <= index < self.len()`.
1397 ///
1398 /// Computes in **O(1)** time.
1399 pub fn get_index_entry(&mut self, index: usize) -> Option<IndexedEntry<'_, K, V>> {
1400 if index >= self.len() {
1401 return None;
1402 }
1403 Some(IndexedEntry::new(&mut self.core, index))
1404 }
1405
1406 /// Get an array of `N` key-value pairs by `N` indices
1407 ///
1408 /// Valid indices are *0 <= index < self.len()* and each index needs to be unique.
1409 ///
1410 /// # Examples
1411 ///
1412 /// ```
1413 /// let mut map = indexmap::IndexMap::from([(1, 'a'), (3, 'b'), (2, 'c')]);
1414 /// assert_eq!(map.get_disjoint_indices_mut([2, 0]), Ok([(&2, &mut 'c'), (&1, &mut 'a')]));
1415 /// ```
1416 pub fn get_disjoint_indices_mut<const N: usize>(
1417 &mut self,
1418 indices: [usize; N],
1419 ) -> Result<[(&K, &mut V); N], GetDisjointMutError> {
1420 self.as_mut_slice().get_disjoint_mut(indices)
1421 }
1422
1423 /// Returns a slice of key-value pairs in the given range of indices.
1424 ///
1425 /// Valid indices are `0 <= index < self.len()`.
1426 ///
1427 /// Computes in **O(1)** time.
1428 pub fn get_range<R: RangeBounds<usize>>(&self, range: R) -> Option<&Slice<K, V>> {
1429 let entries = self.as_entries();
1430 let range = try_simplify_range(range, entries.len())?;
1431 entries.get(range).map(Slice::from_slice)
1432 }
1433
1434 /// Returns a mutable slice of key-value pairs in the given range of indices.
1435 ///
1436 /// Valid indices are `0 <= index < self.len()`.
1437 ///
1438 /// Computes in **O(1)** time.
1439 pub fn get_range_mut<R: RangeBounds<usize>>(&mut self, range: R) -> Option<&mut Slice<K, V>> {
1440 let entries = self.as_entries_mut();
1441 let range = try_simplify_range(range, entries.len())?;
1442 entries.get_mut(range).map(Slice::from_mut_slice)
1443 }
1444
1445 /// Get the first key-value pair
1446 ///
1447 /// Computes in **O(1)** time.
1448 #[doc(alias = "first_key_value")] // like `BTreeMap`
1449 pub fn first(&self) -> Option<(&K, &V)> {
1450 self.as_entries().first().map(Bucket::refs)
1451 }
1452
1453 /// Get the first key-value pair, with mutable access to the value
1454 ///
1455 /// Computes in **O(1)** time.
1456 pub fn first_mut(&mut self) -> Option<(&K, &mut V)> {
1457 self.as_entries_mut().first_mut().map(Bucket::ref_mut)
1458 }
1459
1460 /// Get the first entry in the map for in-place manipulation.
1461 ///
1462 /// Computes in **O(1)** time.
1463 pub fn first_entry(&mut self) -> Option<IndexedEntry<'_, K, V>> {
1464 self.get_index_entry(0)
1465 }
1466
1467 /// Get the last key-value pair
1468 ///
1469 /// Computes in **O(1)** time.
1470 #[doc(alias = "last_key_value")] // like `BTreeMap`
1471 pub fn last(&self) -> Option<(&K, &V)> {
1472 self.as_entries().last().map(Bucket::refs)
1473 }
1474
1475 /// Get the last key-value pair, with mutable access to the value
1476 ///
1477 /// Computes in **O(1)** time.
1478 pub fn last_mut(&mut self) -> Option<(&K, &mut V)> {
1479 self.as_entries_mut().last_mut().map(Bucket::ref_mut)
1480 }
1481
1482 /// Get the last entry in the map for in-place manipulation.
1483 ///
1484 /// Computes in **O(1)** time.
1485 pub fn last_entry(&mut self) -> Option<IndexedEntry<'_, K, V>> {
1486 self.get_index_entry(self.len().checked_sub(1)?)
1487 }
1488
1489 /// Remove the key-value pair by index
1490 ///
1491 /// Valid indices are `0 <= index < self.len()`.
1492 ///
1493 /// Like [`Vec::swap_remove`], the pair is removed by swapping it with the
1494 /// last element of the map and popping it off. **This perturbs
1495 /// the position of what used to be the last element!**
1496 ///
1497 /// Computes in **O(1)** time (average).
1498 pub fn swap_remove_index(&mut self, index: usize) -> Option<(K, V)> {
1499 self.core.swap_remove_index(index)
1500 }
1501
1502 /// Remove the key-value pair by index
1503 ///
1504 /// Valid indices are `0 <= index < self.len()`.
1505 ///
1506 /// Like [`Vec::remove`], the pair is removed by shifting all of the
1507 /// elements that follow it, preserving their relative order.
1508 /// **This perturbs the index of all of those elements!**
1509 ///
1510 /// Computes in **O(n)** time (average).
1511 pub fn shift_remove_index(&mut self, index: usize) -> Option<(K, V)> {
1512 self.core.shift_remove_index(index)
1513 }
1514
1515 /// Moves the position of a key-value pair from one index to another
1516 /// by shifting all other pairs in-between.
1517 ///
1518 /// * If `from < to`, the other pairs will shift down while the targeted pair moves up.
1519 /// * If `from > to`, the other pairs will shift up while the targeted pair moves down.
1520 ///
1521 /// ***Panics*** if `from` or `to` are out of bounds.
1522 ///
1523 /// Computes in **O(n)** time (average).
1524 #[track_caller]
1525 pub fn move_index(&mut self, from: usize, to: usize) {
1526 self.core.move_index(from, to)
1527 }
1528
1529 /// Swaps the position of two key-value pairs in the map.
1530 ///
1531 /// ***Panics*** if `a` or `b` are out of bounds.
1532 ///
1533 /// Computes in **O(1)** time (average).
1534 #[track_caller]
1535 pub fn swap_indices(&mut self, a: usize, b: usize) {
1536 self.core.swap_indices(a, b)
1537 }
1538}
1539
1540/// Access [`IndexMap`] values corresponding to a key.
1541///
1542/// # Examples
1543///
1544/// ```
1545/// use indexmap::IndexMap;
1546///
1547/// let mut map = IndexMap::new();
1548/// for word in "Lorem ipsum dolor sit amet".split_whitespace() {
1549/// map.insert(word.to_lowercase(), word.to_uppercase());
1550/// }
1551/// assert_eq!(map["lorem"], "LOREM");
1552/// assert_eq!(map["ipsum"], "IPSUM");
1553/// ```
1554///
1555/// ```should_panic
1556/// use indexmap::IndexMap;
1557///
1558/// let mut map = IndexMap::new();
1559/// map.insert("foo", 1);
1560/// println!("{:?}", map["bar"]); // panics!
1561/// ```
1562impl<K, V, Q: ?Sized, S> Index<&Q> for IndexMap<K, V, S>
1563where
1564 Q: Hash + Equivalent<K>,
1565 S: BuildHasher,
1566{
1567 type Output = V;
1568
1569 /// Returns a reference to the value corresponding to the supplied `key`.
1570 ///
1571 /// ***Panics*** if `key` is not present in the map.
1572 fn index(&self, key: &Q) -> &V {
1573 self.get(key).expect("no entry found for key")
1574 }
1575}
1576
1577/// Access [`IndexMap`] values corresponding to a key.
1578///
1579/// Mutable indexing allows changing / updating values of key-value
1580/// pairs that are already present.
1581///
1582/// You can **not** insert new pairs with index syntax, use `.insert()`.
1583///
1584/// # Examples
1585///
1586/// ```
1587/// use indexmap::IndexMap;
1588///
1589/// let mut map = IndexMap::new();
1590/// for word in "Lorem ipsum dolor sit amet".split_whitespace() {
1591/// map.insert(word.to_lowercase(), word.to_string());
1592/// }
1593/// let lorem = &mut map["lorem"];
1594/// assert_eq!(lorem, "Lorem");
1595/// lorem.retain(char::is_lowercase);
1596/// assert_eq!(map["lorem"], "orem");
1597/// ```
1598///
1599/// ```should_panic
1600/// use indexmap::IndexMap;
1601///
1602/// let mut map = IndexMap::new();
1603/// map.insert("foo", 1);
1604/// map["bar"] = 1; // panics!
1605/// ```
1606impl<K, V, Q: ?Sized, S> IndexMut<&Q> for IndexMap<K, V, S>
1607where
1608 Q: Hash + Equivalent<K>,
1609 S: BuildHasher,
1610{
1611 /// Returns a mutable reference to the value corresponding to the supplied `key`.
1612 ///
1613 /// ***Panics*** if `key` is not present in the map.
1614 fn index_mut(&mut self, key: &Q) -> &mut V {
1615 self.get_mut(key).expect("no entry found for key")
1616 }
1617}
1618
1619/// Access [`IndexMap`] values at indexed positions.
1620///
1621/// See [`Index<usize> for Keys`][keys] to access a map's keys instead.
1622///
1623/// [keys]: Keys#impl-Index<usize>-for-Keys<'a,+K,+V>
1624///
1625/// # Examples
1626///
1627/// ```
1628/// use indexmap::IndexMap;
1629///
1630/// let mut map = IndexMap::new();
1631/// for word in "Lorem ipsum dolor sit amet".split_whitespace() {
1632/// map.insert(word.to_lowercase(), word.to_uppercase());
1633/// }
1634/// assert_eq!(map[0], "LOREM");
1635/// assert_eq!(map[1], "IPSUM");
1636/// map.reverse();
1637/// assert_eq!(map[0], "AMET");
1638/// assert_eq!(map[1], "SIT");
1639/// map.sort_keys();
1640/// assert_eq!(map[0], "AMET");
1641/// assert_eq!(map[1], "DOLOR");
1642/// ```
1643///
1644/// ```should_panic
1645/// use indexmap::IndexMap;
1646///
1647/// let mut map = IndexMap::new();
1648/// map.insert("foo", 1);
1649/// println!("{:?}", map[10]); // panics!
1650/// ```
1651impl<K, V, S> Index<usize> for IndexMap<K, V, S> {
1652 type Output = V;
1653
1654 /// Returns a reference to the value at the supplied `index`.
1655 ///
1656 /// ***Panics*** if `index` is out of bounds.
1657 fn index(&self, index: usize) -> &V {
1658 if let Some((_, value)) = self.get_index(index) {
1659 value
1660 } else {
1661 panic!(
1662 "index out of bounds: the len is {len} but the index is {index}",
1663 len = self.len()
1664 );
1665 }
1666 }
1667}
1668
1669/// Access [`IndexMap`] values at indexed positions.
1670///
1671/// Mutable indexing allows changing / updating indexed values
1672/// that are already present.
1673///
1674/// You can **not** insert new values with index syntax -- use [`.insert()`][IndexMap::insert].
1675///
1676/// # Examples
1677///
1678/// ```
1679/// use indexmap::IndexMap;
1680///
1681/// let mut map = IndexMap::new();
1682/// for word in "Lorem ipsum dolor sit amet".split_whitespace() {
1683/// map.insert(word.to_lowercase(), word.to_string());
1684/// }
1685/// let lorem = &mut map[0];
1686/// assert_eq!(lorem, "Lorem");
1687/// lorem.retain(char::is_lowercase);
1688/// assert_eq!(map["lorem"], "orem");
1689/// ```
1690///
1691/// ```should_panic
1692/// use indexmap::IndexMap;
1693///
1694/// let mut map = IndexMap::new();
1695/// map.insert("foo", 1);
1696/// map[10] = 1; // panics!
1697/// ```
1698impl<K, V, S> IndexMut<usize> for IndexMap<K, V, S> {
1699 /// Returns a mutable reference to the value at the supplied `index`.
1700 ///
1701 /// ***Panics*** if `index` is out of bounds.
1702 fn index_mut(&mut self, index: usize) -> &mut V {
1703 let len: usize = self.len();
1704
1705 if let Some((_, value)) = self.get_index_mut(index) {
1706 value
1707 } else {
1708 panic!("index out of bounds: the len is {len} but the index is {index}");
1709 }
1710 }
1711}
1712
1713impl<K, V, S> FromIterator<(K, V)> for IndexMap<K, V, S>
1714where
1715 K: Hash + Eq,
1716 S: BuildHasher + Default,
1717{
1718 /// Create an `IndexMap` from the sequence of key-value pairs in the
1719 /// iterable.
1720 ///
1721 /// `from_iter` uses the same logic as `extend`. See
1722 /// [`extend`][IndexMap::extend] for more details.
1723 fn from_iter<I: IntoIterator<Item = (K, V)>>(iterable: I) -> Self {
1724 let iter = iterable.into_iter();
1725 let (low, _) = iter.size_hint();
1726 let mut map = Self::with_capacity_and_hasher(low, <_>::default());
1727 map.extend(iter);
1728 map
1729 }
1730}
1731
1732#[cfg(feature = "std")]
1733#[cfg_attr(docsrs, doc(cfg(feature = "std")))]
1734impl<K, V, const N: usize> From<[(K, V); N]> for IndexMap<K, V, RandomState>
1735where
1736 K: Hash + Eq,
1737{
1738 /// # Examples
1739 ///
1740 /// ```
1741 /// use indexmap::IndexMap;
1742 ///
1743 /// let map1 = IndexMap::from([(1, 2), (3, 4)]);
1744 /// let map2: IndexMap<_, _> = [(1, 2), (3, 4)].into();
1745 /// assert_eq!(map1, map2);
1746 /// ```
1747 fn from(arr: [(K, V); N]) -> Self {
1748 Self::from_iter(arr)
1749 }
1750}
1751
1752impl<K, V, S> Extend<(K, V)> for IndexMap<K, V, S>
1753where
1754 K: Hash + Eq,
1755 S: BuildHasher,
1756{
1757 /// Extend the map with all key-value pairs in the iterable.
1758 ///
1759 /// This is equivalent to calling [`insert`][IndexMap::insert] for each of
1760 /// them in order, which means that for keys that already existed
1761 /// in the map, their value is updated but it keeps the existing order.
1762 ///
1763 /// New keys are inserted in the order they appear in the sequence. If
1764 /// equivalents of a key occur more than once, the last corresponding value
1765 /// prevails.
1766 fn extend<I: IntoIterator<Item = (K, V)>>(&mut self, iterable: I) {
1767 // (Note: this is a copy of `std`/`hashbrown`'s reservation logic.)
1768 // Keys may be already present or show multiple times in the iterator.
1769 // Reserve the entire hint lower bound if the map is empty.
1770 // Otherwise reserve half the hint (rounded up), so the map
1771 // will only resize twice in the worst case.
1772 let iter = iterable.into_iter();
1773 let reserve = if self.is_empty() {
1774 iter.size_hint().0
1775 } else {
1776 (iter.size_hint().0 + 1) / 2
1777 };
1778 self.reserve(reserve);
1779 iter.for_each(move |(k, v)| {
1780 self.insert(k, v);
1781 });
1782 }
1783}
1784
1785impl<'a, K, V, S> Extend<(&'a K, &'a V)> for IndexMap<K, V, S>
1786where
1787 K: Hash + Eq + Copy,
1788 V: Copy,
1789 S: BuildHasher,
1790{
1791 /// Extend the map with all key-value pairs in the iterable.
1792 ///
1793 /// See the first extend method for more details.
1794 fn extend<I: IntoIterator<Item = (&'a K, &'a V)>>(&mut self, iterable: I) {
1795 self.extend(iterable.into_iter().map(|(&key, &value)| (key, value)));
1796 }
1797}
1798
1799impl<K, V, S> Default for IndexMap<K, V, S>
1800where
1801 S: Default,
1802{
1803 /// Return an empty [`IndexMap`]
1804 fn default() -> Self {
1805 Self::with_capacity_and_hasher(0, S::default())
1806 }
1807}
1808
1809impl<K, V1, S1, V2, S2> PartialEq<IndexMap<K, V2, S2>> for IndexMap<K, V1, S1>
1810where
1811 K: Hash + Eq,
1812 V1: PartialEq<V2>,
1813 S1: BuildHasher,
1814 S2: BuildHasher,
1815{
1816 fn eq(&self, other: &IndexMap<K, V2, S2>) -> bool {
1817 if self.len() != other.len() {
1818 return false;
1819 }
1820
1821 self.iter()
1822 .all(|(key, value)| other.get(key).map_or(false, |v| *value == *v))
1823 }
1824}
1825
1826impl<K, V, S> Eq for IndexMap<K, V, S>
1827where
1828 K: Eq + Hash,
1829 V: Eq,
1830 S: BuildHasher,
1831{
1832}