Debian Codegraph @

debian/rust-vendor/hashbrown/src/rustc_entry.rs

raw
1 use self::RustcEntry::*;
2 use crate::alloc::{Allocator, Global};
3 use crate::map::{Drain, HashMap, IntoIter, Iter, IterMut, make_hash, make_hasher};
4 use crate::raw::{Bucket, RawTable};
5 use core::fmt::{self, Debug};
6 use core::hash::{BuildHasher, Hash};
7 use core::mem;
8
9 impl<K, V, S, A> HashMap<K, V, S, A>
10 where
11 K: Eq + Hash,
12 S: BuildHasher,
13 A: Allocator,
14 {
15 /// Gets the given key's corresponding entry in the map for in-place manipulation.
16 ///
17 /// # Examples
18 ///
19 /// ```
20 /// use hashbrown::HashMap;
21 ///
22 /// let mut letters = HashMap::new();
23 ///
24 /// for ch in "a short treatise on fungi".chars() {
25 /// let counter = letters.rustc_entry(ch).or_insert(0);
26 /// *counter += 1;
27 /// }
28 ///
29 /// assert_eq!(letters[&'s'], 2);
30 /// assert_eq!(letters[&'t'], 3);
31 /// assert_eq!(letters[&'u'], 1);
32 /// assert_eq!(letters.get(&'y'), None);
33 /// ```
34 #[cfg_attr(feature = "inline-more", inline)]
35 pub fn rustc_entry(&mut self, key: K) -> RustcEntry<'_, K, V, A> {
36 let hash = make_hash(&self.hash_builder, &key);
37 if let Some(elem) = self.table.find(hash, |q| q.0.eq(&key)) {
38 RustcEntry::Occupied(RustcOccupiedEntry {
39 elem,
40 table: &mut self.table,
41 })
42 } else {
43 // Ideally we would put this in VacantEntry::insert, but Entry is not
44 // generic over the BuildHasher and adding a generic parameter would be
45 // a breaking change.
46 self.reserve(1);
47
48 RustcEntry::Vacant(RustcVacantEntry {
49 hash,
50 key,
51 table: &mut self.table,
52 })
53 }
54 }
55
56 /// Tries to insert a key-value pair into the map, and returns
57 /// a mutable reference to the value in the entry.
58 ///
59 /// # Errors
60 ///
61 /// If the map already had this key present, nothing is updated, and an error
62 /// containing the occupied entry, the key, and the value is returned.
63 ///
64 /// # Examples
65 ///
66 /// Basic usage:
67 ///
68 /// ```
69 /// use hashbrown::HashMap;
70 /// use hashbrown::hash_map::RustcOccupiedError;
71 ///
72 /// let mut map = HashMap::new();
73 /// assert_eq!(map.rustc_try_insert(37, "a").ok().unwrap(), &"a");
74 ///
75 /// match map.rustc_try_insert(37, "b") {
76 /// Err(RustcOccupiedError { entry, key, value, .. }) => {
77 /// assert_eq!(entry.key(), &37);
78 /// assert_eq!(entry.get(), &"a");
79 /// assert_eq!(key, 37);
80 /// assert_eq!(value, "b");
81 /// }
82 /// _ => panic!()
83 /// }
84 /// ```
85 #[cfg_attr(feature = "inline-more", inline)]
86 pub fn rustc_try_insert(
87 &mut self,
88 key: K,
89 value: V,
90 ) -> Result<&mut V, RustcOccupiedError<'_, K, V, A>> {
91 let hash = make_hash(&self.hash_builder, &key);
92 if let Some(elem) = self.table.find(hash, |q| q.0.eq(&key)) {
93 let entry = RustcOccupiedEntry {
94 elem,
95 table: &mut self.table,
96 };
97 Err(RustcOccupiedError { entry, key, value })
98 } else {
99 let hasher = make_hasher(&self.hash_builder);
100 let entry = self.table.insert_entry(hash, (key, value), hasher);
101 Ok(&mut entry.1)
102 }
103 }
104 }
105
106 /// The error returned by [`rustc_try_insert`](HashMap::rustc_try_insert) when the key already exists.
107 ///
108 /// Note: There are no impls for this type, because we expect the standard library will
109 /// immediately reconstruct these errors into its own `OccupiedError`.
110 #[non_exhaustive]
111 pub struct RustcOccupiedError<'a, K, V, A = Global>
112 where
113 A: Allocator,
114 {
115 /// The entry in the map that was already occupied.
116 pub entry: RustcOccupiedEntry<'a, K, V, A>,
117 /// The key which was not inserted, because the entry was already occupied.
118 pub key: K,
119 /// The value which was not inserted, because the entry was already occupied.
120 pub value: V,
121 }
122
123 /// A view into a single entry in a map, which may either be vacant or occupied.
124 ///
125 /// This `enum` is constructed from the [`rustc_entry`] method on [`HashMap`].
126 ///
127 /// [`rustc_entry`]: HashMap::rustc_entry
128 pub enum RustcEntry<'a, K, V, A = Global>
129 where
130 A: Allocator,
131 {
132 /// An occupied entry.
133 Occupied(RustcOccupiedEntry<'a, K, V, A>),
134
135 /// A vacant entry.
136 Vacant(RustcVacantEntry<'a, K, V, A>),
137 }
138
139 impl<K: Debug, V: Debug, A: Allocator> Debug for RustcEntry<'_, K, V, A> {
140 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
141 match *self {
142 Vacant(ref v) => f.debug_tuple("Entry").field(v).finish(),
143 Occupied(ref o) => f.debug_tuple("Entry").field(o).finish(),
144 }
145 }
146 }
147
148 /// A view into an occupied entry in a `HashMap`.
149 /// It is part of the [`RustcEntry`] enum.
150 pub struct RustcOccupiedEntry<'a, K, V, A = Global>
151 where
152 A: Allocator,
153 {
154 elem: Bucket<(K, V)>,
155 table: &'a mut RawTable<(K, V), A>,
156 }
157
158 unsafe impl<K, V, A> Send for RustcOccupiedEntry<'_, K, V, A>
159 where
160 K: Send,
161 V: Send,
162 A: Allocator + Send,
163 {
164 }
165 unsafe impl<K, V, A> Sync for RustcOccupiedEntry<'_, K, V, A>
166 where
167 K: Sync,
168 V: Sync,
169 A: Allocator + Sync,
170 {
171 }
172
173 impl<K: Debug, V: Debug, A: Allocator> Debug for RustcOccupiedEntry<'_, K, V, A> {
174 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
175 f.debug_struct("OccupiedEntry")
176 .field("key", self.key())
177 .field("value", self.get())
178 .finish()
179 }
180 }
181
182 /// A view into a vacant entry in a `HashMap`.
183 /// It is part of the [`RustcEntry`] enum.
184 pub struct RustcVacantEntry<'a, K, V, A = Global>
185 where
186 A: Allocator,
187 {
188 hash: u64,
189 key: K,
190 table: &'a mut RawTable<(K, V), A>,
191 }
192
193 impl<K: Debug, V, A: Allocator> Debug for RustcVacantEntry<'_, K, V, A> {
194 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
195 f.debug_tuple("VacantEntry").field(self.key()).finish()
196 }
197 }
198
199 impl<'a, K, V, A: Allocator> RustcEntry<'a, K, V, A> {
200 /// Sets the value of the entry, and returns a RustcOccupiedEntry.
201 ///
202 /// # Examples
203 ///
204 /// ```
205 /// use hashbrown::HashMap;
206 ///
207 /// let mut map: HashMap<&str, u32> = HashMap::new();
208 /// let entry = map.rustc_entry("horseyland").insert(37);
209 ///
210 /// assert_eq!(entry.key(), &"horseyland");
211 /// ```
212 pub fn insert(self, value: V) -> RustcOccupiedEntry<'a, K, V, A> {
213 match self {
214 Vacant(entry) => entry.insert_entry(value),
215 Occupied(mut entry) => {
216 entry.insert(value);
217 entry
218 }
219 }
220 }
221
222 /// Ensures a value is in the entry by inserting the default if empty, and returns
223 /// a mutable reference to the value in the entry.
224 ///
225 /// # Examples
226 ///
227 /// ```
228 /// use hashbrown::HashMap;
229 ///
230 /// let mut map: HashMap<&str, u32> = HashMap::new();
231 ///
232 /// map.rustc_entry("poneyland").or_insert(3);
233 /// assert_eq!(map["poneyland"], 3);
234 ///
235 /// *map.rustc_entry("poneyland").or_insert(10) *= 2;
236 /// assert_eq!(map["poneyland"], 6);
237 /// ```
238 #[cfg_attr(feature = "inline-more", inline)]
239 pub fn or_insert(self, default: V) -> &'a mut V
240 where
241 K: Hash,
242 {
243 match self {
244 Occupied(entry) => entry.into_mut(),
245 Vacant(entry) => entry.insert(default),
246 }
247 }
248
249 /// Ensures a value is in the entry by inserting the result of the default function if empty,
250 /// and returns a mutable reference to the value in the entry.
251 ///
252 /// # Examples
253 ///
254 /// ```
255 /// use hashbrown::HashMap;
256 ///
257 /// let mut map: HashMap<&str, String> = HashMap::new();
258 /// let s = "hoho".to_string();
259 ///
260 /// map.rustc_entry("poneyland").or_insert_with(|| s);
261 ///
262 /// assert_eq!(map["poneyland"], "hoho".to_string());
263 /// ```
264 #[cfg_attr(feature = "inline-more", inline)]
265 pub fn or_insert_with<F: FnOnce() -> V>(self, default: F) -> &'a mut V
266 where
267 K: Hash,
268 {
269 match self {
270 Occupied(entry) => entry.into_mut(),
271 Vacant(entry) => entry.insert(default()),
272 }
273 }
274
275 /// Returns a reference to this entry's key.
276 ///
277 /// # Examples
278 ///
279 /// ```
280 /// use hashbrown::HashMap;
281 ///
282 /// let mut map: HashMap<&str, u32> = HashMap::new();
283 /// assert_eq!(map.rustc_entry("poneyland").key(), &"poneyland");
284 /// ```
285 #[cfg_attr(feature = "inline-more", inline)]
286 pub fn key(&self) -> &K {
287 match *self {
288 Occupied(ref entry) => entry.key(),
289 Vacant(ref entry) => entry.key(),
290 }
291 }
292
293 /// Provides in-place mutable access to an occupied entry before any
294 /// potential inserts into the map.
295 ///
296 /// # Examples
297 ///
298 /// ```
299 /// use hashbrown::HashMap;
300 ///
301 /// let mut map: HashMap<&str, u32> = HashMap::new();
302 ///
303 /// map.rustc_entry("poneyland")
304 /// .and_modify(|e| { *e += 1 })
305 /// .or_insert(42);
306 /// assert_eq!(map["poneyland"], 42);
307 ///
308 /// map.rustc_entry("poneyland")
309 /// .and_modify(|e| { *e += 1 })
310 /// .or_insert(42);
311 /// assert_eq!(map["poneyland"], 43);
312 /// ```
313 #[cfg_attr(feature = "inline-more", inline)]
314 pub fn and_modify<F>(self, f: F) -> Self
315 where
316 F: FnOnce(&mut V),
317 {
318 match self {
319 Occupied(mut entry) => {
320 f(entry.get_mut());
321 Occupied(entry)
322 }
323 Vacant(entry) => Vacant(entry),
324 }
325 }
326 }
327
328 impl<'a, K, V: Default, A: Allocator> RustcEntry<'a, K, V, A> {
329 /// Ensures a value is in the entry by inserting the default value if empty,
330 /// and returns a mutable reference to the value in the entry.
331 ///
332 /// # Examples
333 ///
334 /// ```
335 /// # fn main() {
336 /// use hashbrown::HashMap;
337 ///
338 /// let mut map: HashMap<&str, Option<u32>> = HashMap::new();
339 /// map.rustc_entry("poneyland").or_default();
340 ///
341 /// assert_eq!(map["poneyland"], None);
342 /// # }
343 /// ```
344 #[cfg_attr(feature = "inline-more", inline)]
345 pub fn or_default(self) -> &'a mut V
346 where
347 K: Hash,
348 {
349 match self {
350 Occupied(entry) => entry.into_mut(),
351 Vacant(entry) => entry.insert(Default::default()),
352 }
353 }
354 }
355
356 impl<'a, K, V, A: Allocator> RustcOccupiedEntry<'a, K, V, A> {
357 /// Gets a reference to the key in the entry.
358 ///
359 /// # Examples
360 ///
361 /// ```
362 /// use hashbrown::HashMap;
363 ///
364 /// let mut map: HashMap<&str, u32> = HashMap::new();
365 /// map.rustc_entry("poneyland").or_insert(12);
366 /// assert_eq!(map.rustc_entry("poneyland").key(), &"poneyland");
367 /// ```
368 #[cfg_attr(feature = "inline-more", inline)]
369 pub fn key(&self) -> &K {
370 unsafe { &self.elem.as_ref().0 }
371 }
372
373 /// Take the ownership of the key and value from the map.
374 ///
375 /// # Examples
376 ///
377 /// ```
378 /// use hashbrown::HashMap;
379 /// use hashbrown::hash_map::RustcEntry;
380 ///
381 /// let mut map: HashMap<&str, u32> = HashMap::new();
382 /// map.rustc_entry("poneyland").or_insert(12);
383 ///
384 /// if let RustcEntry::Occupied(o) = map.rustc_entry("poneyland") {
385 /// // We delete the entry from the map.
386 /// o.remove_entry();
387 /// }
388 ///
389 /// assert_eq!(map.contains_key("poneyland"), false);
390 /// ```
391 #[cfg_attr(feature = "inline-more", inline)]
392 pub fn remove_entry(self) -> (K, V) {
393 unsafe { self.table.remove(self.elem).0 }
394 }
395
396 /// Gets a reference to the value in the entry.
397 ///
398 /// # Examples
399 ///
400 /// ```
401 /// use hashbrown::HashMap;
402 /// use hashbrown::hash_map::RustcEntry;
403 ///
404 /// let mut map: HashMap<&str, u32> = HashMap::new();
405 /// map.rustc_entry("poneyland").or_insert(12);
406 ///
407 /// if let RustcEntry::Occupied(o) = map.rustc_entry("poneyland") {
408 /// assert_eq!(o.get(), &12);
409 /// }
410 /// ```
411 #[cfg_attr(feature = "inline-more", inline)]
412 pub fn get(&self) -> &V {
413 unsafe { &self.elem.as_ref().1 }
414 }
415
416 /// Gets a mutable reference to the value in the entry.
417 ///
418 /// If you need a reference to the `RustcOccupiedEntry` which may outlive the
419 /// destruction of the `RustcEntry` value, see [`into_mut`].
420 ///
421 /// [`into_mut`]: #method.into_mut
422 ///
423 /// # Examples
424 ///
425 /// ```
426 /// use hashbrown::HashMap;
427 /// use hashbrown::hash_map::RustcEntry;
428 ///
429 /// let mut map: HashMap<&str, u32> = HashMap::new();
430 /// map.rustc_entry("poneyland").or_insert(12);
431 ///
432 /// assert_eq!(map["poneyland"], 12);
433 /// if let RustcEntry::Occupied(mut o) = map.rustc_entry("poneyland") {
434 /// *o.get_mut() += 10;
435 /// assert_eq!(*o.get(), 22);
436 ///
437 /// // We can use the same RustcEntry multiple times.
438 /// *o.get_mut() += 2;
439 /// }
440 ///
441 /// assert_eq!(map["poneyland"], 24);
442 /// ```
443 #[cfg_attr(feature = "inline-more", inline)]
444 pub fn get_mut(&mut self) -> &mut V {
445 unsafe { &mut self.elem.as_mut().1 }
446 }
447
448 /// Converts the RustcOccupiedEntry into a mutable reference to the value in the entry
449 /// with a lifetime bound to the map itself.
450 ///
451 /// If you need multiple references to the `RustcOccupiedEntry`, see [`get_mut`].
452 ///
453 /// [`get_mut`]: #method.get_mut
454 ///
455 /// # Examples
456 ///
457 /// ```
458 /// use hashbrown::HashMap;
459 /// use hashbrown::hash_map::RustcEntry;
460 ///
461 /// let mut map: HashMap<&str, u32> = HashMap::new();
462 /// map.rustc_entry("poneyland").or_insert(12);
463 ///
464 /// assert_eq!(map["poneyland"], 12);
465 /// if let RustcEntry::Occupied(o) = map.rustc_entry("poneyland") {
466 /// *o.into_mut() += 10;
467 /// }
468 ///
469 /// assert_eq!(map["poneyland"], 22);
470 /// ```
471 #[cfg_attr(feature = "inline-more", inline)]
472 pub fn into_mut(self) -> &'a mut V {
473 unsafe { &mut self.elem.as_mut().1 }
474 }
475
476 /// Sets the value of the entry, and returns the entry's old value.
477 ///
478 /// # Examples
479 ///
480 /// ```
481 /// use hashbrown::HashMap;
482 /// use hashbrown::hash_map::RustcEntry;
483 ///
484 /// let mut map: HashMap<&str, u32> = HashMap::new();
485 /// map.rustc_entry("poneyland").or_insert(12);
486 ///
487 /// if let RustcEntry::Occupied(mut o) = map.rustc_entry("poneyland") {
488 /// assert_eq!(o.insert(15), 12);
489 /// }
490 ///
491 /// assert_eq!(map["poneyland"], 15);
492 /// ```
493 #[cfg_attr(feature = "inline-more", inline)]
494 pub fn insert(&mut self, value: V) -> V {
495 mem::replace(self.get_mut(), value)
496 }
497
498 /// Takes the value out of the entry, and returns it.
499 ///
500 /// # Examples
501 ///
502 /// ```
503 /// use hashbrown::HashMap;
504 /// use hashbrown::hash_map::RustcEntry;
505 ///
506 /// let mut map: HashMap<&str, u32> = HashMap::new();
507 /// map.rustc_entry("poneyland").or_insert(12);
508 ///
509 /// if let RustcEntry::Occupied(o) = map.rustc_entry("poneyland") {
510 /// assert_eq!(o.remove(), 12);
511 /// }
512 ///
513 /// assert_eq!(map.contains_key("poneyland"), false);
514 /// ```
515 #[cfg_attr(feature = "inline-more", inline)]
516 pub fn remove(self) -> V {
517 self.remove_entry().1
518 }
519 }
520
521 impl<'a, K, V, A: Allocator> RustcVacantEntry<'a, K, V, A> {
522 /// Gets a reference to the key that would be used when inserting a value
523 /// through the `RustcVacantEntry`.
524 ///
525 /// # Examples
526 ///
527 /// ```
528 /// use hashbrown::HashMap;
529 ///
530 /// let mut map: HashMap<&str, u32> = HashMap::new();
531 /// assert_eq!(map.rustc_entry("poneyland").key(), &"poneyland");
532 /// ```
533 #[cfg_attr(feature = "inline-more", inline)]
534 pub fn key(&self) -> &K {
535 &self.key
536 }
537
538 /// Take ownership of the key.
539 ///
540 /// # Examples
541 ///
542 /// ```
543 /// use hashbrown::HashMap;
544 /// use hashbrown::hash_map::RustcEntry;
545 ///
546 /// let mut map: HashMap<&str, u32> = HashMap::new();
547 ///
548 /// if let RustcEntry::Vacant(v) = map.rustc_entry("poneyland") {
549 /// v.into_key();
550 /// }
551 /// ```
552 #[cfg_attr(feature = "inline-more", inline)]
553 pub fn into_key(self) -> K {
554 self.key
555 }
556
557 /// Sets the value of the entry with the RustcVacantEntry's key,
558 /// and returns a mutable reference to it.
559 ///
560 /// # Examples
561 ///
562 /// ```
563 /// use hashbrown::HashMap;
564 /// use hashbrown::hash_map::RustcEntry;
565 ///
566 /// let mut map: HashMap<&str, u32> = HashMap::new();
567 ///
568 /// if let RustcEntry::Vacant(o) = map.rustc_entry("poneyland") {
569 /// o.insert(37);
570 /// }
571 /// assert_eq!(map["poneyland"], 37);
572 /// ```
573 #[cfg_attr(feature = "inline-more", inline)]
574 pub fn insert(self, value: V) -> &'a mut V {
575 unsafe {
576 let bucket = self.table.insert_no_grow(self.hash, (self.key, value));
577 &mut bucket.as_mut().1
578 }
579 }
580
581 /// Sets the value of the entry with the RustcVacantEntry's key,
582 /// and returns a RustcOccupiedEntry.
583 ///
584 /// # Examples
585 ///
586 /// ```
587 /// use hashbrown::HashMap;
588 /// use hashbrown::hash_map::RustcEntry;
589 ///
590 /// let mut map: HashMap<&str, u32> = HashMap::new();
591 ///
592 /// if let RustcEntry::Vacant(v) = map.rustc_entry("poneyland") {
593 /// let o = v.insert_entry(37);
594 /// assert_eq!(o.get(), &37);
595 /// }
596 /// ```
597 #[cfg_attr(feature = "inline-more", inline)]
598 pub fn insert_entry(self, value: V) -> RustcOccupiedEntry<'a, K, V, A> {
599 let bucket = unsafe { self.table.insert_no_grow(self.hash, (self.key, value)) };
600 RustcOccupiedEntry {
601 elem: bucket,
602 table: self.table,
603 }
604 }
605 }
606
607 impl<K, V> IterMut<'_, K, V> {
608 /// Returns a iterator of references over the remaining items.
609 #[cfg_attr(feature = "inline-more", inline)]
610 pub fn rustc_iter(&self) -> Iter<'_, K, V> {
611 self.iter()
612 }
613 }
614
615 impl<K, V, A: Allocator> IntoIter<K, V, A> {
616 /// Returns a iterator of references over the remaining items.
617 #[cfg_attr(feature = "inline-more", inline)]
618 pub fn rustc_iter(&self) -> Iter<'_, K, V> {
619 self.iter()
620 }
621 }
622
623 impl<K, V, A: Allocator> Drain<'_, K, V, A> {
624 /// Returns a iterator of references over the remaining items.
625 #[cfg_attr(feature = "inline-more", inline)]
626 pub fn rustc_iter(&self) -> Iter<'_, K, V> {
627 self.iter()
628 }
629 }