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