Coverage Report

Created: 2021-03-22 08:29

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