Debian Codegraph @

src/map/raw_entry_v1.rs

raw symbols SCIP
1 //! Opt-in access to the experimental raw entry API.
2 //!
3 //! This module is designed to mimic the raw entry API of [`HashMap`][std::collections::hash_map],
4 //! matching its unstable state as of Rust 1.75. See the tracking issue
5 //! [rust#56167](https://github.com/rust-lang/rust/issues/56167) for more details.
6 //!
7 //! The trait [`RawEntryApiV1`] and the `_v1` suffix on its methods are meant to insulate this for
8 //! the future, in case later breaking changes are needed. If the standard library stabilizes its
9 //! `hash_raw_entry` feature (or some replacement), matching *inherent* methods will be added to
10 //! `OrderMap` without such an opt-in trait.
11
12 use crate::{Equivalent, OrderMap};
13 use core::fmt;
14 use core::hash::{BuildHasher, Hash};
15 use indexmap::map::RawEntryApiV1 as _;
16 use indexmap::map::raw_entry_v1 as ix;
17
18 #[cfg(doc)]
19 use alloc::vec::Vec;
20
21 /// Opt-in access to the experimental raw entry API.
22 ///
23 /// See the [`raw_entry_v1`][self] module documentation for more information.
24 #[expect(private_bounds)]
25 pub trait RawEntryApiV1<K, V, S>: Sealed {
26 /// Creates a raw immutable entry builder for the [`OrderMap`].
27 ///
28 /// Raw entries provide the lowest level of control for searching and
29 /// manipulating a map. They must be manually initialized with a hash and
30 /// then manually searched.
31 ///
32 /// This is useful for
33 /// * Hash memoization
34 /// * Using a search key that doesn't work with the [`Equivalent`] trait
35 /// * Using custom comparison logic without newtype wrappers
36 ///
37 /// Unless you are in such a situation, higher-level and more foolproof APIs like
38 /// [`get`][OrderMap::get] should be preferred.
39 ///
40 /// Immutable raw entries have very limited use; you might instead want
41 /// [`raw_entry_mut_v1`][Self::raw_entry_mut_v1].
42 ///
43 /// # Examples
44 ///
45 /// ```
46 /// use core::hash::BuildHasher;
47 /// use ordermap::map::{OrderMap, RawEntryApiV1};
48 ///
49 /// let mut map = OrderMap::new();
50 /// map.extend([("a", 100), ("b", 200), ("c", 300)]);
51 ///
52 /// for k in ["a", "b", "c", "d", "e", "f"] {
53 /// let hash = map.hasher().hash_one(k);
54 /// let i = map.get_index_of(k);
55 /// let v = map.get(k);
56 /// let kv = map.get_key_value(k);
57 /// let ikv = map.get_full(k);
58 ///
59 /// println!("Key: {} and value: {:?}", k, v);
60 ///
61 /// assert_eq!(map.raw_entry_v1().from_key(k), kv);
62 /// assert_eq!(map.raw_entry_v1().from_hash(hash, |q| *q == k), kv);
63 /// assert_eq!(map.raw_entry_v1().from_key_hashed_nocheck(hash, k), kv);
64 /// assert_eq!(map.raw_entry_v1().from_hash_full(hash, |q| *q == k), ikv);
65 /// assert_eq!(map.raw_entry_v1().index_from_hash(hash, |q| *q == k), i);
66 /// }
67 /// ```
68 fn raw_entry_v1(&self) -> RawEntryBuilder<'_, K, V, S>;
69
70 /// Creates a raw entry builder for the [`OrderMap`].
71 ///
72 /// Raw entries provide the lowest level of control for searching and
73 /// manipulating a map. They must be manually initialized with a hash and
74 /// then manually searched. After this, insertions into a vacant entry
75 /// still require an owned key to be provided.
76 ///
77 /// Raw entries are useful for such exotic situations as:
78 ///
79 /// * Hash memoization
80 /// * Deferring the creation of an owned key until it is known to be required
81 /// * Using a search key that doesn't work with the [`Equivalent`] trait
82 /// * Using custom comparison logic without newtype wrappers
83 ///
84 /// Because raw entries provide much more low-level control, it's much easier
85 /// to put the `OrderMap` into an inconsistent state which, while memory-safe,
86 /// will cause the map to produce seemingly random results. Higher-level and more
87 /// foolproof APIs like [`entry`][OrderMap::entry] should be preferred when possible.
88 ///
89 /// Raw entries give mutable access to the keys. This must not be used
90 /// to modify how the key would compare or hash, as the map will not re-evaluate
91 /// where the key should go, meaning the keys may become "lost" if their
92 /// location does not reflect their state. For instance, if you change a key
93 /// so that the map now contains keys which compare equal, search may start
94 /// acting erratically, with two keys randomly masking each other. Implementations
95 /// are free to assume this doesn't happen (within the limits of memory-safety).
96 ///
97 /// # Examples
98 ///
99 /// ```
100 /// use core::hash::BuildHasher;
101 /// use ordermap::map::{OrderMap, RawEntryApiV1};
102 /// use ordermap::map::raw_entry_v1::RawEntryMut;
103 ///
104 /// let mut map = OrderMap::new();
105 /// map.extend([("a", 100), ("b", 200), ("c", 300)]);
106 ///
107 /// // Existing key (insert and update)
108 /// match map.raw_entry_mut_v1().from_key("a") {
109 /// RawEntryMut::Vacant(_) => unreachable!(),
110 /// RawEntryMut::Occupied(mut view) => {
111 /// assert_eq!(view.index(), 0);
112 /// assert_eq!(view.get(), &100);
113 /// let v = view.get_mut();
114 /// let new_v = (*v) * 10;
115 /// *v = new_v;
116 /// assert_eq!(view.insert(1111), 1000);
117 /// }
118 /// }
119 ///
120 /// assert_eq!(map["a"], 1111);
121 /// assert_eq!(map.len(), 3);
122 ///
123 /// // Existing key (take)
124 /// let hash = map.hasher().hash_one("c");
125 /// match map.raw_entry_mut_v1().from_key_hashed_nocheck(hash, "c") {
126 /// RawEntryMut::Vacant(_) => unreachable!(),
127 /// RawEntryMut::Occupied(view) => {
128 /// assert_eq!(view.index(), 2);
129 /// assert_eq!(view.remove_entry(), ("c", 300));
130 /// }
131 /// }
132 /// assert_eq!(map.raw_entry_v1().from_key("c"), None);
133 /// assert_eq!(map.len(), 2);
134 ///
135 /// // Nonexistent key (insert and update)
136 /// let key = "d";
137 /// let hash = map.hasher().hash_one(key);
138 /// match map.raw_entry_mut_v1().from_hash(hash, |q| *q == key) {
139 /// RawEntryMut::Occupied(_) => unreachable!(),
140 /// RawEntryMut::Vacant(view) => {
141 /// assert_eq!(view.index(), 2);
142 /// let (k, value) = view.insert("d", 4000);
143 /// assert_eq!((*k, *value), ("d", 4000));
144 /// *value = 40000;
145 /// }
146 /// }
147 /// assert_eq!(map["d"], 40000);
148 /// assert_eq!(map.len(), 3);
149 ///
150 /// match map.raw_entry_mut_v1().from_hash(hash, |q| *q == key) {
151 /// RawEntryMut::Vacant(_) => unreachable!(),
152 /// RawEntryMut::Occupied(view) => {
153 /// assert_eq!(view.index(), 2);
154 /// assert_eq!(view.swap_remove_entry(), ("d", 40000));
155 /// }
156 /// }
157 /// assert_eq!(map.get("d"), None);
158 /// assert_eq!(map.len(), 2);
159 /// ```
160 fn raw_entry_mut_v1(&mut self) -> RawEntryBuilderMut<'_, K, V, S>;
161 }
162
163 impl<K, V, S> RawEntryApiV1<K, V, S> for OrderMap<K, V, S> {
164 fn raw_entry_v1(&self) -> RawEntryBuilder<'_, K, V, S> {
165 RawEntryBuilder {
166 inner: self.inner.raw_entry_v1(),
167 }
168 }
169
170 fn raw_entry_mut_v1(&mut self) -> RawEntryBuilderMut<'_, K, V, S> {
171 RawEntryBuilderMut {
172 inner: self.inner.raw_entry_mut_v1(),
173 }
174 }
175 }
176
177 /// A builder for computing where in an [`OrderMap`] a key-value pair would be stored.
178 ///
179 /// This `struct` is created by the [`OrderMap::raw_entry_v1`] method, provided by the
180 /// [`RawEntryApiV1`] trait. See its documentation for more.
181 pub struct RawEntryBuilder<'a, K, V, S> {
182 inner: ix::RawEntryBuilder<'a, K, V, S>,
183 }
184
185 impl<K, V, S> fmt::Debug for RawEntryBuilder<'_, K, V, S> {
186 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
187 f.debug_struct("RawEntryBuilder").finish_non_exhaustive()
188 }
189 }
190
191 impl<'a, K, V, S> RawEntryBuilder<'a, K, V, S> {
192 /// Access an entry by key.
193 pub fn from_key<Q>(self, key: &Q) -> Option<(&'a K, &'a V)>
194 where
195 S: BuildHasher,
196 Q: ?Sized + Hash + Equivalent<K>,
197 {
198 self.inner.from_key(key)
199 }
200
201 /// Access an entry by a key and its hash.
202 pub fn from_key_hashed_nocheck<Q>(self, hash: u64, key: &Q) -> Option<(&'a K, &'a V)>
203 where
204 Q: ?Sized + Equivalent<K>,
205 {
206 self.inner.from_key_hashed_nocheck(hash, key)
207 }
208
209 /// Access an entry by hash.
210 pub fn from_hash<F>(self, hash: u64, is_match: F) -> Option<(&'a K, &'a V)>
211 where
212 F: FnMut(&K) -> bool,
213 {
214 self.inner.from_hash(hash, is_match)
215 }
216
217 /// Access an entry by hash, including its index.
218 pub fn from_hash_full<F>(self, hash: u64, is_match: F) -> Option<(usize, &'a K, &'a V)>
219 where
220 F: FnMut(&K) -> bool,
221 {
222 self.inner.from_hash_full(hash, is_match)
223 }
224
225 /// Access the index of an entry by hash.
226 pub fn index_from_hash<F>(self, hash: u64, is_match: F) -> Option<usize>
227 where
228 F: FnMut(&K) -> bool,
229 {
230 self.inner.index_from_hash(hash, is_match)
231 }
232 }
233
234 /// A builder for computing where in an [`OrderMap`] a key-value pair would be stored.
235 ///
236 /// This `struct` is created by the [`OrderMap::raw_entry_mut_v1`] method, provided by the
237 /// [`RawEntryApiV1`] trait. See its documentation for more.
238 pub struct RawEntryBuilderMut<'a, K, V, S> {
239 inner: ix::RawEntryBuilderMut<'a, K, V, S>,
240 }
241
242 impl<K, V, S> fmt::Debug for RawEntryBuilderMut<'_, K, V, S> {
243 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
244 f.debug_struct("RawEntryBuilderMut").finish_non_exhaustive()
245 }
246 }
247
248 impl<'a, K, V, S> RawEntryBuilderMut<'a, K, V, S> {
249 /// Access an entry by key.
250 pub fn from_key<Q>(self, key: &Q) -> RawEntryMut<'a, K, V, S>
251 where
252 S: BuildHasher,
253 Q: ?Sized + Hash + Equivalent<K>,
254 {
255 RawEntryMut::new(self.inner.from_key(key))
256 }
257
258 /// Access an entry by a key and its hash.
259 pub fn from_key_hashed_nocheck<Q>(self, hash: u64, key: &Q) -> RawEntryMut<'a, K, V, S>
260 where
261 Q: ?Sized + Equivalent<K>,
262 {
263 RawEntryMut::new(self.inner.from_key_hashed_nocheck(hash, key))
264 }
265
266 /// Access an entry by hash.
267 pub fn from_hash<F>(self, hash: u64, is_match: F) -> RawEntryMut<'a, K, V, S>
268 where
269 F: FnMut(&K) -> bool,
270 {
271 RawEntryMut::new(self.inner.from_hash(hash, is_match))
272 }
273 }
274
275 /// Raw entry for an existing key-value pair or a vacant location to
276 /// insert one.
277 pub enum RawEntryMut<'a, K, V, S> {
278 /// Existing slot with equivalent key.
279 Occupied(RawOccupiedEntryMut<'a, K, V, S>),
280 /// Vacant slot (no equivalent key in the map).
281 Vacant(RawVacantEntryMut<'a, K, V, S>),
282 }
283
284 impl<K: fmt::Debug, V: fmt::Debug, S> fmt::Debug for RawEntryMut<'_, K, V, S> {
285 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
286 let mut tuple = f.debug_tuple("RawEntryMut");
287 match self {
288 Self::Vacant(v) => tuple.field(v),
289 Self::Occupied(o) => tuple.field(o),
290 };
291 tuple.finish()
292 }
293 }
294
295 impl<'a, K, V, S> RawEntryMut<'a, K, V, S> {
296 fn new(entry: ix::RawEntryMut<'a, K, V, S>) -> Self {
297 match entry {
298 ix::RawEntryMut::Occupied(inner) => Self::Occupied(RawOccupiedEntryMut { inner }),
299 ix::RawEntryMut::Vacant(inner) => Self::Vacant(RawVacantEntryMut { inner }),
300 }
301 }
302
303 /// Return the index where the key-value pair exists or may be inserted.
304 #[inline]
305 pub fn index(&self) -> usize {
306 match self {
307 Self::Occupied(entry) => entry.index(),
308 Self::Vacant(entry) => entry.index(),
309 }
310 }
311
312 /// Inserts the given default key and value in the entry if it is vacant and returns mutable
313 /// references to them. Otherwise mutable references to an already existent pair are returned.
314 pub fn or_insert(self, default_key: K, default_value: V) -> (&'a mut K, &'a mut V)
315 where
316 K: Hash,
317 S: BuildHasher,
318 {
319 match self {
320 Self::Occupied(entry) => entry.into_key_value_mut(),
321 Self::Vacant(entry) => entry.insert(default_key, default_value),
322 }
323 }
324
325 /// Inserts the result of the `call` function in the entry if it is vacant and returns mutable
326 /// references to them. Otherwise mutable references to an already existent pair are returned.
327 pub fn or_insert_with<F>(self, call: F) -> (&'a mut K, &'a mut V)
328 where
329 F: FnOnce() -> (K, V),
330 K: Hash,
331 S: BuildHasher,
332 {
333 match self {
334 Self::Occupied(entry) => entry.into_key_value_mut(),
335 Self::Vacant(entry) => {
336 let (key, value) = call();
337 entry.insert(key, value)
338 }
339 }
340 }
341
342 /// Modifies the entry if it is occupied.
343 pub fn and_modify<F>(mut self, f: F) -> Self
344 where
345 F: FnOnce(&mut K, &mut V),
346 {
347 if let Self::Occupied(entry) = &mut self {
348 let (k, v) = entry.get_key_value_mut();
349 f(k, v);
350 }
351 self
352 }
353 }
354
355 /// A raw view into an occupied entry in an [`OrderMap`].
356 /// It is part of the [`RawEntryMut`] enum.
357 pub struct RawOccupiedEntryMut<'a, K, V, S> {
358 inner: ix::RawOccupiedEntryMut<'a, K, V, S>,
359 }
360
361 impl<K: fmt::Debug, V: fmt::Debug, S> fmt::Debug for RawOccupiedEntryMut<'_, K, V, S> {
362 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
363 f.debug_struct("RawOccupiedEntryMut")
364 .field("key", self.key())
365 .field("value", self.get())
366 .finish_non_exhaustive()
367 }
368 }
369
370 impl<'a, K, V, S> RawOccupiedEntryMut<'a, K, V, S> {
371 /// Return the index of the key-value pair
372 #[inline]
373 pub fn index(&self) -> usize {
374 self.inner.index()
375 }
376
377 /// Gets a reference to the entry's key in the map.
378 ///
379 /// Note that this is not the key that was used to find the entry. There may be an observable
380 /// difference if the key type has any distinguishing features outside of `Hash` and `Eq`, like
381 /// extra fields or the memory address of an allocation.
382 pub fn key(&self) -> &K {
383 self.inner.key()
384 }
385
386 /// Gets a mutable reference to the entry's key in the map.
387 ///
388 /// Note that this is not the key that was used to find the entry. There may be an observable
389 /// difference if the key type has any distinguishing features outside of `Hash` and `Eq`, like
390 /// extra fields or the memory address of an allocation.
391 pub fn key_mut(&mut self) -> &mut K {
392 self.inner.key_mut()
393 }
394
395 /// Converts into a mutable reference to the entry's key in the map,
396 /// with a lifetime bound to the map itself.
397 ///
398 /// Note that this is not the key that was used to find the entry. There may be an observable
399 /// difference if the key type has any distinguishing features outside of `Hash` and `Eq`, like
400 /// extra fields or the memory address of an allocation.
401 pub fn into_key(self) -> &'a mut K {
402 self.inner.into_key()
403 }
404
405 /// Gets a reference to the entry's value in the map.
406 pub fn get(&self) -> &V {
407 self.inner.get()
408 }
409
410 /// Gets a mutable reference to the entry's value in the map.
411 ///
412 /// If you need a reference which may outlive the destruction of the
413 /// [`RawEntryMut`] value, see [`into_mut`][Self::into_mut].
414 pub fn get_mut(&mut self) -> &mut V {
415 self.inner.get_mut()
416 }
417
418 /// Converts into a mutable reference to the entry's value in the map,
419 /// with a lifetime bound to the map itself.
420 pub fn into_mut(self) -> &'a mut V {
421 self.inner.into_mut()
422 }
423
424 /// Gets a reference to the entry's key and value in the map.
425 pub fn get_key_value(&self) -> (&K, &V) {
426 self.inner.get_key_value()
427 }
428
429 /// Gets a reference to the entry's key and value in the map.
430 pub fn get_key_value_mut(&mut self) -> (&mut K, &mut V) {
431 self.inner.get_key_value_mut()
432 }
433
434 /// Converts into a mutable reference to the entry's key and value in the map,
435 /// with a lifetime bound to the map itself.
436 pub fn into_key_value_mut(self) -> (&'a mut K, &'a mut V) {
437 self.inner.into_key_value_mut()
438 }
439
440 /// Sets the value of the entry, and returns the entry's old value.
441 pub fn insert(&mut self, value: V) -> V {
442 self.inner.insert(value)
443 }
444
445 /// Sets the key of the entry, and returns the entry's old key.
446 pub fn insert_key(&mut self, key: K) -> K {
447 self.inner.insert_key(key)
448 }
449
450 /// Remove the key, value pair stored in the map for this entry, and return the value.
451 ///
452 /// **NOTE:** This is equivalent to indexmap's
453 /// [`RawOccupiedEntryMut::shift_remove`][ix::RawOccupiedEntryMut::shift_remove], and
454 /// like [`Vec::remove`], the pair is removed by shifting all of the
455 /// elements that follow it, preserving their relative order.
456 /// **This perturbs the index of all of those elements!**
457 ///
458 /// Computes in **O(n)** time (average).
459 pub fn remove(self) -> V {
460 self.inner.shift_remove()
461 }
462
463 /// Remove the key, value pair stored in the map for this entry, and return the value.
464 ///
465 /// Like [`Vec::swap_remove`], the pair is removed by swapping it with
466 /// the last element of the map and popping it off.
467 /// **This perturbs the position of what used to be the last element!**
468 ///
469 /// Computes in **O(1)** time (average).
470 pub fn swap_remove(self) -> V {
471 self.inner.swap_remove()
472 }
473
474 /// Remove and return the key, value pair stored in the map for this entry
475 ///
476 /// **NOTE:** This is equivalent to indexmap's
477 /// [`RawOccupiedEntryMut::shift_remove_entry`][ix::RawOccupiedEntryMut::shift_remove_entry], and
478 /// like [`Vec::remove`], the pair is removed by shifting all of the
479 /// elements that follow it, preserving their relative order.
480 /// **This perturbs the index of all of those elements!**
481 ///
482 /// Computes in **O(n)** time (average).
483 pub fn remove_entry(self) -> (K, V) {
484 self.inner.shift_remove_entry()
485 }
486
487 /// Remove and return the key, value pair stored in the map for this entry
488 ///
489 /// Like [`Vec::swap_remove`], the pair is removed by swapping it with
490 /// the last element of the map and popping it off.
491 /// **This perturbs the position of what used to be the last element!**
492 ///
493 /// Computes in **O(1)** time (average).
494 pub fn swap_remove_entry(self) -> (K, V) {
495 self.inner.swap_remove_entry()
496 }
497
498 /// Moves the position of the entry to a new index
499 /// by shifting all other entries in-between.
500 ///
501 /// This is equivalent to [`OrderMap::move_index`]
502 /// coming `from` the current [`.index()`][Self::index].
503 ///
504 /// * If `self.index() < to`, the other pairs will shift down while the targeted pair moves up.
505 /// * If `self.index() > to`, the other pairs will shift up while the targeted pair moves down.
506 ///
507 /// ***Panics*** if `to` is out of bounds.
508 ///
509 /// Computes in **O(n)** time (average).
510 #[track_caller]
511 pub fn move_index(self, to: usize) {
512 self.inner.move_index(to);
513 }
514
515 /// Swaps the position of entry with another.
516 ///
517 /// This is equivalent to [`OrderMap::swap_indices`]
518 /// with the current [`.index()`][Self::index] as one of the two being swapped.
519 ///
520 /// ***Panics*** if the `other` index is out of bounds.
521 ///
522 /// Computes in **O(1)** time (average).
523 #[track_caller]
524 pub fn swap_indices(self, other: usize) {
525 self.inner.swap_indices(other);
526 }
527 }
528
529 /// A view into a vacant raw entry in an [`OrderMap`].
530 /// It is part of the [`RawEntryMut`] enum.
531 pub struct RawVacantEntryMut<'a, K, V, S> {
532 inner: ix::RawVacantEntryMut<'a, K, V, S>,
533 }
534
535 impl<K, V, S> fmt::Debug for RawVacantEntryMut<'_, K, V, S> {
536 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
537 f.debug_struct("RawVacantEntryMut").finish_non_exhaustive()
538 }
539 }
540
541 impl<'a, K, V, S> RawVacantEntryMut<'a, K, V, S> {
542 /// Return the index where a key-value pair may be inserted.
543 pub fn index(&self) -> usize {
544 self.inner.index()
545 }
546
547 /// Inserts the given key and value into the map,
548 /// and returns mutable references to them.
549 pub fn insert(self, key: K, value: V) -> (&'a mut K, &'a mut V)
550 where
551 K: Hash,
552 S: BuildHasher,
553 {
554 self.inner.insert(key, value)
555 }
556
557 /// Inserts the given key and value into the map with the provided hash,
558 /// and returns mutable references to them.
559 pub fn insert_hashed_nocheck(self, hash: u64, key: K, value: V) -> (&'a mut K, &'a mut V) {
560 self.inner.insert_hashed_nocheck(hash, key, value)
561 }
562
563 /// Inserts the given key and value into the map at the given index,
564 /// shifting others to the right, and returns mutable references to them.
565 ///
566 /// ***Panics*** if `index` is out of bounds.
567 ///
568 /// Computes in **O(n)** time (average).
569 #[track_caller]
570 pub fn shift_insert(self, index: usize, key: K, value: V) -> (&'a mut K, &'a mut V)
571 where
572 K: Hash,
573 S: BuildHasher,
574 {
575 self.inner.shift_insert(index, key, value)
576 }
577
578 /// Inserts the given key and value into the map with the provided hash
579 /// at the given index, and returns mutable references to them.
580 ///
581 /// ***Panics*** if `index` is out of bounds.
582 ///
583 /// Computes in **O(n)** time (average).
584 #[track_caller]
585 pub fn shift_insert_hashed_nocheck(
586 self,
587 index: usize,
588 hash: u64,
589 key: K,
590 value: V,
591 ) -> (&'a mut K, &'a mut V) {
592 self.inner
593 .shift_insert_hashed_nocheck(index, hash, key, value)
594 }
595 }
596
597 trait Sealed {}
598
599 impl<K, V, S> Sealed for OrderMap<K, V, S> {}