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