Debian Codegraph @

src/map/entry.rs

raw symbols SCIP
1 use core::cmp::Ordering;
2 use core::fmt;
3 use indexmap::map as ix;
4
5 #[cfg(doc)]
6 use alloc::vec::Vec;
7
8 /// Entry for an existing key-value pair in an [`OrderMap`][crate::OrderMap]
9 /// or a vacant location to insert one.
10 pub enum Entry<'a, K, V> {
11 /// Existing slot with equivalent key.
12 Occupied(OccupiedEntry<'a, K, V>),
13 /// Vacant slot (no equivalent key in the map).
14 Vacant(VacantEntry<'a, K, V>),
15 }
16
17 impl<'a, K, V> Entry<'a, K, V> {
18 pub(super) fn new(entry: ix::Entry<'a, K, V>) -> Self {
19 match entry {
20 ix::Entry::Occupied(inner) => Self::Occupied(OccupiedEntry { inner }),
21 ix::Entry::Vacant(inner) => Self::Vacant(VacantEntry { inner }),
22 }
23 }
24
25 /// Return the index where the key-value pair exists or will be inserted.
26 pub fn index(&self) -> usize {
27 match *self {
28 Entry::Occupied(ref entry) => entry.index(),
29 Entry::Vacant(ref entry) => entry.index(),
30 }
31 }
32
33 /// Sets the value of the entry (after inserting if vacant), and returns an `OccupiedEntry`.
34 ///
35 /// Computes in **O(1)** time (amortized average).
36 pub fn insert_entry(self, value: V) -> OccupiedEntry<'a, K, V> {
37 match self {
38 Entry::Occupied(mut entry) => {
39 entry.insert(value);
40 entry
41 }
42 Entry::Vacant(entry) => entry.insert_entry(value),
43 }
44 }
45
46 /// Inserts the given default value in the entry if it is vacant and returns a mutable
47 /// reference to it. Otherwise a mutable reference to an already existent value is returned.
48 ///
49 /// Computes in **O(1)** time (amortized average).
50 pub fn or_insert(self, default: V) -> &'a mut V {
51 match self {
52 Entry::Occupied(entry) => entry.into_mut(),
53 Entry::Vacant(entry) => entry.insert(default),
54 }
55 }
56
57 /// Inserts the result of the `call` function in the entry if it is vacant and returns a mutable
58 /// reference to it. Otherwise a mutable reference to an already existent value is returned.
59 ///
60 /// Computes in **O(1)** time (amortized average).
61 pub fn or_insert_with<F>(self, call: F) -> &'a mut V
62 where
63 F: FnOnce() -> V,
64 {
65 match self {
66 Entry::Occupied(entry) => entry.into_mut(),
67 Entry::Vacant(entry) => entry.insert(call()),
68 }
69 }
70
71 /// Inserts the result of the `call` function with a reference to the entry's key if it is
72 /// vacant, and returns a mutable reference to the new value. Otherwise a mutable reference to
73 /// an already existent value is returned.
74 ///
75 /// Computes in **O(1)** time (amortized average).
76 pub fn or_insert_with_key<F>(self, call: F) -> &'a mut V
77 where
78 F: FnOnce(&K) -> V,
79 {
80 match self {
81 Entry::Occupied(entry) => entry.into_mut(),
82 Entry::Vacant(entry) => {
83 let value = call(&entry.key());
84 entry.insert(value)
85 }
86 }
87 }
88
89 /// Gets a reference to the entry's key, either within the map if occupied,
90 /// or else the new key that was used to find the entry.
91 pub fn key(&self) -> &K {
92 match *self {
93 Entry::Occupied(ref entry) => entry.key(),
94 Entry::Vacant(ref entry) => entry.key(),
95 }
96 }
97
98 /// Modifies the entry if it is occupied.
99 pub fn and_modify<F>(mut self, f: F) -> Self
100 where
101 F: FnOnce(&mut V),
102 {
103 if let Entry::Occupied(entry) = &mut self {
104 f(entry.get_mut());
105 }
106 self
107 }
108
109 /// Inserts a default-constructed value in the entry if it is vacant and returns a mutable
110 /// reference to it. Otherwise a mutable reference to an already existent value is returned.
111 ///
112 /// Computes in **O(1)** time (amortized average).
113 pub fn or_default(self) -> &'a mut V
114 where
115 V: Default,
116 {
117 match self {
118 Entry::Occupied(entry) => entry.into_mut(),
119 Entry::Vacant(entry) => entry.insert(V::default()),
120 }
121 }
122 }
123
124 impl<K: fmt::Debug, V: fmt::Debug> fmt::Debug for Entry<'_, K, V> {
125 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
126 let mut tuple = f.debug_tuple("Entry");
127 match self {
128 Entry::Vacant(v) => tuple.field(v),
129 Entry::Occupied(o) => tuple.field(o),
130 };
131 tuple.finish()
132 }
133 }
134
135 /// A view into an occupied entry in an [`OrderMap`][crate::OrderMap].
136 /// It is part of the [`Entry`] enum.
137 pub struct OccupiedEntry<'a, K, V> {
138 pub(crate) inner: ix::OccupiedEntry<'a, K, V>,
139 }
140
141 impl<'a, K, V> OccupiedEntry<'a, K, V> {
142 /// Return the index of the key-value pair
143 #[inline]
144 pub fn index(&self) -> usize {
145 self.inner.index()
146 }
147
148 /// Gets a reference to the entry's key in the map.
149 ///
150 /// Note that this is not the key that was used to find the entry. There may be an observable
151 /// difference if the key type has any distinguishing features outside of `Hash` and `Eq`, like
152 /// extra fields or the memory address of an allocation.
153 pub fn key(&self) -> &K {
154 self.inner.key()
155 }
156
157 /// Gets a reference to the entry's value in the map.
158 pub fn get(&self) -> &V {
159 self.inner.get()
160 }
161
162 /// Gets a mutable reference to the entry's value in the map.
163 ///
164 /// If you need a reference which may outlive the destruction of the
165 /// [`Entry`] value, see [`into_mut`][Self::into_mut].
166 pub fn get_mut(&mut self) -> &mut V {
167 self.inner.get_mut()
168 }
169
170 /// Converts into a mutable reference to the entry's value in the map,
171 /// with a lifetime bound to the map itself.
172 pub fn into_mut(self) -> &'a mut V {
173 self.inner.into_mut()
174 }
175
176 /// Sets the value of the entry to `value`, and returns the entry's old value.
177 pub fn insert(&mut self, value: V) -> V {
178 self.inner.insert(value)
179 }
180
181 /// Remove the key, value pair stored in the map for this entry, and return the value.
182 ///
183 /// **NOTE:** This is equivalent to indexmap's
184 /// [`OccupiedEntry::shift_remove`][ix::OccupiedEntry::shift_remove], and
185 /// like [`Vec::remove`], the pair is removed by shifting all of the
186 /// elements that follow it, preserving their relative order.
187 /// **This perturbs the index of all of those elements!**
188 ///
189 /// Computes in **O(n)** time (average).
190 pub fn remove(self) -> V {
191 self.inner.shift_remove()
192 }
193
194 /// Remove and return the key, value pair stored in the map for this entry
195 ///
196 /// **NOTE:** This is equivalent to indexmap's
197 /// [`OccupiedEntry::shift_remove_entry`][ix::OccupiedEntry::shift_remove_entry], and
198 /// like [`Vec::remove`], the pair is removed by shifting all of the
199 /// elements that follow it, preserving their relative order.
200 /// **This perturbs the index of all of those elements!**
201 ///
202 /// Computes in **O(n)** time (average).
203 pub fn remove_entry(self) -> (K, V) {
204 self.inner.shift_remove_entry()
205 }
206
207 /// Remove the key, value pair stored in the map for this entry, and return the value.
208 ///
209 /// Like [`Vec::swap_remove`], the pair is removed by swapping it with
210 /// the last element of the map and popping it off.
211 /// **This perturbs the position of what used to be the last element!**
212 ///
213 /// Computes in **O(1)** time (average).
214 pub fn swap_remove(self) -> V {
215 self.inner.swap_remove()
216 }
217
218 /// Remove and return the key, value pair stored in the map for this entry
219 ///
220 /// Like [`Vec::swap_remove`], the pair is removed by swapping it with
221 /// the last element of the map and popping it off.
222 /// **This perturbs the position of what used to be the last element!**
223 ///
224 /// Computes in **O(1)** time (average).
225 pub fn swap_remove_entry(self) -> (K, V) {
226 self.inner.swap_remove_entry()
227 }
228
229 /// Moves the position of the entry to a new index
230 /// by shifting all other entries in-between.
231 ///
232 /// This is equivalent to [`OrderMap::move_index`][`crate::OrderMap::move_index`]
233 /// coming `from` the current [`.index()`][Self::index].
234 ///
235 /// * If `self.index() < to`, the other pairs will shift down while the targeted pair moves up.
236 /// * If `self.index() > to`, the other pairs will shift up while the targeted pair moves down.
237 ///
238 /// ***Panics*** if `to` is out of bounds.
239 ///
240 /// Computes in **O(n)** time (average).
241 #[track_caller]
242 pub fn move_index(self, to: usize) {
243 self.inner.move_index(to);
244 }
245
246 /// Swaps the position of entry with another.
247 ///
248 /// This is equivalent to [`OrderMap::swap_indices`][`crate::OrderMap::swap_indices`]
249 /// with the current [`.index()`][Self::index] as one of the two being swapped.
250 ///
251 /// ***Panics*** if the `other` index is out of bounds.
252 ///
253 /// Computes in **O(1)** time (average).
254 #[track_caller]
255 pub fn swap_indices(self, other: usize) {
256 self.inner.swap_indices(other);
257 }
258 }
259
260 impl<K: fmt::Debug, V: fmt::Debug> fmt::Debug for OccupiedEntry<'_, K, V> {
261 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
262 f.debug_struct("OccupiedEntry")
263 .field("key", self.key())
264 .field("value", self.get())
265 .finish()
266 }
267 }
268
269 impl<'a, K, V> From<IndexedEntry<'a, K, V>> for OccupiedEntry<'a, K, V> {
270 fn from(entry: IndexedEntry<'a, K, V>) -> Self {
271 Self {
272 inner: entry.inner.into(),
273 }
274 }
275 }
276
277 /// A view into a vacant entry in an [`OrderMap`][crate::OrderMap].
278 /// It is part of the [`Entry`] enum.
279 pub struct VacantEntry<'a, K, V> {
280 pub(crate) inner: ix::VacantEntry<'a, K, V>,
281 }
282
283 impl<'a, K, V> VacantEntry<'a, K, V> {
284 /// Return the index where a key-value pair may be inserted.
285 pub fn index(&self) -> usize {
286 self.inner.index()
287 }
288
289 /// Gets a reference to the key that was used to find the entry.
290 pub fn key(&self) -> &K {
291 self.inner.key()
292 }
293
294 /// Takes ownership of the key, leaving the entry vacant.
295 pub fn into_key(self) -> K {
296 self.inner.into_key()
297 }
298
299 /// Inserts the entry's key and the given value into the map, and returns a mutable reference
300 /// to the value.
301 pub fn insert(self, value: V) -> &'a mut V {
302 self.inner.insert(value)
303 }
304
305 /// Inserts the entry's key and the given value into the map, and returns an `OccupiedEntry`.
306 ///
307 /// Computes in **O(1)** time (amortized average).
308 pub fn insert_entry(self, value: V) -> OccupiedEntry<'a, K, V> {
309 OccupiedEntry {
310 inner: self.inner.insert_entry(value),
311 }
312 }
313
314 /// Inserts the entry's key and the given value into the map at its ordered
315 /// position among sorted keys, and returns the new index and a mutable
316 /// reference to the value.
317 ///
318 /// If the existing keys are **not** already sorted, then the insertion
319 /// index is unspecified (like [`slice::binary_search`]), but the key-value
320 /// pair is inserted at that position regardless.
321 ///
322 /// Computes in **O(n)** time (average).
323 pub fn insert_sorted(self, value: V) -> (usize, &'a mut V)
324 where
325 K: Ord,
326 {
327 self.inner.insert_sorted(value)
328 }
329
330 /// Inserts the entry's key and the given value into the map at its ordered
331 /// position among keys sorted by `cmp`, and returns the new index and a
332 /// mutable reference to the value.
333 ///
334 /// If the existing keys are **not** already sorted, then the insertion
335 /// index is unspecified (like [`slice::binary_search`]), but the key-value
336 /// pair is inserted at that position regardless.
337 ///
338 /// Computes in **O(n)** time (average).
339 pub fn insert_sorted_by<F>(self, value: V, cmp: F) -> (usize, &'a mut V)
340 where
341 F: FnMut(&K, &V, &K, &V) -> Ordering,
342 {
343 self.inner.insert_sorted_by(value, cmp)
344 }
345
346 /// Inserts the entry's key and the given value into the map at its ordered
347 /// position using a sort-key extraction function, and returns the new index
348 /// and a mutable reference to the value.
349 ///
350 /// If the existing keys are **not** already sorted, then the insertion
351 /// index is unspecified (like [`slice::binary_search`]), but the key-value
352 /// pair is inserted at that position regardless.
353 ///
354 /// Computes in **O(n)** time (average).
355 pub fn insert_sorted_by_key<B, F>(self, value: V, sort_key: F) -> (usize, &'a mut V)
356 where
357 B: Ord,
358 F: FnMut(&K, &V) -> B,
359 {
360 self.inner.insert_sorted_by_key(value, sort_key)
361 }
362
363 /// Inserts the entry's key and the given value into the map at the given index,
364 /// shifting others to the right, and returns a mutable reference to the value.
365 ///
366 /// ***Panics*** if `index` is out of bounds.
367 ///
368 /// Computes in **O(n)** time (average).
369 #[track_caller]
370 pub fn shift_insert(self, index: usize, value: V) -> &'a mut V {
371 self.inner.shift_insert(index, value)
372 }
373
374 /// Replaces the key at the given index with this entry's key, returning the
375 /// old key and an `OccupiedEntry` for that index.
376 ///
377 /// ***Panics*** if `index` is out of bounds.
378 ///
379 /// Computes in **O(1)** time (average).
380 #[track_caller]
381 pub fn replace_index(self, index: usize) -> (K, OccupiedEntry<'a, K, V>) {
382 let (old_key, inner) = self.inner.replace_index(index);
383 (old_key, OccupiedEntry { inner })
384 }
385 }
386
387 impl<K: fmt::Debug, V> fmt::Debug for VacantEntry<'_, K, V> {
388 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
389 f.debug_tuple("VacantEntry").field(self.key()).finish()
390 }
391 }
392
393 /// A view into an occupied entry in an [`OrderMap`][crate::OrderMap] obtained by index.
394 ///
395 /// This `struct` is created from the [`get_index_entry`][crate::OrderMap::get_index_entry] method.
396 pub struct IndexedEntry<'a, K, V> {
397 pub(crate) inner: ix::IndexedEntry<'a, K, V>,
398 }
399
400 impl<'a, K, V> IndexedEntry<'a, K, V> {
401 pub(super) fn new(inner: ix::IndexedEntry<'a, K, V>) -> Self {
402 Self { inner }
403 }
404
405 /// Return the index of the key-value pair
406 #[inline]
407 pub fn index(&self) -> usize {
408 self.inner.index()
409 }
410
411 /// Gets a reference to the entry's key in the map.
412 pub fn key(&self) -> &K {
413 self.inner.key()
414 }
415
416 /// Gets a reference to the entry's value in the map.
417 pub fn get(&self) -> &V {
418 self.inner.get()
419 }
420
421 /// Gets a mutable reference to the entry's value in the map.
422 ///
423 /// If you need a reference which may outlive the destruction of the
424 /// `IndexedEntry` value, see [`into_mut`][Self::into_mut].
425 pub fn get_mut(&mut self) -> &mut V {
426 self.inner.get_mut()
427 }
428
429 /// Sets the value of the entry to `value`, and returns the entry's old value.
430 pub fn insert(&mut self, value: V) -> V {
431 self.inner.insert(value)
432 }
433
434 /// Converts into a mutable reference to the entry's value in the map,
435 /// with a lifetime bound to the map itself.
436 pub fn into_mut(self) -> &'a mut V {
437 self.inner.into_mut()
438 }
439
440 /// Remove and return the key, value pair stored in the map for this entry
441 ///
442 /// **NOTE:** This is equivalent to indexmap's
443 /// [`IndexedEntry::shift_remove_entry`][ix::IndexedEntry::shift_remove_entry], and
444 /// like [`Vec::remove`], the pair is removed by shifting all of the
445 /// elements that follow it, preserving their relative order.
446 /// **This perturbs the index of all of those elements!**
447 ///
448 /// Computes in **O(n)** time (average).
449 pub fn remove_entry(self) -> (K, V) {
450 self.inner.shift_remove_entry()
451 }
452
453 /// Remove the key, value pair stored in the map for this entry, and return the value.
454 ///
455 /// **NOTE:** This is equivalent to indexmap's
456 /// [`IndexedEntry::shift_remove`][ix::IndexedEntry::shift_remove], and
457 /// like [`Vec::remove`], the pair is removed by shifting all of the
458 /// elements that follow it, preserving their relative order.
459 /// **This perturbs the index of all of those elements!**
460 ///
461 /// Computes in **O(n)** time (average).
462 pub fn remove(self) -> V {
463 self.inner.shift_remove()
464 }
465
466 /// Remove and return the key, value pair stored in the map for this entry
467 ///
468 /// Like [`Vec::swap_remove`], the pair is removed by swapping it with
469 /// the last element of the map and popping it off.
470 /// **This perturbs the position of what used to be the last element!**
471 ///
472 /// Computes in **O(1)** time (average).
473 pub fn swap_remove_entry(self) -> (K, V) {
474 self.inner.swap_remove_entry()
475 }
476
477 /// Remove the key, value pair stored in the map for this entry, and return the value.
478 ///
479 /// Like [`Vec::swap_remove`], the pair is removed by swapping it with
480 /// the last element of the map and popping it off.
481 /// **This perturbs the position of what used to be the last element!**
482 ///
483 /// Computes in **O(1)** time (average).
484 pub fn swap_remove(self) -> V {
485 self.inner.swap_remove()
486 }
487
488 /// Moves the position of the entry to a new index
489 /// by shifting all other entries in-between.
490 ///
491 /// This is equivalent to [`OrderMap::move_index`][`crate::OrderMap::move_index`]
492 /// coming `from` the current [`.index()`][Self::index].
493 ///
494 /// * If `self.index() < to`, the other pairs will shift down while the targeted pair moves up.
495 /// * If `self.index() > to`, the other pairs will shift up while the targeted pair moves down.
496 ///
497 /// ***Panics*** if `to` is out of bounds.
498 ///
499 /// Computes in **O(n)** time (average).
500 #[track_caller]
501 pub fn move_index(self, to: usize) {
502 self.inner.move_index(to)
503 }
504
505 /// Swaps the position of entry with another.
506 ///
507 /// This is equivalent to [`OrderMap::swap_indices`][`crate::OrderMap::swap_indices`]
508 /// with the current [`.index()`][Self::index] as one of the two being swapped.
509 ///
510 /// ***Panics*** if the `other` index is out of bounds.
511 ///
512 /// Computes in **O(1)** time (average).
513 #[track_caller]
514 pub fn swap_indices(self, other: usize) {
515 self.inner.swap_indices(other)
516 }
517 }
518
519 impl<K: fmt::Debug, V: fmt::Debug> fmt::Debug for IndexedEntry<'_, K, V> {
520 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
521 f.debug_struct("IndexedEntry")
522 .field("index", &self.index())
523 .field("key", self.key())
524 .field("value", self.get())
525 .finish()
526 }
527 }
528
529 impl<'a, K, V> From<OccupiedEntry<'a, K, V>> for IndexedEntry<'a, K, V> {
530 fn from(entry: OccupiedEntry<'a, K, V>) -> Self {
531 Self {
532 inner: entry.inner.into(),
533 }
534 }
535 }