indexmap/map/core/entry.rs
1use super::{equivalent, get_hash, Bucket, IndexMapCore};
2use crate::HashValue;
3use core::cmp::Ordering;
4use core::{fmt, mem};
5
6/// Entry for an existing key-value pair in an [`IndexMap`][crate::IndexMap]
7/// or a vacant location to insert one.
8pub enum Entry<'a, K, V> {
9 /// Existing slot with equivalent key.
10 Occupied(OccupiedEntry<'a, K, V>),
11 /// Vacant slot (no equivalent key in the map).
12 Vacant(VacantEntry<'a, K, V>),
13}
14
15impl<'a, K, V> Entry<'a, K, V> {
16 pub(crate) fn new(map: &'a mut IndexMapCore<K, V>, hash: HashValue, key: K) -> Self
17 where
18 K: Eq,
19 {
20 let eq = equivalent(&key, &map.entries);
21 match map.indices.find_entry(hash.get(), eq) {
22 Ok(entry) => Entry::Occupied(OccupiedEntry {
23 bucket: entry.bucket_index(),
24 index: *entry.get(),
25 map,
26 }),
27 Err(_) => Entry::Vacant(VacantEntry { map, hash, key }),
28 }
29 }
30
31 /// Return the index where the key-value pair exists or will be inserted.
32 pub fn index(&self) -> usize {
33 match self {
34 Entry::Occupied(entry) => entry.index,
35 Entry::Vacant(entry) => entry.index(),
36 }
37 }
38
39 /// Sets the value of the entry (after inserting if vacant), and returns an `OccupiedEntry`.
40 ///
41 /// Computes in **O(1)** time (amortized average).
42 pub fn insert_entry(self, value: V) -> OccupiedEntry<'a, K, V> {
43 match self {
44 Entry::Occupied(mut entry) => {
45 entry.insert(value);
46 entry
47 }
48 Entry::Vacant(entry) => entry.insert_entry(value),
49 }
50 }
51
52 /// Inserts the given default value in the entry if it is vacant and returns a mutable
53 /// reference to it. Otherwise a mutable reference to an already existent value is returned.
54 ///
55 /// Computes in **O(1)** time (amortized average).
56 pub fn or_insert(self, default: V) -> &'a mut V {
57 match self {
58 Entry::Occupied(entry) => entry.into_mut(),
59 Entry::Vacant(entry) => entry.insert(default),
60 }
61 }
62
63 /// Inserts the result of the `call` function in the entry if it is vacant and returns a mutable
64 /// reference to it. Otherwise a mutable reference to an already existent value is returned.
65 ///
66 /// Computes in **O(1)** time (amortized average).
67 pub fn or_insert_with<F>(self, call: F) -> &'a mut V
68 where
69 F: FnOnce() -> V,
70 {
71 match self {
72 Entry::Occupied(entry) => entry.into_mut(),
73 Entry::Vacant(entry) => entry.insert(call()),
74 }
75 }
76
77 /// Inserts the result of the `call` function with a reference to the entry's key if it is
78 /// vacant, and returns a mutable reference to the new value. Otherwise a mutable reference to
79 /// an already existent value is returned.
80 ///
81 /// Computes in **O(1)** time (amortized average).
82 pub fn or_insert_with_key<F>(self, call: F) -> &'a mut V
83 where
84 F: FnOnce(&K) -> V,
85 {
86 match self {
87 Entry::Occupied(entry) => entry.into_mut(),
88 Entry::Vacant(entry) => {
89 let value = call(&entry.key);
90 entry.insert(value)
91 }
92 }
93 }
94
95 /// Gets a reference to the entry's key, either within the map if occupied,
96 /// or else the new key that was used to find the entry.
97 pub fn key(&self) -> &K {
98 match *self {
99 Entry::Occupied(ref entry) => entry.key(),
100 Entry::Vacant(ref entry) => entry.key(),
101 }
102 }
103
104 /// Modifies the entry if it is occupied.
105 pub fn and_modify<F>(mut self, f: F) -> Self
106 where
107 F: FnOnce(&mut V),
108 {
109 if let Entry::Occupied(entry) = &mut self {
110 f(entry.get_mut());
111 }
112 self
113 }
114
115 /// Inserts a default-constructed value in the entry if it is vacant and returns a mutable
116 /// reference to it. Otherwise a mutable reference to an already existent value is returned.
117 ///
118 /// Computes in **O(1)** time (amortized average).
119 pub fn or_default(self) -> &'a mut V
120 where
121 V: Default,
122 {
123 match self {
124 Entry::Occupied(entry) => entry.into_mut(),
125 Entry::Vacant(entry) => entry.insert(V::default()),
126 }
127 }
128}
129
130impl<K: fmt::Debug, V: fmt::Debug> fmt::Debug for Entry<'_, K, V> {
131 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
132 let mut tuple = f.debug_tuple("Entry");
133 match self {
134 Entry::Vacant(v) => tuple.field(v),
135 Entry::Occupied(o) => tuple.field(o),
136 };
137 tuple.finish()
138 }
139}
140
141/// A view into an occupied entry in an [`IndexMap`][crate::IndexMap].
142/// It is part of the [`Entry`] enum.
143pub struct OccupiedEntry<'a, K, V> {
144 map: &'a mut IndexMapCore<K, V>,
145 // We have a mutable reference to the map, which keeps these two
146 // indices valid and pointing to the correct entry.
147 index: usize,
148 bucket: usize,
149}
150
151impl<'a, K, V> OccupiedEntry<'a, K, V> {
152 /// Constructor for `RawEntryMut::from_hash`
153 pub(super) fn from_hash<F>(
154 map: &'a mut IndexMapCore<K, V>,
155 hash: u64,
156 mut is_match: F,
157 ) -> Result<Self, &'a mut IndexMapCore<K, V>>
158 where
159 F: FnMut(&K) -> bool,
160 {
161 let entries = &*map.entries;
162 let eq = move |&i: &usize| is_match(&entries[i].key);
163 match map.indices.find_entry(hash, eq) {
164 Ok(entry) => Ok(OccupiedEntry {
165 bucket: entry.bucket_index(),
166 index: *entry.get(),
167 map,
168 }),
169 Err(_) => Err(map),
170 }
171 }
172
173 pub(crate) fn get_bucket(&self) -> &Bucket<K, V> {
174 &self.map.entries[self.index]
175 }
176
177 pub(crate) fn get_bucket_mut(&mut self) -> &mut Bucket<K, V> {
178 &mut self.map.entries[self.index]
179 }
180
181 pub(crate) fn into_bucket(self) -> &'a mut Bucket<K, V> {
182 &mut self.map.entries[self.index]
183 }
184
185 /// Return the index of the key-value pair
186 #[inline]
187 pub fn index(&self) -> usize {
188 self.index
189 }
190
191 /// Gets a reference to the entry's key in the map.
192 ///
193 /// Note that this is not the key that was used to find the entry. There may be an observable
194 /// difference if the key type has any distinguishing features outside of `Hash` and `Eq`, like
195 /// extra fields or the memory address of an allocation.
196 pub fn key(&self) -> &K {
197 &self.map.entries[self.index].key
198 }
199
200 /// Gets a reference to the entry's value in the map.
201 pub fn get(&self) -> &V {
202 &self.map.entries[self.index].value
203 }
204
205 /// Gets a mutable reference to the entry's value in the map.
206 ///
207 /// If you need a reference which may outlive the destruction of the
208 /// [`Entry`] value, see [`into_mut`][Self::into_mut].
209 pub fn get_mut(&mut self) -> &mut V {
210 &mut self.map.entries[self.index].value
211 }
212
213 /// Converts into a mutable reference to the entry's value in the map,
214 /// with a lifetime bound to the map itself.
215 pub fn into_mut(self) -> &'a mut V {
216 &mut self.map.entries[self.index].value
217 }
218
219 /// Sets the value of the entry to `value`, and returns the entry's old value.
220 pub fn insert(&mut self, value: V) -> V {
221 mem::replace(self.get_mut(), value)
222 }
223
224 /// Remove the key, value pair stored in the map for this entry, and return the value.
225 ///
226 /// **NOTE:** This is equivalent to [`.swap_remove()`][Self::swap_remove], replacing this
227 /// entry's position with the last element, and it is deprecated in favor of calling that
228 /// explicitly. If you need to preserve the relative order of the keys in the map, use
229 /// [`.shift_remove()`][Self::shift_remove] instead.
230 #[deprecated(note = "`remove` disrupts the map order -- \
231 use `swap_remove` or `shift_remove` for explicit behavior.")]
232 pub fn remove(self) -> V {
233 self.swap_remove()
234 }
235
236 /// Remove the key, value pair stored in the map for this entry, and return the value.
237 ///
238 /// Like [`Vec::swap_remove`][alloc::vec::Vec::swap_remove], the pair is removed by swapping it
239 /// with the last element of the map and popping it off.
240 /// **This perturbs the position of what used to be the last element!**
241 ///
242 /// Computes in **O(1)** time (average).
243 pub fn swap_remove(self) -> V {
244 self.swap_remove_entry().1
245 }
246
247 /// Remove the key, value pair stored in the map for this entry, and return the value.
248 ///
249 /// Like [`Vec::remove`][alloc::vec::Vec::remove], the pair is removed by shifting all of the
250 /// elements that follow it, preserving their relative order.
251 /// **This perturbs the index of all of those elements!**
252 ///
253 /// Computes in **O(n)** time (average).
254 pub fn shift_remove(self) -> V {
255 self.shift_remove_entry().1
256 }
257
258 /// Remove and return the key, value pair stored in the map for this entry
259 ///
260 /// **NOTE:** This is equivalent to [`.swap_remove_entry()`][Self::swap_remove_entry],
261 /// replacing this entry's position with the last element, and it is deprecated in favor of
262 /// calling that explicitly. If you need to preserve the relative order of the keys in the map,
263 /// use [`.shift_remove_entry()`][Self::shift_remove_entry] instead.
264 #[deprecated(note = "`remove_entry` disrupts the map order -- \
265 use `swap_remove_entry` or `shift_remove_entry` for explicit behavior.")]
266 pub fn remove_entry(self) -> (K, V) {
267 self.swap_remove_entry()
268 }
269
270 /// Remove and return the key, value pair stored in the map for this entry
271 ///
272 /// Like [`Vec::swap_remove`][alloc::vec::Vec::swap_remove], the pair is removed by swapping it
273 /// with the last element of the map and popping it off.
274 /// **This perturbs the position of what used to be the last element!**
275 ///
276 /// Computes in **O(1)** time (average).
277 pub fn swap_remove_entry(mut self) -> (K, V) {
278 self.remove_index();
279 self.map.swap_remove_finish(self.index)
280 }
281
282 /// Remove and return the key, value pair stored in the map for this entry
283 ///
284 /// Like [`Vec::remove`][alloc::vec::Vec::remove], the pair is removed by shifting all of the
285 /// elements that follow it, preserving their relative order.
286 /// **This perturbs the index of all of those elements!**
287 ///
288 /// Computes in **O(n)** time (average).
289 pub fn shift_remove_entry(mut self) -> (K, V) {
290 self.remove_index();
291 self.map.shift_remove_finish(self.index)
292 }
293
294 fn remove_index(&mut self) {
295 let entry = self.map.indices.get_bucket_entry(self.bucket).unwrap();
296 debug_assert_eq!(*entry.get(), self.index);
297 entry.remove();
298 }
299
300 /// Moves the position of the entry to a new index
301 /// by shifting all other entries in-between.
302 ///
303 /// This is equivalent to [`IndexMap::move_index`][`crate::IndexMap::move_index`]
304 /// coming `from` the current [`.index()`][Self::index].
305 ///
306 /// * If `self.index() < to`, the other pairs will shift down while the targeted pair moves up.
307 /// * If `self.index() > to`, the other pairs will shift up while the targeted pair moves down.
308 ///
309 /// ***Panics*** if `to` is out of bounds.
310 ///
311 /// Computes in **O(n)** time (average).
312 #[track_caller]
313 pub fn move_index(self, to: usize) {
314 if self.index != to {
315 let _ = self.map.entries[to]; // explicit bounds check
316 self.map.move_index_inner(self.index, to);
317 self.update_index(to);
318 }
319 }
320
321 /// Swaps the position of entry with another.
322 ///
323 /// This is equivalent to [`IndexMap::swap_indices`][`crate::IndexMap::swap_indices`]
324 /// with the current [`.index()`][Self::index] as one of the two being swapped.
325 ///
326 /// ***Panics*** if the `other` index is out of bounds.
327 ///
328 /// Computes in **O(1)** time (average).
329 #[track_caller]
330 pub fn swap_indices(self, other: usize) {
331 if self.index != other {
332 // Since we already know where our bucket is, we only need to find the other.
333 let hash = self.map.entries[other].hash;
334 let other_mut = self.map.indices.find_mut(hash.get(), move |&i| i == other);
335 *other_mut.expect("index not found") = self.index;
336
337 self.map.entries.swap(self.index, other);
338 self.update_index(other);
339 }
340 }
341
342 fn update_index(self, to: usize) {
343 let index = self.map.indices.get_bucket_mut(self.bucket).unwrap();
344 debug_assert_eq!(*index, self.index);
345 *index = to;
346 }
347}
348
349impl<K: fmt::Debug, V: fmt::Debug> fmt::Debug for OccupiedEntry<'_, K, V> {
350 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
351 f.debug_struct("OccupiedEntry")
352 .field("key", self.key())
353 .field("value", self.get())
354 .finish()
355 }
356}
357
358impl<'a, K, V> From<IndexedEntry<'a, K, V>> for OccupiedEntry<'a, K, V> {
359 fn from(other: IndexedEntry<'a, K, V>) -> Self {
360 let IndexedEntry { map, index } = other;
361 let hash = map.entries[index].hash;
362 let bucket = map
363 .indices
364 .find_bucket_index(hash.get(), move |&i| i == index)
365 .expect("index not found");
366 Self { map, index, bucket }
367 }
368}
369
370/// A view into a vacant entry in an [`IndexMap`][crate::IndexMap].
371/// It is part of the [`Entry`] enum.
372pub struct VacantEntry<'a, K, V> {
373 map: &'a mut IndexMapCore<K, V>,
374 hash: HashValue,
375 key: K,
376}
377
378impl<'a, K, V> VacantEntry<'a, K, V> {
379 /// Return the index where a key-value pair may be inserted.
380 pub fn index(&self) -> usize {
381 self.map.indices.len()
382 }
383
384 /// Gets a reference to the key that was used to find the entry.
385 pub fn key(&self) -> &K {
386 &self.key
387 }
388
389 pub(crate) fn key_mut(&mut self) -> &mut K {
390 &mut self.key
391 }
392
393 /// Takes ownership of the key, leaving the entry vacant.
394 pub fn into_key(self) -> K {
395 self.key
396 }
397
398 /// Inserts the entry's key and the given value into the map, and returns a mutable reference
399 /// to the value.
400 ///
401 /// Computes in **O(1)** time (amortized average).
402 pub fn insert(self, value: V) -> &'a mut V {
403 let Self { map, hash, key } = self;
404 map.insert_unique(hash, key, value).value_mut()
405 }
406
407 /// Inserts the entry's key and the given value into the map, and returns an `OccupiedEntry`.
408 ///
409 /// Computes in **O(1)** time (amortized average).
410 pub fn insert_entry(self, value: V) -> OccupiedEntry<'a, K, V> {
411 let Self { map, hash, key } = self;
412 let index = map.indices.len();
413 debug_assert_eq!(index, map.entries.len());
414 let bucket = map
415 .indices
416 .insert_unique(hash.get(), index, get_hash(&map.entries))
417 .bucket_index();
418 map.push_entry(hash, key, value);
419 OccupiedEntry { map, index, bucket }
420 }
421
422 /// Inserts the entry's key and the given value into the map at its ordered
423 /// position among sorted keys, and returns the new index and a mutable
424 /// reference to the value.
425 ///
426 /// If the existing keys are **not** already sorted, then the insertion
427 /// index is unspecified (like [`slice::binary_search`]), but the key-value
428 /// pair is inserted at that position regardless.
429 ///
430 /// Computes in **O(n)** time (average).
431 pub fn insert_sorted(self, value: V) -> (usize, &'a mut V)
432 where
433 K: Ord,
434 {
435 let slice = crate::map::Slice::from_slice(&self.map.entries);
436 let i = slice.binary_search_keys(&self.key).unwrap_err();
437 (i, self.shift_insert(i, value))
438 }
439
440 /// Inserts the entry's key and the given value into the map at its ordered
441 /// position among keys sorted by `cmp`, and returns the new index and a
442 /// mutable reference to the value.
443 ///
444 /// If the existing keys are **not** already sorted, then the insertion
445 /// index is unspecified (like [`slice::binary_search`]), but the key-value
446 /// pair is inserted at that position regardless.
447 ///
448 /// Computes in **O(n)** time (average).
449 pub fn insert_sorted_by<F>(self, value: V, mut cmp: F) -> (usize, &'a mut V)
450 where
451 F: FnMut(&K, &V, &K, &V) -> Ordering,
452 {
453 let slice = crate::map::Slice::from_slice(&self.map.entries);
454 let (Ok(i) | Err(i)) = slice.binary_search_by(|k, v| cmp(k, v, &self.key, &value));
455 (i, self.shift_insert(i, value))
456 }
457
458 /// Inserts the entry's key and the given value into the map at its ordered
459 /// position using a sort-key extraction function, and returns the new index
460 /// and a mutable reference to the value.
461 ///
462 /// If the existing keys are **not** already sorted, then the insertion
463 /// index is unspecified (like [`slice::binary_search`]), but the key-value
464 /// pair is inserted at that position regardless.
465 ///
466 /// Computes in **O(n)** time (average).
467 pub fn insert_sorted_by_key<B, F>(self, value: V, mut sort_key: F) -> (usize, &'a mut V)
468 where
469 B: Ord,
470 F: FnMut(&K, &V) -> B,
471 {
472 let search_key = sort_key(&self.key, &value);
473 let slice = crate::map::Slice::from_slice(&self.map.entries);
474 let (Ok(i) | Err(i)) = slice.binary_search_by_key(&search_key, sort_key);
475 (i, self.shift_insert(i, value))
476 }
477
478 /// Inserts the entry's key and the given value into the map at the given index,
479 /// shifting others to the right, and returns a mutable reference to the value.
480 ///
481 /// ***Panics*** if `index` is out of bounds.
482 ///
483 /// Computes in **O(n)** time (average).
484 #[track_caller]
485 pub fn shift_insert(self, index: usize, value: V) -> &'a mut V {
486 self.map
487 .shift_insert_unique(index, self.hash, self.key, value);
488 &mut self.map.entries[index].value
489 }
490
491 /// Replaces the key at the given index with this entry's key, returning the
492 /// old key and an `OccupiedEntry` for that index.
493 ///
494 /// ***Panics*** if `index` is out of bounds.
495 ///
496 /// Computes in **O(1)** time (average).
497 #[track_caller]
498 pub fn replace_index(self, index: usize) -> (K, OccupiedEntry<'a, K, V>) {
499 let Self { map, hash, key } = self;
500
501 // NB: This removal and insertion isn't "no grow" (with unreachable hasher)
502 // because hashbrown's tombstones might force a resize anyway.
503 let old_hash = map.entries[index].hash;
504 map.indices
505 .find_entry(old_hash.get(), move |&i| i == index)
506 .expect("index not found")
507 .remove();
508 let bucket = map
509 .indices
510 .insert_unique(hash.get(), index, get_hash(&map.entries))
511 .bucket_index();
512
513 let entry = &mut map.entries[index];
514 entry.hash = hash;
515 let old_key = mem::replace(&mut entry.key, key);
516
517 (old_key, OccupiedEntry { map, index, bucket })
518 }
519}
520
521impl<K: fmt::Debug, V> fmt::Debug for VacantEntry<'_, K, V> {
522 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
523 f.debug_tuple("VacantEntry").field(self.key()).finish()
524 }
525}
526
527/// A view into an occupied entry in an [`IndexMap`][crate::IndexMap] obtained by index.
528///
529/// This `struct` is created from the [`get_index_entry`][crate::IndexMap::get_index_entry] method.
530pub struct IndexedEntry<'a, K, V> {
531 map: &'a mut IndexMapCore<K, V>,
532 // We have a mutable reference to the map, which keeps the index
533 // valid and pointing to the correct entry.
534 index: usize,
535}
536
537impl<'a, K, V> IndexedEntry<'a, K, V> {
538 pub(crate) fn new(map: &'a mut IndexMapCore<K, V>, index: usize) -> Option<Self> {
539 if index < map.len() {
540 Some(Self { map, index })
541 } else {
542 None
543 }
544 }
545
546 /// Return the index of the key-value pair
547 #[inline]
548 pub fn index(&self) -> usize {
549 self.index
550 }
551
552 /// Gets a reference to the entry's key in the map.
553 pub fn key(&self) -> &K {
554 &self.map.entries[self.index].key
555 }
556
557 pub(crate) fn key_mut(&mut self) -> &mut K {
558 &mut self.map.entries[self.index].key
559 }
560
561 /// Gets a reference to the entry's value in the map.
562 pub fn get(&self) -> &V {
563 &self.map.entries[self.index].value
564 }
565
566 /// Gets a mutable reference to the entry's value in the map.
567 ///
568 /// If you need a reference which may outlive the destruction of the
569 /// `IndexedEntry` value, see [`into_mut`][Self::into_mut].
570 pub fn get_mut(&mut self) -> &mut V {
571 &mut self.map.entries[self.index].value
572 }
573
574 /// Sets the value of the entry to `value`, and returns the entry's old value.
575 pub fn insert(&mut self, value: V) -> V {
576 mem::replace(self.get_mut(), value)
577 }
578
579 /// Converts into a mutable reference to the entry's value in the map,
580 /// with a lifetime bound to the map itself.
581 pub fn into_mut(self) -> &'a mut V {
582 &mut self.map.entries[self.index].value
583 }
584
585 /// Remove and return the key, value pair stored in the map for this entry
586 ///
587 /// Like [`Vec::swap_remove`][alloc::vec::Vec::swap_remove], the pair is removed by swapping it
588 /// with the last element of the map and popping it off.
589 /// **This perturbs the position of what used to be the last element!**
590 ///
591 /// Computes in **O(1)** time (average).
592 pub fn swap_remove_entry(self) -> (K, V) {
593 self.map.swap_remove_index(self.index).unwrap()
594 }
595
596 /// Remove and return the key, value pair stored in the map for this entry
597 ///
598 /// Like [`Vec::remove`][alloc::vec::Vec::remove], the pair is removed by shifting all of the
599 /// elements that follow it, preserving their relative order.
600 /// **This perturbs the index of all of those elements!**
601 ///
602 /// Computes in **O(n)** time (average).
603 pub fn shift_remove_entry(self) -> (K, V) {
604 self.map.shift_remove_index(self.index).unwrap()
605 }
606
607 /// Remove the key, value pair stored in the map for this entry, and return the value.
608 ///
609 /// Like [`Vec::swap_remove`][alloc::vec::Vec::swap_remove], the pair is removed by swapping it
610 /// with the last element of the map and popping it off.
611 /// **This perturbs the position of what used to be the last element!**
612 ///
613 /// Computes in **O(1)** time (average).
614 pub fn swap_remove(self) -> V {
615 self.swap_remove_entry().1
616 }
617
618 /// Remove the key, value pair stored in the map for this entry, and return the value.
619 ///
620 /// Like [`Vec::remove`][alloc::vec::Vec::remove], the pair is removed by shifting all of the
621 /// elements that follow it, preserving their relative order.
622 /// **This perturbs the index of all of those elements!**
623 ///
624 /// Computes in **O(n)** time (average).
625 pub fn shift_remove(self) -> V {
626 self.shift_remove_entry().1
627 }
628
629 /// Moves the position of the entry to a new index
630 /// by shifting all other entries in-between.
631 ///
632 /// This is equivalent to [`IndexMap::move_index`][`crate::IndexMap::move_index`]
633 /// coming `from` the current [`.index()`][Self::index].
634 ///
635 /// * If `self.index() < to`, the other pairs will shift down while the targeted pair moves up.
636 /// * If `self.index() > to`, the other pairs will shift up while the targeted pair moves down.
637 ///
638 /// ***Panics*** if `to` is out of bounds.
639 ///
640 /// Computes in **O(n)** time (average).
641 #[track_caller]
642 pub fn move_index(self, to: usize) {
643 self.map.move_index(self.index, to);
644 }
645
646 /// Swaps the position of entry with another.
647 ///
648 /// This is equivalent to [`IndexMap::swap_indices`][`crate::IndexMap::swap_indices`]
649 /// with the current [`.index()`][Self::index] as one of the two being swapped.
650 ///
651 /// ***Panics*** if the `other` index is out of bounds.
652 ///
653 /// Computes in **O(1)** time (average).
654 #[track_caller]
655 pub fn swap_indices(self, other: usize) {
656 self.map.swap_indices(self.index, other);
657 }
658}
659
660impl<K: fmt::Debug, V: fmt::Debug> fmt::Debug for IndexedEntry<'_, K, V> {
661 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
662 f.debug_struct("IndexedEntry")
663 .field("index", &self.index)
664 .field("key", self.key())
665 .field("value", self.get())
666 .finish()
667 }
668}
669
670impl<'a, K, V> From<OccupiedEntry<'a, K, V>> for IndexedEntry<'a, K, V> {
671 fn from(other: OccupiedEntry<'a, K, V>) -> Self {
672 let OccupiedEntry { map, index, .. } = other;
673 Self { map, index }
674 }
675}