Coverage Report

Created: 2026-10-28 06:37

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