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