1 | use crate::raw::{Allocator, Bucket, Global, RawDrain, RawIntoIter, RawIter, RawTable}; |
2 | use crate::TryReserveError; |
3 | use core::borrow::Borrow; |
4 | use core::fmt::{self, Debug}; |
5 | use core::hash::{BuildHasher, Hash}; |
6 | use core::iter::{FromIterator, FusedIterator}; |
7 | use core::marker::PhantomData; |
8 | use core::mem; |
9 | use core::ops::Index; |
10 | |
11 | /// Default hasher for `HashMap`. |
12 | #[cfg (feature = "ahash" )] |
13 | pub type DefaultHashBuilder = ahash::RandomState; |
14 | |
15 | /// Dummy default hasher for `HashMap`. |
16 | #[cfg (not(feature = "ahash" ))] |
17 | pub enum DefaultHashBuilder {} |
18 | |
19 | /// A hash map implemented with quadratic probing and SIMD lookup. |
20 | /// |
21 | /// The default hashing algorithm is currently [`AHash`], though this is |
22 | /// subject to change at any point in the future. This hash function is very |
23 | /// fast for all types of keys, but this algorithm will typically *not* protect |
24 | /// against attacks such as HashDoS. |
25 | /// |
26 | /// The hashing algorithm can be replaced on a per-`HashMap` basis using the |
27 | /// [`default`], [`with_hasher`], and [`with_capacity_and_hasher`] methods. Many |
28 | /// alternative algorithms are available on crates.io, such as the [`fnv`] crate. |
29 | /// |
30 | /// It is required that the keys implement the [`Eq`] and [`Hash`] traits, although |
31 | /// this can frequently be achieved by using `#[derive(PartialEq, Eq, Hash)]`. |
32 | /// If you implement these yourself, it is important that the following |
33 | /// property holds: |
34 | /// |
35 | /// ```text |
36 | /// k1 == k2 -> hash(k1) == hash(k2) |
37 | /// ``` |
38 | /// |
39 | /// In other words, if two keys are equal, their hashes must be equal. |
40 | /// |
41 | /// It is a logic error for a key to be modified in such a way that the key's |
42 | /// hash, as determined by the [`Hash`] trait, or its equality, as determined by |
43 | /// the [`Eq`] trait, changes while it is in the map. This is normally only |
44 | /// possible through [`Cell`], [`RefCell`], global state, I/O, or unsafe code. |
45 | /// |
46 | /// It is also a logic error for the [`Hash`] implementation of a key to panic. |
47 | /// This is generally only possible if the trait is implemented manually. If a |
48 | /// panic does occur then the contents of the `HashMap` may become corrupted and |
49 | /// some items may be dropped from the table. |
50 | /// |
51 | /// # Examples |
52 | /// |
53 | /// ``` |
54 | /// use hashbrown::HashMap; |
55 | /// |
56 | /// // Type inference lets us omit an explicit type signature (which |
57 | /// // would be `HashMap<String, String>` in this example). |
58 | /// let mut book_reviews = HashMap::new(); |
59 | /// |
60 | /// // Review some books. |
61 | /// book_reviews.insert( |
62 | /// "Adventures of Huckleberry Finn" .to_string(), |
63 | /// "My favorite book." .to_string(), |
64 | /// ); |
65 | /// book_reviews.insert( |
66 | /// "Grimms' Fairy Tales" .to_string(), |
67 | /// "Masterpiece." .to_string(), |
68 | /// ); |
69 | /// book_reviews.insert( |
70 | /// "Pride and Prejudice" .to_string(), |
71 | /// "Very enjoyable." .to_string(), |
72 | /// ); |
73 | /// book_reviews.insert( |
74 | /// "The Adventures of Sherlock Holmes" .to_string(), |
75 | /// "Eye lyked it alot." .to_string(), |
76 | /// ); |
77 | /// |
78 | /// // Check for a specific one. |
79 | /// // When collections store owned values (String), they can still be |
80 | /// // queried using references (&str). |
81 | /// if !book_reviews.contains_key("Les Misérables" ) { |
82 | /// println!("We've got {} reviews, but Les Misérables ain't one." , |
83 | /// book_reviews.len()); |
84 | /// } |
85 | /// |
86 | /// // oops, this review has a lot of spelling mistakes, let's delete it. |
87 | /// book_reviews.remove("The Adventures of Sherlock Holmes" ); |
88 | /// |
89 | /// // Look up the values associated with some keys. |
90 | /// let to_find = ["Pride and Prejudice" , "Alice's Adventure in Wonderland" ]; |
91 | /// for &book in &to_find { |
92 | /// match book_reviews.get(book) { |
93 | /// Some(review) => println!("{}: {}" , book, review), |
94 | /// None => println!("{} is unreviewed." , book) |
95 | /// } |
96 | /// } |
97 | /// |
98 | /// // Look up the value for a key (will panic if the key is not found). |
99 | /// println!("Review for Jane: {}" , book_reviews["Pride and Prejudice" ]); |
100 | /// |
101 | /// // Iterate over everything. |
102 | /// for (book, review) in &book_reviews { |
103 | /// println!("{}: \"{} \"" , book, review); |
104 | /// } |
105 | /// ``` |
106 | /// |
107 | /// `HashMap` also implements an [`Entry API`](#method.entry), which allows |
108 | /// for more complex methods of getting, setting, updating and removing keys and |
109 | /// their values: |
110 | /// |
111 | /// ``` |
112 | /// use hashbrown::HashMap; |
113 | /// |
114 | /// // type inference lets us omit an explicit type signature (which |
115 | /// // would be `HashMap<&str, u8>` in this example). |
116 | /// let mut player_stats = HashMap::new(); |
117 | /// |
118 | /// fn random_stat_buff() -> u8 { |
119 | /// // could actually return some random value here - let's just return |
120 | /// // some fixed value for now |
121 | /// 42 |
122 | /// } |
123 | /// |
124 | /// // insert a key only if it doesn't already exist |
125 | /// player_stats.entry("health" ).or_insert(100); |
126 | /// |
127 | /// // insert a key using a function that provides a new value only if it |
128 | /// // doesn't already exist |
129 | /// player_stats.entry("defence" ).or_insert_with(random_stat_buff); |
130 | /// |
131 | /// // update a key, guarding against the key possibly not being set |
132 | /// let stat = player_stats.entry("attack" ).or_insert(100); |
133 | /// *stat += random_stat_buff(); |
134 | /// ``` |
135 | /// |
136 | /// The easiest way to use `HashMap` with a custom key type is to derive [`Eq`] and [`Hash`]. |
137 | /// We must also derive [`PartialEq`]. |
138 | /// |
139 | /// [`Eq`]: https://doc.rust-lang.org/std/cmp/trait.Eq.html |
140 | /// [`Hash`]: https://doc.rust-lang.org/std/hash/trait.Hash.html |
141 | /// [`PartialEq`]: https://doc.rust-lang.org/std/cmp/trait.PartialEq.html |
142 | /// [`RefCell`]: https://doc.rust-lang.org/std/cell/struct.RefCell.html |
143 | /// [`Cell`]: https://doc.rust-lang.org/std/cell/struct.Cell.html |
144 | /// [`default`]: #method.default |
145 | /// [`with_hasher`]: #method.with_hasher |
146 | /// [`with_capacity_and_hasher`]: #method.with_capacity_and_hasher |
147 | /// [`fnv`]: https://crates.io/crates/fnv |
148 | /// [`AHash`]: https://crates.io/crates/ahash |
149 | /// |
150 | /// ``` |
151 | /// use hashbrown::HashMap; |
152 | /// |
153 | /// #[derive(Hash, Eq, PartialEq, Debug)] |
154 | /// struct Viking { |
155 | /// name: String, |
156 | /// country: String, |
157 | /// } |
158 | /// |
159 | /// impl Viking { |
160 | /// /// Creates a new Viking. |
161 | /// fn new(name: &str, country: &str) -> Viking { |
162 | /// Viking { name: name.to_string(), country: country.to_string() } |
163 | /// } |
164 | /// } |
165 | /// |
166 | /// // Use a HashMap to store the vikings' health points. |
167 | /// let mut vikings = HashMap::new(); |
168 | /// |
169 | /// vikings.insert(Viking::new("Einar" , "Norway" ), 25); |
170 | /// vikings.insert(Viking::new("Olaf" , "Denmark" ), 24); |
171 | /// vikings.insert(Viking::new("Harald" , "Iceland" ), 12); |
172 | /// |
173 | /// // Use derived implementation to print the status of the vikings. |
174 | /// for (viking, health) in &vikings { |
175 | /// println!("{:?} has {} hp" , viking, health); |
176 | /// } |
177 | /// ``` |
178 | /// |
179 | /// A `HashMap` with fixed list of elements can be initialized from an array: |
180 | /// |
181 | /// ``` |
182 | /// use hashbrown::HashMap; |
183 | /// |
184 | /// let timber_resources: HashMap<&str, i32> = [("Norway" , 100), ("Denmark" , 50), ("Iceland" , 10)] |
185 | /// .iter().cloned().collect(); |
186 | /// // use the values stored in map |
187 | /// ``` |
188 | pub struct HashMap<K, V, S = DefaultHashBuilder, A: Allocator + Clone = Global> { |
189 | pub(crate) hash_builder: S, |
190 | pub(crate) table: RawTable<(K, V), A>, |
191 | } |
192 | |
193 | impl<K: Clone, V: Clone, S: Clone, A: Allocator + Clone> Clone for HashMap<K, V, S, A> { |
194 | fn clone(&self) -> Self { |
195 | HashMap { |
196 | hash_builder: self.hash_builder.clone(), |
197 | table: self.table.clone(), |
198 | } |
199 | } |
200 | |
201 | fn clone_from(&mut self, source: &Self) { |
202 | self.table.clone_from(&source.table); |
203 | |
204 | // Update hash_builder only if we successfully cloned all elements. |
205 | self.hash_builder.clone_from(&source.hash_builder); |
206 | } |
207 | } |
208 | |
209 | /// Ensures that a single closure type across uses of this which, in turn prevents multiple |
210 | /// instances of any functions like RawTable::reserve from being generated |
211 | #[cfg_attr (feature = "inline-more" , inline)] |
212 | pub(crate) fn make_hasher<K, Q, V, S>(hash_builder: &S) -> impl Fn(&(Q, V)) -> u64 + '_ |
213 | where |
214 | K: Borrow<Q>, |
215 | Q: Hash, |
216 | S: BuildHasher, |
217 | { |
218 | move |val: &(Q, V)| make_hash::<K, Q, S>(hash_builder, &val.0) |
219 | } |
220 | |
221 | /// Ensures that a single closure type across uses of this which, in turn prevents multiple |
222 | /// instances of any functions like RawTable::reserve from being generated |
223 | #[cfg_attr (feature = "inline-more" , inline)] |
224 | fn equivalent_key<Q, K, V>(k: &Q) -> impl Fn(&(K, V)) -> bool + '_ |
225 | where |
226 | K: Borrow<Q>, |
227 | Q: ?Sized + Eq, |
228 | { |
229 | move |x: &(K, V)| k.eq(x.0.borrow()) |
230 | } |
231 | |
232 | /// Ensures that a single closure type across uses of this which, in turn prevents multiple |
233 | /// instances of any functions like RawTable::reserve from being generated |
234 | #[cfg_attr (feature = "inline-more" , inline)] |
235 | fn equivalent<Q, K>(k: &Q) -> impl Fn(&K) -> bool + '_ |
236 | where |
237 | K: Borrow<Q>, |
238 | Q: ?Sized + Eq, |
239 | { |
240 | move |x: &K| k.eq(x.borrow()) |
241 | } |
242 | |
243 | #[cfg (not(feature = "nightly" ))] |
244 | #[cfg_attr (feature = "inline-more" , inline)] |
245 | pub(crate) fn make_hash<K, Q, S>(hash_builder: &S, val: &Q) -> u64 |
246 | where |
247 | K: Borrow<Q>, |
248 | Q: Hash + ?Sized, |
249 | S: BuildHasher, |
250 | { |
251 | use core::hash::Hasher; |
252 | let mut state: ::Hasher = hash_builder.build_hasher(); |
253 | val.hash(&mut state); |
254 | state.finish() |
255 | } |
256 | |
257 | #[cfg (feature = "nightly" )] |
258 | #[cfg_attr (feature = "inline-more" , inline)] |
259 | pub(crate) fn make_hash<K, Q, S>(hash_builder: &S, val: &Q) -> u64 |
260 | where |
261 | K: Borrow<Q>, |
262 | Q: Hash + ?Sized, |
263 | S: BuildHasher, |
264 | { |
265 | hash_builder.hash_one(val) |
266 | } |
267 | |
268 | #[cfg (not(feature = "nightly" ))] |
269 | #[cfg_attr (feature = "inline-more" , inline)] |
270 | pub(crate) fn make_insert_hash<K, S>(hash_builder: &S, val: &K) -> u64 |
271 | where |
272 | K: Hash, |
273 | S: BuildHasher, |
274 | { |
275 | use core::hash::Hasher; |
276 | let mut state: ::Hasher = hash_builder.build_hasher(); |
277 | val.hash(&mut state); |
278 | state.finish() |
279 | } |
280 | |
281 | #[cfg (feature = "nightly" )] |
282 | #[cfg_attr (feature = "inline-more" , inline)] |
283 | pub(crate) fn make_insert_hash<K, S>(hash_builder: &S, val: &K) -> u64 |
284 | where |
285 | K: Hash, |
286 | S: BuildHasher, |
287 | { |
288 | hash_builder.hash_one(val) |
289 | } |
290 | |
291 | #[cfg (feature = "ahash" )] |
292 | impl<K, V> HashMap<K, V, DefaultHashBuilder> { |
293 | /// Creates an empty `HashMap`. |
294 | /// |
295 | /// The hash map is initially created with a capacity of 0, so it will not allocate until it |
296 | /// is first inserted into. |
297 | /// |
298 | /// # Examples |
299 | /// |
300 | /// ``` |
301 | /// use hashbrown::HashMap; |
302 | /// let mut map: HashMap<&str, i32> = HashMap::new(); |
303 | /// assert_eq!(map.len(), 0); |
304 | /// assert_eq!(map.capacity(), 0); |
305 | /// ``` |
306 | #[cfg_attr (feature = "inline-more" , inline)] |
307 | pub fn new() -> Self { |
308 | Self::default() |
309 | } |
310 | |
311 | /// Creates an empty `HashMap` with the specified capacity. |
312 | /// |
313 | /// The hash map will be able to hold at least `capacity` elements without |
314 | /// reallocating. If `capacity` is 0, the hash map will not allocate. |
315 | /// |
316 | /// # Examples |
317 | /// |
318 | /// ``` |
319 | /// use hashbrown::HashMap; |
320 | /// let mut map: HashMap<&str, i32> = HashMap::with_capacity(10); |
321 | /// assert_eq!(map.len(), 0); |
322 | /// assert!(map.capacity() >= 10); |
323 | /// ``` |
324 | #[cfg_attr (feature = "inline-more" , inline)] |
325 | pub fn with_capacity(capacity: usize) -> Self { |
326 | Self::with_capacity_and_hasher(capacity, DefaultHashBuilder::default()) |
327 | } |
328 | } |
329 | |
330 | #[cfg (feature = "ahash" )] |
331 | impl<K, V, A: Allocator + Clone> HashMap<K, V, DefaultHashBuilder, A> { |
332 | /// Creates an empty `HashMap` using the given allocator. |
333 | /// |
334 | /// The hash map is initially created with a capacity of 0, so it will not allocate until it |
335 | /// is first inserted into. |
336 | #[cfg_attr (feature = "inline-more" , inline)] |
337 | pub fn new_in(alloc: A) -> Self { |
338 | Self::with_hasher_in(DefaultHashBuilder::default(), alloc) |
339 | } |
340 | |
341 | /// Creates an empty `HashMap` with the specified capacity using the given allocator. |
342 | /// |
343 | /// The hash map will be able to hold at least `capacity` elements without |
344 | /// reallocating. If `capacity` is 0, the hash map will not allocate. |
345 | #[cfg_attr (feature = "inline-more" , inline)] |
346 | pub fn with_capacity_in(capacity: usize, alloc: A) -> Self { |
347 | Self::with_capacity_and_hasher_in(capacity, DefaultHashBuilder::default(), alloc) |
348 | } |
349 | } |
350 | |
351 | impl<K, V, S> HashMap<K, V, S> { |
352 | /// Creates an empty `HashMap` which will use the given hash builder to hash |
353 | /// keys. |
354 | /// |
355 | /// The hash map is initially created with a capacity of 0, so it will not |
356 | /// allocate until it is first inserted into. |
357 | /// |
358 | /// Warning: `hash_builder` is normally randomly generated, and |
359 | /// is designed to allow HashMaps to be resistant to attacks that |
360 | /// cause many collisions and very poor performance. Setting it |
361 | /// manually using this function can expose a DoS attack vector. |
362 | /// |
363 | /// The `hash_builder` passed should implement the [`BuildHasher`] trait for |
364 | /// the HashMap to be useful, see its documentation for details. |
365 | /// |
366 | /// # Examples |
367 | /// |
368 | /// ``` |
369 | /// use hashbrown::HashMap; |
370 | /// use hashbrown::hash_map::DefaultHashBuilder; |
371 | /// |
372 | /// let s = DefaultHashBuilder::default(); |
373 | /// let mut map = HashMap::with_hasher(s); |
374 | /// assert_eq!(map.len(), 0); |
375 | /// assert_eq!(map.capacity(), 0); |
376 | /// |
377 | /// map.insert(1, 2); |
378 | /// ``` |
379 | /// |
380 | /// [`BuildHasher`]: https://doc.rust-lang.org/std/hash/trait.BuildHasher.html |
381 | #[cfg_attr (feature = "inline-more" , inline)] |
382 | pub const fn with_hasher(hash_builder: S) -> Self { |
383 | Self { |
384 | hash_builder, |
385 | table: RawTable::new(), |
386 | } |
387 | } |
388 | |
389 | /// Creates an empty `HashMap` with the specified capacity, using `hash_builder` |
390 | /// to hash the keys. |
391 | /// |
392 | /// The hash map will be able to hold at least `capacity` elements without |
393 | /// reallocating. If `capacity` is 0, the hash map will not allocate. |
394 | /// |
395 | /// Warning: `hash_builder` is normally randomly generated, and |
396 | /// is designed to allow HashMaps to be resistant to attacks that |
397 | /// cause many collisions and very poor performance. Setting it |
398 | /// manually using this function can expose a DoS attack vector. |
399 | /// |
400 | /// The `hash_builder` passed should implement the [`BuildHasher`] trait for |
401 | /// the HashMap to be useful, see its documentation for details. |
402 | /// |
403 | /// # Examples |
404 | /// |
405 | /// ``` |
406 | /// use hashbrown::HashMap; |
407 | /// use hashbrown::hash_map::DefaultHashBuilder; |
408 | /// |
409 | /// let s = DefaultHashBuilder::default(); |
410 | /// let mut map = HashMap::with_capacity_and_hasher(10, s); |
411 | /// assert_eq!(map.len(), 0); |
412 | /// assert!(map.capacity() >= 10); |
413 | /// |
414 | /// map.insert(1, 2); |
415 | /// ``` |
416 | /// |
417 | /// [`BuildHasher`]: https://doc.rust-lang.org/std/hash/trait.BuildHasher.html |
418 | #[cfg_attr (feature = "inline-more" , inline)] |
419 | pub fn with_capacity_and_hasher(capacity: usize, hash_builder: S) -> Self { |
420 | Self { |
421 | hash_builder, |
422 | table: RawTable::with_capacity(capacity), |
423 | } |
424 | } |
425 | } |
426 | |
427 | impl<K, V, S, A: Allocator + Clone> HashMap<K, V, S, A> { |
428 | /// Returns a reference to the underlying allocator. |
429 | #[inline ] |
430 | pub fn allocator(&self) -> &A { |
431 | self.table.allocator() |
432 | } |
433 | |
434 | /// Creates an empty `HashMap` which will use the given hash builder to hash |
435 | /// keys. It will be allocated with the given allocator. |
436 | /// |
437 | /// The created map has the default initial capacity. |
438 | /// |
439 | /// Warning: `hash_builder` is normally randomly generated, and |
440 | /// is designed to allow HashMaps to be resistant to attacks that |
441 | /// cause many collisions and very poor performance. Setting it |
442 | /// manually using this function can expose a DoS attack vector. |
443 | /// |
444 | /// # Examples |
445 | /// |
446 | /// ``` |
447 | /// use hashbrown::HashMap; |
448 | /// use hashbrown::hash_map::DefaultHashBuilder; |
449 | /// |
450 | /// let s = DefaultHashBuilder::default(); |
451 | /// let mut map = HashMap::with_hasher(s); |
452 | /// map.insert(1, 2); |
453 | /// ``` |
454 | #[cfg_attr (feature = "inline-more" , inline)] |
455 | pub fn with_hasher_in(hash_builder: S, alloc: A) -> Self { |
456 | Self { |
457 | hash_builder, |
458 | table: RawTable::new_in(alloc), |
459 | } |
460 | } |
461 | |
462 | /// Creates an empty `HashMap` with the specified capacity, using `hash_builder` |
463 | /// to hash the keys. It will be allocated with the given allocator. |
464 | /// |
465 | /// The hash map will be able to hold at least `capacity` elements without |
466 | /// reallocating. If `capacity` is 0, the hash map will not allocate. |
467 | /// |
468 | /// Warning: `hash_builder` is normally randomly generated, and |
469 | /// is designed to allow HashMaps to be resistant to attacks that |
470 | /// cause many collisions and very poor performance. Setting it |
471 | /// manually using this function can expose a DoS attack vector. |
472 | /// |
473 | /// # Examples |
474 | /// |
475 | /// ``` |
476 | /// use hashbrown::HashMap; |
477 | /// use hashbrown::hash_map::DefaultHashBuilder; |
478 | /// |
479 | /// let s = DefaultHashBuilder::default(); |
480 | /// let mut map = HashMap::with_capacity_and_hasher(10, s); |
481 | /// map.insert(1, 2); |
482 | /// ``` |
483 | #[cfg_attr (feature = "inline-more" , inline)] |
484 | pub fn with_capacity_and_hasher_in(capacity: usize, hash_builder: S, alloc: A) -> Self { |
485 | Self { |
486 | hash_builder, |
487 | table: RawTable::with_capacity_in(capacity, alloc), |
488 | } |
489 | } |
490 | |
491 | /// Returns a reference to the map's [`BuildHasher`]. |
492 | /// |
493 | /// [`BuildHasher`]: https://doc.rust-lang.org/std/hash/trait.BuildHasher.html |
494 | /// |
495 | /// # Examples |
496 | /// |
497 | /// ``` |
498 | /// use hashbrown::HashMap; |
499 | /// use hashbrown::hash_map::DefaultHashBuilder; |
500 | /// |
501 | /// let hasher = DefaultHashBuilder::default(); |
502 | /// let map: HashMap<i32, i32> = HashMap::with_hasher(hasher); |
503 | /// let hasher: &DefaultHashBuilder = map.hasher(); |
504 | /// ``` |
505 | #[cfg_attr (feature = "inline-more" , inline)] |
506 | pub fn hasher(&self) -> &S { |
507 | &self.hash_builder |
508 | } |
509 | |
510 | /// Returns the number of elements the map can hold without reallocating. |
511 | /// |
512 | /// This number is a lower bound; the `HashMap<K, V>` might be able to hold |
513 | /// more, but is guaranteed to be able to hold at least this many. |
514 | /// |
515 | /// # Examples |
516 | /// |
517 | /// ``` |
518 | /// use hashbrown::HashMap; |
519 | /// let map: HashMap<i32, i32> = HashMap::with_capacity(100); |
520 | /// assert_eq!(map.len(), 0); |
521 | /// assert!(map.capacity() >= 100); |
522 | /// ``` |
523 | #[cfg_attr (feature = "inline-more" , inline)] |
524 | pub fn capacity(&self) -> usize { |
525 | self.table.capacity() |
526 | } |
527 | |
528 | /// An iterator visiting all keys in arbitrary order. |
529 | /// The iterator element type is `&'a K`. |
530 | /// |
531 | /// # Examples |
532 | /// |
533 | /// ``` |
534 | /// use hashbrown::HashMap; |
535 | /// |
536 | /// let mut map = HashMap::new(); |
537 | /// map.insert("a" , 1); |
538 | /// map.insert("b" , 2); |
539 | /// map.insert("c" , 3); |
540 | /// assert_eq!(map.len(), 3); |
541 | /// let mut vec: Vec<&str> = Vec::new(); |
542 | /// |
543 | /// for key in map.keys() { |
544 | /// println!("{}" , key); |
545 | /// vec.push(*key); |
546 | /// } |
547 | /// |
548 | /// // The `Keys` iterator produces keys in arbitrary order, so the |
549 | /// // keys must be sorted to test them against a sorted array. |
550 | /// vec.sort_unstable(); |
551 | /// assert_eq!(vec, ["a" , "b" , "c" ]); |
552 | /// |
553 | /// assert_eq!(map.len(), 3); |
554 | /// ``` |
555 | #[cfg_attr (feature = "inline-more" , inline)] |
556 | pub fn keys(&self) -> Keys<'_, K, V> { |
557 | Keys { inner: self.iter() } |
558 | } |
559 | |
560 | /// An iterator visiting all values in arbitrary order. |
561 | /// The iterator element type is `&'a V`. |
562 | /// |
563 | /// # Examples |
564 | /// |
565 | /// ``` |
566 | /// use hashbrown::HashMap; |
567 | /// |
568 | /// let mut map = HashMap::new(); |
569 | /// map.insert("a" , 1); |
570 | /// map.insert("b" , 2); |
571 | /// map.insert("c" , 3); |
572 | /// assert_eq!(map.len(), 3); |
573 | /// let mut vec: Vec<i32> = Vec::new(); |
574 | /// |
575 | /// for val in map.values() { |
576 | /// println!("{}" , val); |
577 | /// vec.push(*val); |
578 | /// } |
579 | /// |
580 | /// // The `Values` iterator produces values in arbitrary order, so the |
581 | /// // values must be sorted to test them against a sorted array. |
582 | /// vec.sort_unstable(); |
583 | /// assert_eq!(vec, [1, 2, 3]); |
584 | /// |
585 | /// assert_eq!(map.len(), 3); |
586 | /// ``` |
587 | #[cfg_attr (feature = "inline-more" , inline)] |
588 | pub fn values(&self) -> Values<'_, K, V> { |
589 | Values { inner: self.iter() } |
590 | } |
591 | |
592 | /// An iterator visiting all values mutably in arbitrary order. |
593 | /// The iterator element type is `&'a mut V`. |
594 | /// |
595 | /// # Examples |
596 | /// |
597 | /// ``` |
598 | /// use hashbrown::HashMap; |
599 | /// |
600 | /// let mut map = HashMap::new(); |
601 | /// |
602 | /// map.insert("a" , 1); |
603 | /// map.insert("b" , 2); |
604 | /// map.insert("c" , 3); |
605 | /// |
606 | /// for val in map.values_mut() { |
607 | /// *val = *val + 10; |
608 | /// } |
609 | /// |
610 | /// assert_eq!(map.len(), 3); |
611 | /// let mut vec: Vec<i32> = Vec::new(); |
612 | /// |
613 | /// for val in map.values() { |
614 | /// println!("{}" , val); |
615 | /// vec.push(*val); |
616 | /// } |
617 | /// |
618 | /// // The `Values` iterator produces values in arbitrary order, so the |
619 | /// // values must be sorted to test them against a sorted array. |
620 | /// vec.sort_unstable(); |
621 | /// assert_eq!(vec, [11, 12, 13]); |
622 | /// |
623 | /// assert_eq!(map.len(), 3); |
624 | /// ``` |
625 | #[cfg_attr (feature = "inline-more" , inline)] |
626 | pub fn values_mut(&mut self) -> ValuesMut<'_, K, V> { |
627 | ValuesMut { |
628 | inner: self.iter_mut(), |
629 | } |
630 | } |
631 | |
632 | /// An iterator visiting all key-value pairs in arbitrary order. |
633 | /// The iterator element type is `(&'a K, &'a V)`. |
634 | /// |
635 | /// # Examples |
636 | /// |
637 | /// ``` |
638 | /// use hashbrown::HashMap; |
639 | /// |
640 | /// let mut map = HashMap::new(); |
641 | /// map.insert("a" , 1); |
642 | /// map.insert("b" , 2); |
643 | /// map.insert("c" , 3); |
644 | /// assert_eq!(map.len(), 3); |
645 | /// let mut vec: Vec<(&str, i32)> = Vec::new(); |
646 | /// |
647 | /// for (key, val) in map.iter() { |
648 | /// println!("key: {} val: {}" , key, val); |
649 | /// vec.push((*key, *val)); |
650 | /// } |
651 | /// |
652 | /// // The `Iter` iterator produces items in arbitrary order, so the |
653 | /// // items must be sorted to test them against a sorted array. |
654 | /// vec.sort_unstable(); |
655 | /// assert_eq!(vec, [("a" , 1), ("b" , 2), ("c" , 3)]); |
656 | /// |
657 | /// assert_eq!(map.len(), 3); |
658 | /// ``` |
659 | #[cfg_attr (feature = "inline-more" , inline)] |
660 | pub fn iter(&self) -> Iter<'_, K, V> { |
661 | // Here we tie the lifetime of self to the iter. |
662 | unsafe { |
663 | Iter { |
664 | inner: self.table.iter(), |
665 | marker: PhantomData, |
666 | } |
667 | } |
668 | } |
669 | |
670 | /// An iterator visiting all key-value pairs in arbitrary order, |
671 | /// with mutable references to the values. |
672 | /// The iterator element type is `(&'a K, &'a mut V)`. |
673 | /// |
674 | /// # Examples |
675 | /// |
676 | /// ``` |
677 | /// use hashbrown::HashMap; |
678 | /// |
679 | /// let mut map = HashMap::new(); |
680 | /// map.insert("a" , 1); |
681 | /// map.insert("b" , 2); |
682 | /// map.insert("c" , 3); |
683 | /// |
684 | /// // Update all values |
685 | /// for (_, val) in map.iter_mut() { |
686 | /// *val *= 2; |
687 | /// } |
688 | /// |
689 | /// assert_eq!(map.len(), 3); |
690 | /// let mut vec: Vec<(&str, i32)> = Vec::new(); |
691 | /// |
692 | /// for (key, val) in &map { |
693 | /// println!("key: {} val: {}" , key, val); |
694 | /// vec.push((*key, *val)); |
695 | /// } |
696 | /// |
697 | /// // The `Iter` iterator produces items in arbitrary order, so the |
698 | /// // items must be sorted to test them against a sorted array. |
699 | /// vec.sort_unstable(); |
700 | /// assert_eq!(vec, [("a" , 2), ("b" , 4), ("c" , 6)]); |
701 | /// |
702 | /// assert_eq!(map.len(), 3); |
703 | /// ``` |
704 | #[cfg_attr (feature = "inline-more" , inline)] |
705 | pub fn iter_mut(&mut self) -> IterMut<'_, K, V> { |
706 | // Here we tie the lifetime of self to the iter. |
707 | unsafe { |
708 | IterMut { |
709 | inner: self.table.iter(), |
710 | marker: PhantomData, |
711 | } |
712 | } |
713 | } |
714 | |
715 | #[cfg (test)] |
716 | #[cfg_attr (feature = "inline-more" , inline)] |
717 | fn raw_capacity(&self) -> usize { |
718 | self.table.buckets() |
719 | } |
720 | |
721 | /// Returns the number of elements in the map. |
722 | /// |
723 | /// # Examples |
724 | /// |
725 | /// ``` |
726 | /// use hashbrown::HashMap; |
727 | /// |
728 | /// let mut a = HashMap::new(); |
729 | /// assert_eq!(a.len(), 0); |
730 | /// a.insert(1, "a" ); |
731 | /// assert_eq!(a.len(), 1); |
732 | /// ``` |
733 | #[cfg_attr (feature = "inline-more" , inline)] |
734 | pub fn len(&self) -> usize { |
735 | self.table.len() |
736 | } |
737 | |
738 | /// Returns `true` if the map contains no elements. |
739 | /// |
740 | /// # Examples |
741 | /// |
742 | /// ``` |
743 | /// use hashbrown::HashMap; |
744 | /// |
745 | /// let mut a = HashMap::new(); |
746 | /// assert!(a.is_empty()); |
747 | /// a.insert(1, "a" ); |
748 | /// assert!(!a.is_empty()); |
749 | /// ``` |
750 | #[cfg_attr (feature = "inline-more" , inline)] |
751 | pub fn is_empty(&self) -> bool { |
752 | self.len() == 0 |
753 | } |
754 | |
755 | /// Clears the map, returning all key-value pairs as an iterator. Keeps the |
756 | /// allocated memory for reuse. |
757 | /// |
758 | /// If the returned iterator is dropped before being fully consumed, it |
759 | /// drops the remaining key-value pairs. The returned iterator keeps a |
760 | /// mutable borrow on the vector to optimize its implementation. |
761 | /// |
762 | /// # Examples |
763 | /// |
764 | /// ``` |
765 | /// use hashbrown::HashMap; |
766 | /// |
767 | /// let mut a = HashMap::new(); |
768 | /// a.insert(1, "a" ); |
769 | /// a.insert(2, "b" ); |
770 | /// let capacity_before_drain = a.capacity(); |
771 | /// |
772 | /// for (k, v) in a.drain().take(1) { |
773 | /// assert!(k == 1 || k == 2); |
774 | /// assert!(v == "a" || v == "b" ); |
775 | /// } |
776 | /// |
777 | /// // As we can see, the map is empty and contains no element. |
778 | /// assert!(a.is_empty() && a.len() == 0); |
779 | /// // But map capacity is equal to old one. |
780 | /// assert_eq!(a.capacity(), capacity_before_drain); |
781 | /// |
782 | /// let mut a = HashMap::new(); |
783 | /// a.insert(1, "a" ); |
784 | /// a.insert(2, "b" ); |
785 | /// |
786 | /// { // Iterator is dropped without being consumed. |
787 | /// let d = a.drain(); |
788 | /// } |
789 | /// |
790 | /// // But the map is empty even if we do not use Drain iterator. |
791 | /// assert!(a.is_empty()); |
792 | /// ``` |
793 | #[cfg_attr (feature = "inline-more" , inline)] |
794 | pub fn drain(&mut self) -> Drain<'_, K, V, A> { |
795 | Drain { |
796 | inner: self.table.drain(), |
797 | } |
798 | } |
799 | |
800 | /// Retains only the elements specified by the predicate. Keeps the |
801 | /// allocated memory for reuse. |
802 | /// |
803 | /// In other words, remove all pairs `(k, v)` such that `f(&k, &mut v)` returns `false`. |
804 | /// The elements are visited in unsorted (and unspecified) order. |
805 | /// |
806 | /// # Examples |
807 | /// |
808 | /// ``` |
809 | /// use hashbrown::HashMap; |
810 | /// |
811 | /// let mut map: HashMap<i32, i32> = (0..8).map(|x|(x, x*10)).collect(); |
812 | /// assert_eq!(map.len(), 8); |
813 | /// let capacity_before_retain = map.capacity(); |
814 | /// |
815 | /// map.retain(|&k, _| k % 2 == 0); |
816 | /// |
817 | /// // We can see, that the number of elements inside map is changed. |
818 | /// assert_eq!(map.len(), 4); |
819 | /// // But map capacity is equal to old one. |
820 | /// assert_eq!(map.capacity(), capacity_before_retain); |
821 | /// |
822 | /// let mut vec: Vec<(i32, i32)> = map.iter().map(|(&k, &v)| (k, v)).collect(); |
823 | /// vec.sort_unstable(); |
824 | /// assert_eq!(vec, [(0, 0), (2, 20), (4, 40), (6, 60)]); |
825 | /// ``` |
826 | pub fn retain<F>(&mut self, mut f: F) |
827 | where |
828 | F: FnMut(&K, &mut V) -> bool, |
829 | { |
830 | // Here we only use `iter` as a temporary, preventing use-after-free |
831 | unsafe { |
832 | for item in self.table.iter() { |
833 | let &mut (ref key, ref mut value) = item.as_mut(); |
834 | if !f(key, value) { |
835 | self.table.erase(item); |
836 | } |
837 | } |
838 | } |
839 | } |
840 | |
841 | /// Drains elements which are true under the given predicate, |
842 | /// and returns an iterator over the removed items. |
843 | /// |
844 | /// In other words, move all pairs `(k, v)` such that `f(&k, &mut v)` returns `true` out |
845 | /// into another iterator. |
846 | /// |
847 | /// Note that `drain_filter` lets you mutate every value in the filter closure, regardless of |
848 | /// whether you choose to keep or remove it. |
849 | /// |
850 | /// When the returned DrainedFilter is dropped, any remaining elements that satisfy |
851 | /// the predicate are dropped from the table. |
852 | /// |
853 | /// It is unspecified how many more elements will be subjected to the closure |
854 | /// if a panic occurs in the closure, or a panic occurs while dropping an element, |
855 | /// or if the `DrainFilter` value is leaked. |
856 | /// |
857 | /// Keeps the allocated memory for reuse. |
858 | /// |
859 | /// # Examples |
860 | /// |
861 | /// ``` |
862 | /// use hashbrown::HashMap; |
863 | /// |
864 | /// let mut map: HashMap<i32, i32> = (0..8).map(|x| (x, x)).collect(); |
865 | /// let capacity_before_drain_filter = map.capacity(); |
866 | /// let drained: HashMap<i32, i32> = map.drain_filter(|k, _v| k % 2 == 0).collect(); |
867 | /// |
868 | /// let mut evens = drained.keys().cloned().collect::<Vec<_>>(); |
869 | /// let mut odds = map.keys().cloned().collect::<Vec<_>>(); |
870 | /// evens.sort(); |
871 | /// odds.sort(); |
872 | /// |
873 | /// assert_eq!(evens, vec![0, 2, 4, 6]); |
874 | /// assert_eq!(odds, vec![1, 3, 5, 7]); |
875 | /// // Map capacity is equal to old one. |
876 | /// assert_eq!(map.capacity(), capacity_before_drain_filter); |
877 | /// |
878 | /// let mut map: HashMap<i32, i32> = (0..8).map(|x| (x, x)).collect(); |
879 | /// |
880 | /// { // Iterator is dropped without being consumed. |
881 | /// let d = map.drain_filter(|k, _v| k % 2 != 0); |
882 | /// } |
883 | /// |
884 | /// // But the map lens have been reduced by half |
885 | /// // even if we do not use DrainFilter iterator. |
886 | /// assert_eq!(map.len(), 4); |
887 | /// ``` |
888 | #[cfg_attr (feature = "inline-more" , inline)] |
889 | pub fn drain_filter<F>(&mut self, f: F) -> DrainFilter<'_, K, V, F, A> |
890 | where |
891 | F: FnMut(&K, &mut V) -> bool, |
892 | { |
893 | DrainFilter { |
894 | f, |
895 | inner: DrainFilterInner { |
896 | iter: unsafe { self.table.iter() }, |
897 | table: &mut self.table, |
898 | }, |
899 | } |
900 | } |
901 | |
902 | /// Clears the map, removing all key-value pairs. Keeps the allocated memory |
903 | /// for reuse. |
904 | /// |
905 | /// # Examples |
906 | /// |
907 | /// ``` |
908 | /// use hashbrown::HashMap; |
909 | /// |
910 | /// let mut a = HashMap::new(); |
911 | /// a.insert(1, "a" ); |
912 | /// let capacity_before_clear = a.capacity(); |
913 | /// |
914 | /// a.clear(); |
915 | /// |
916 | /// // Map is empty. |
917 | /// assert!(a.is_empty()); |
918 | /// // But map capacity is equal to old one. |
919 | /// assert_eq!(a.capacity(), capacity_before_clear); |
920 | /// ``` |
921 | #[cfg_attr (feature = "inline-more" , inline)] |
922 | pub fn clear(&mut self) { |
923 | self.table.clear(); |
924 | } |
925 | |
926 | /// Creates a consuming iterator visiting all the keys in arbitrary order. |
927 | /// The map cannot be used after calling this. |
928 | /// The iterator element type is `K`. |
929 | /// |
930 | /// # Examples |
931 | /// |
932 | /// ``` |
933 | /// use hashbrown::HashMap; |
934 | /// |
935 | /// let mut map = HashMap::new(); |
936 | /// map.insert("a" , 1); |
937 | /// map.insert("b" , 2); |
938 | /// map.insert("c" , 3); |
939 | /// |
940 | /// let mut vec: Vec<&str> = map.into_keys().collect(); |
941 | /// |
942 | /// // The `IntoKeys` iterator produces keys in arbitrary order, so the |
943 | /// // keys must be sorted to test them against a sorted array. |
944 | /// vec.sort_unstable(); |
945 | /// assert_eq!(vec, ["a" , "b" , "c" ]); |
946 | /// ``` |
947 | #[inline ] |
948 | pub fn into_keys(self) -> IntoKeys<K, V, A> { |
949 | IntoKeys { |
950 | inner: self.into_iter(), |
951 | } |
952 | } |
953 | |
954 | /// Creates a consuming iterator visiting all the values in arbitrary order. |
955 | /// The map cannot be used after calling this. |
956 | /// The iterator element type is `V`. |
957 | /// |
958 | /// # Examples |
959 | /// |
960 | /// ``` |
961 | /// use hashbrown::HashMap; |
962 | /// |
963 | /// let mut map = HashMap::new(); |
964 | /// map.insert("a" , 1); |
965 | /// map.insert("b" , 2); |
966 | /// map.insert("c" , 3); |
967 | /// |
968 | /// let mut vec: Vec<i32> = map.into_values().collect(); |
969 | /// |
970 | /// // The `IntoValues` iterator produces values in arbitrary order, so |
971 | /// // the values must be sorted to test them against a sorted array. |
972 | /// vec.sort_unstable(); |
973 | /// assert_eq!(vec, [1, 2, 3]); |
974 | /// ``` |
975 | #[inline ] |
976 | pub fn into_values(self) -> IntoValues<K, V, A> { |
977 | IntoValues { |
978 | inner: self.into_iter(), |
979 | } |
980 | } |
981 | } |
982 | |
983 | impl<K, V, S, A> HashMap<K, V, S, A> |
984 | where |
985 | K: Eq + Hash, |
986 | S: BuildHasher, |
987 | A: Allocator + Clone, |
988 | { |
989 | /// Reserves capacity for at least `additional` more elements to be inserted |
990 | /// in the `HashMap`. The collection may reserve more space to avoid |
991 | /// frequent reallocations. |
992 | /// |
993 | /// # Panics |
994 | /// |
995 | /// Panics if the new allocation size overflows [`usize`]. |
996 | /// |
997 | /// [`usize`]: https://doc.rust-lang.org/std/primitive.usize.html |
998 | /// |
999 | /// # Examples |
1000 | /// |
1001 | /// ``` |
1002 | /// use hashbrown::HashMap; |
1003 | /// let mut map: HashMap<&str, i32> = HashMap::new(); |
1004 | /// // Map is empty and doesn't allocate memory |
1005 | /// assert_eq!(map.capacity(), 0); |
1006 | /// |
1007 | /// map.reserve(10); |
1008 | /// |
1009 | /// // And now map can hold at least 10 elements |
1010 | /// assert!(map.capacity() >= 10); |
1011 | /// ``` |
1012 | #[cfg_attr (feature = "inline-more" , inline)] |
1013 | pub fn reserve(&mut self, additional: usize) { |
1014 | self.table |
1015 | .reserve(additional, make_hasher::<K, _, V, S>(&self.hash_builder)); |
1016 | } |
1017 | |
1018 | /// Tries to reserve capacity for at least `additional` more elements to be inserted |
1019 | /// in the given `HashMap<K,V>`. The collection may reserve more space to avoid |
1020 | /// frequent reallocations. |
1021 | /// |
1022 | /// # Errors |
1023 | /// |
1024 | /// If the capacity overflows, or the allocator reports a failure, then an error |
1025 | /// is returned. |
1026 | /// |
1027 | /// # Examples |
1028 | /// |
1029 | /// ``` |
1030 | /// use hashbrown::HashMap; |
1031 | /// |
1032 | /// let mut map: HashMap<&str, isize> = HashMap::new(); |
1033 | /// // Map is empty and doesn't allocate memory |
1034 | /// assert_eq!(map.capacity(), 0); |
1035 | /// |
1036 | /// map.try_reserve(10).expect("why is the test harness OOMing on 10 bytes?" ); |
1037 | /// |
1038 | /// // And now map can hold at least 10 elements |
1039 | /// assert!(map.capacity() >= 10); |
1040 | /// ``` |
1041 | /// If the capacity overflows, or the allocator reports a failure, then an error |
1042 | /// is returned: |
1043 | /// ``` |
1044 | /// # fn test() { |
1045 | /// use hashbrown::HashMap; |
1046 | /// use hashbrown::TryReserveError; |
1047 | /// let mut map: HashMap<i32, i32> = HashMap::new(); |
1048 | /// |
1049 | /// match map.try_reserve(usize::MAX) { |
1050 | /// Err(error) => match error { |
1051 | /// TryReserveError::CapacityOverflow => {} |
1052 | /// _ => panic!("TryReserveError::AllocError ?" ), |
1053 | /// }, |
1054 | /// _ => panic!(), |
1055 | /// } |
1056 | /// # } |
1057 | /// # fn main() { |
1058 | /// # #[cfg (not(miri))] |
1059 | /// # test() |
1060 | /// # } |
1061 | /// ``` |
1062 | #[cfg_attr (feature = "inline-more" , inline)] |
1063 | pub fn try_reserve(&mut self, additional: usize) -> Result<(), TryReserveError> { |
1064 | self.table |
1065 | .try_reserve(additional, make_hasher::<K, _, V, S>(&self.hash_builder)) |
1066 | } |
1067 | |
1068 | /// Shrinks the capacity of the map as much as possible. It will drop |
1069 | /// down as much as possible while maintaining the internal rules |
1070 | /// and possibly leaving some space in accordance with the resize policy. |
1071 | /// |
1072 | /// # Examples |
1073 | /// |
1074 | /// ``` |
1075 | /// use hashbrown::HashMap; |
1076 | /// |
1077 | /// let mut map: HashMap<i32, i32> = HashMap::with_capacity(100); |
1078 | /// map.insert(1, 2); |
1079 | /// map.insert(3, 4); |
1080 | /// assert!(map.capacity() >= 100); |
1081 | /// map.shrink_to_fit(); |
1082 | /// assert!(map.capacity() >= 2); |
1083 | /// ``` |
1084 | #[cfg_attr (feature = "inline-more" , inline)] |
1085 | pub fn shrink_to_fit(&mut self) { |
1086 | self.table |
1087 | .shrink_to(0, make_hasher::<K, _, V, S>(&self.hash_builder)); |
1088 | } |
1089 | |
1090 | /// Shrinks the capacity of the map with a lower limit. It will drop |
1091 | /// down no lower than the supplied limit while maintaining the internal rules |
1092 | /// and possibly leaving some space in accordance with the resize policy. |
1093 | /// |
1094 | /// This function does nothing if the current capacity is smaller than the |
1095 | /// supplied minimum capacity. |
1096 | /// |
1097 | /// # Examples |
1098 | /// |
1099 | /// ``` |
1100 | /// use hashbrown::HashMap; |
1101 | /// |
1102 | /// let mut map: HashMap<i32, i32> = HashMap::with_capacity(100); |
1103 | /// map.insert(1, 2); |
1104 | /// map.insert(3, 4); |
1105 | /// assert!(map.capacity() >= 100); |
1106 | /// map.shrink_to(10); |
1107 | /// assert!(map.capacity() >= 10); |
1108 | /// map.shrink_to(0); |
1109 | /// assert!(map.capacity() >= 2); |
1110 | /// map.shrink_to(10); |
1111 | /// assert!(map.capacity() >= 2); |
1112 | /// ``` |
1113 | #[cfg_attr (feature = "inline-more" , inline)] |
1114 | pub fn shrink_to(&mut self, min_capacity: usize) { |
1115 | self.table |
1116 | .shrink_to(min_capacity, make_hasher::<K, _, V, S>(&self.hash_builder)); |
1117 | } |
1118 | |
1119 | /// Gets the given key's corresponding entry in the map for in-place manipulation. |
1120 | /// |
1121 | /// # Examples |
1122 | /// |
1123 | /// ``` |
1124 | /// use hashbrown::HashMap; |
1125 | /// |
1126 | /// let mut letters = HashMap::new(); |
1127 | /// |
1128 | /// for ch in "a short treatise on fungi" .chars() { |
1129 | /// let counter = letters.entry(ch).or_insert(0); |
1130 | /// *counter += 1; |
1131 | /// } |
1132 | /// |
1133 | /// assert_eq!(letters[&'s' ], 2); |
1134 | /// assert_eq!(letters[&'t' ], 3); |
1135 | /// assert_eq!(letters[&'u' ], 1); |
1136 | /// assert_eq!(letters.get(&'y' ), None); |
1137 | /// ``` |
1138 | #[cfg_attr (feature = "inline-more" , inline)] |
1139 | pub fn entry(&mut self, key: K) -> Entry<'_, K, V, S, A> { |
1140 | let hash = make_insert_hash::<K, S>(&self.hash_builder, &key); |
1141 | if let Some(elem) = self.table.find(hash, equivalent_key(&key)) { |
1142 | Entry::Occupied(OccupiedEntry { |
1143 | hash, |
1144 | key: Some(key), |
1145 | elem, |
1146 | table: self, |
1147 | }) |
1148 | } else { |
1149 | Entry::Vacant(VacantEntry { |
1150 | hash, |
1151 | key, |
1152 | table: self, |
1153 | }) |
1154 | } |
1155 | } |
1156 | |
1157 | /// Gets the given key's corresponding entry by reference in the map for in-place manipulation. |
1158 | /// |
1159 | /// # Examples |
1160 | /// |
1161 | /// ``` |
1162 | /// use hashbrown::HashMap; |
1163 | /// |
1164 | /// let mut words: HashMap<String, usize> = HashMap::new(); |
1165 | /// let source = ["poneyland" , "horseyland" , "poneyland" , "poneyland" ]; |
1166 | /// for (i, &s) in source.iter().enumerate() { |
1167 | /// let counter = words.entry_ref(s).or_insert(0); |
1168 | /// *counter += 1; |
1169 | /// } |
1170 | /// |
1171 | /// assert_eq!(words["poneyland" ], 3); |
1172 | /// assert_eq!(words["horseyland" ], 1); |
1173 | /// ``` |
1174 | #[cfg_attr (feature = "inline-more" , inline)] |
1175 | pub fn entry_ref<'a, 'b, Q: ?Sized>(&'a mut self, key: &'b Q) -> EntryRef<'a, 'b, K, Q, V, S, A> |
1176 | where |
1177 | K: Borrow<Q>, |
1178 | Q: Hash + Eq, |
1179 | { |
1180 | let hash = make_hash::<K, Q, S>(&self.hash_builder, key); |
1181 | if let Some(elem) = self.table.find(hash, equivalent_key(key)) { |
1182 | EntryRef::Occupied(OccupiedEntryRef { |
1183 | hash, |
1184 | key: Some(KeyOrRef::Borrowed(key)), |
1185 | elem, |
1186 | table: self, |
1187 | }) |
1188 | } else { |
1189 | EntryRef::Vacant(VacantEntryRef { |
1190 | hash, |
1191 | key: KeyOrRef::Borrowed(key), |
1192 | table: self, |
1193 | }) |
1194 | } |
1195 | } |
1196 | |
1197 | /// Returns a reference to the value corresponding to the key. |
1198 | /// |
1199 | /// The key may be any borrowed form of the map's key type, but |
1200 | /// [`Hash`] and [`Eq`] on the borrowed form *must* match those for |
1201 | /// the key type. |
1202 | /// |
1203 | /// [`Eq`]: https://doc.rust-lang.org/std/cmp/trait.Eq.html |
1204 | /// [`Hash`]: https://doc.rust-lang.org/std/hash/trait.Hash.html |
1205 | /// |
1206 | /// # Examples |
1207 | /// |
1208 | /// ``` |
1209 | /// use hashbrown::HashMap; |
1210 | /// |
1211 | /// let mut map = HashMap::new(); |
1212 | /// map.insert(1, "a" ); |
1213 | /// assert_eq!(map.get(&1), Some(&"a" )); |
1214 | /// assert_eq!(map.get(&2), None); |
1215 | /// ``` |
1216 | #[inline ] |
1217 | pub fn get<Q: ?Sized>(&self, k: &Q) -> Option<&V> |
1218 | where |
1219 | K: Borrow<Q>, |
1220 | Q: Hash + Eq, |
1221 | { |
1222 | // Avoid `Option::map` because it bloats LLVM IR. |
1223 | match self.get_inner(k) { |
1224 | Some(&(_, ref v)) => Some(v), |
1225 | None => None, |
1226 | } |
1227 | } |
1228 | |
1229 | /// Returns the key-value pair corresponding to the supplied key. |
1230 | /// |
1231 | /// The supplied key may be any borrowed form of the map's key type, but |
1232 | /// [`Hash`] and [`Eq`] on the borrowed form *must* match those for |
1233 | /// the key type. |
1234 | /// |
1235 | /// [`Eq`]: https://doc.rust-lang.org/std/cmp/trait.Eq.html |
1236 | /// [`Hash`]: https://doc.rust-lang.org/std/hash/trait.Hash.html |
1237 | /// |
1238 | /// # Examples |
1239 | /// |
1240 | /// ``` |
1241 | /// use hashbrown::HashMap; |
1242 | /// |
1243 | /// let mut map = HashMap::new(); |
1244 | /// map.insert(1, "a" ); |
1245 | /// assert_eq!(map.get_key_value(&1), Some((&1, &"a" ))); |
1246 | /// assert_eq!(map.get_key_value(&2), None); |
1247 | /// ``` |
1248 | #[inline ] |
1249 | pub fn get_key_value<Q: ?Sized>(&self, k: &Q) -> Option<(&K, &V)> |
1250 | where |
1251 | K: Borrow<Q>, |
1252 | Q: Hash + Eq, |
1253 | { |
1254 | // Avoid `Option::map` because it bloats LLVM IR. |
1255 | match self.get_inner(k) { |
1256 | Some(&(ref key, ref value)) => Some((key, value)), |
1257 | None => None, |
1258 | } |
1259 | } |
1260 | |
1261 | #[inline ] |
1262 | fn get_inner<Q: ?Sized>(&self, k: &Q) -> Option<&(K, V)> |
1263 | where |
1264 | K: Borrow<Q>, |
1265 | Q: Hash + Eq, |
1266 | { |
1267 | if self.table.is_empty() { |
1268 | None |
1269 | } else { |
1270 | let hash = make_hash::<K, Q, S>(&self.hash_builder, k); |
1271 | self.table.get(hash, equivalent_key(k)) |
1272 | } |
1273 | } |
1274 | |
1275 | /// Returns the key-value pair corresponding to the supplied key, with a mutable reference to value. |
1276 | /// |
1277 | /// The supplied key may be any borrowed form of the map's key type, but |
1278 | /// [`Hash`] and [`Eq`] on the borrowed form *must* match those for |
1279 | /// the key type. |
1280 | /// |
1281 | /// [`Eq`]: https://doc.rust-lang.org/std/cmp/trait.Eq.html |
1282 | /// [`Hash`]: https://doc.rust-lang.org/std/hash/trait.Hash.html |
1283 | /// |
1284 | /// # Examples |
1285 | /// |
1286 | /// ``` |
1287 | /// use hashbrown::HashMap; |
1288 | /// |
1289 | /// let mut map = HashMap::new(); |
1290 | /// map.insert(1, "a" ); |
1291 | /// let (k, v) = map.get_key_value_mut(&1).unwrap(); |
1292 | /// assert_eq!(k, &1); |
1293 | /// assert_eq!(v, &mut "a" ); |
1294 | /// *v = "b" ; |
1295 | /// assert_eq!(map.get_key_value_mut(&1), Some((&1, &mut "b" ))); |
1296 | /// assert_eq!(map.get_key_value_mut(&2), None); |
1297 | /// ``` |
1298 | #[inline ] |
1299 | pub fn get_key_value_mut<Q: ?Sized>(&mut self, k: &Q) -> Option<(&K, &mut V)> |
1300 | where |
1301 | K: Borrow<Q>, |
1302 | Q: Hash + Eq, |
1303 | { |
1304 | // Avoid `Option::map` because it bloats LLVM IR. |
1305 | match self.get_inner_mut(k) { |
1306 | Some(&mut (ref key, ref mut value)) => Some((key, value)), |
1307 | None => None, |
1308 | } |
1309 | } |
1310 | |
1311 | /// Returns `true` if the map contains a value for the specified key. |
1312 | /// |
1313 | /// The key may be any borrowed form of the map's key type, but |
1314 | /// [`Hash`] and [`Eq`] on the borrowed form *must* match those for |
1315 | /// the key type. |
1316 | /// |
1317 | /// [`Eq`]: https://doc.rust-lang.org/std/cmp/trait.Eq.html |
1318 | /// [`Hash`]: https://doc.rust-lang.org/std/hash/trait.Hash.html |
1319 | /// |
1320 | /// # Examples |
1321 | /// |
1322 | /// ``` |
1323 | /// use hashbrown::HashMap; |
1324 | /// |
1325 | /// let mut map = HashMap::new(); |
1326 | /// map.insert(1, "a" ); |
1327 | /// assert_eq!(map.contains_key(&1), true); |
1328 | /// assert_eq!(map.contains_key(&2), false); |
1329 | /// ``` |
1330 | #[cfg_attr (feature = "inline-more" , inline)] |
1331 | pub fn contains_key<Q: ?Sized>(&self, k: &Q) -> bool |
1332 | where |
1333 | K: Borrow<Q>, |
1334 | Q: Hash + Eq, |
1335 | { |
1336 | self.get_inner(k).is_some() |
1337 | } |
1338 | |
1339 | /// Returns a mutable reference to the value corresponding to the key. |
1340 | /// |
1341 | /// The key may be any borrowed form of the map's key type, but |
1342 | /// [`Hash`] and [`Eq`] on the borrowed form *must* match those for |
1343 | /// the key type. |
1344 | /// |
1345 | /// [`Eq`]: https://doc.rust-lang.org/std/cmp/trait.Eq.html |
1346 | /// [`Hash`]: https://doc.rust-lang.org/std/hash/trait.Hash.html |
1347 | /// |
1348 | /// # Examples |
1349 | /// |
1350 | /// ``` |
1351 | /// use hashbrown::HashMap; |
1352 | /// |
1353 | /// let mut map = HashMap::new(); |
1354 | /// map.insert(1, "a" ); |
1355 | /// if let Some(x) = map.get_mut(&1) { |
1356 | /// *x = "b" ; |
1357 | /// } |
1358 | /// assert_eq!(map[&1], "b" ); |
1359 | /// |
1360 | /// assert_eq!(map.get_mut(&2), None); |
1361 | /// ``` |
1362 | #[cfg_attr (feature = "inline-more" , inline)] |
1363 | pub fn get_mut<Q: ?Sized>(&mut self, k: &Q) -> Option<&mut V> |
1364 | where |
1365 | K: Borrow<Q>, |
1366 | Q: Hash + Eq, |
1367 | { |
1368 | // Avoid `Option::map` because it bloats LLVM IR. |
1369 | match self.get_inner_mut(k) { |
1370 | Some(&mut (_, ref mut v)) => Some(v), |
1371 | None => None, |
1372 | } |
1373 | } |
1374 | |
1375 | #[inline ] |
1376 | fn get_inner_mut<Q: ?Sized>(&mut self, k: &Q) -> Option<&mut (K, V)> |
1377 | where |
1378 | K: Borrow<Q>, |
1379 | Q: Hash + Eq, |
1380 | { |
1381 | if self.table.is_empty() { |
1382 | None |
1383 | } else { |
1384 | let hash = make_hash::<K, Q, S>(&self.hash_builder, k); |
1385 | self.table.get_mut(hash, equivalent_key(k)) |
1386 | } |
1387 | } |
1388 | |
1389 | /// Attempts to get mutable references to `N` values in the map at once. |
1390 | /// |
1391 | /// Returns an array of length `N` with the results of each query. For soundness, at most one |
1392 | /// mutable reference will be returned to any value. `None` will be returned if any of the |
1393 | /// keys are duplicates or missing. |
1394 | /// |
1395 | /// # Examples |
1396 | /// |
1397 | /// ``` |
1398 | /// use hashbrown::HashMap; |
1399 | /// |
1400 | /// let mut libraries = HashMap::new(); |
1401 | /// libraries.insert("Bodleian Library" .to_string(), 1602); |
1402 | /// libraries.insert("Athenæum" .to_string(), 1807); |
1403 | /// libraries.insert("Herzogin-Anna-Amalia-Bibliothek" .to_string(), 1691); |
1404 | /// libraries.insert("Library of Congress" .to_string(), 1800); |
1405 | /// |
1406 | /// let got = libraries.get_many_mut([ |
1407 | /// "Athenæum" , |
1408 | /// "Library of Congress" , |
1409 | /// ]); |
1410 | /// assert_eq!( |
1411 | /// got, |
1412 | /// Some([ |
1413 | /// &mut 1807, |
1414 | /// &mut 1800, |
1415 | /// ]), |
1416 | /// ); |
1417 | /// |
1418 | /// // Missing keys result in None |
1419 | /// let got = libraries.get_many_mut([ |
1420 | /// "Athenæum" , |
1421 | /// "New York Public Library" , |
1422 | /// ]); |
1423 | /// assert_eq!(got, None); |
1424 | /// |
1425 | /// // Duplicate keys result in None |
1426 | /// let got = libraries.get_many_mut([ |
1427 | /// "Athenæum" , |
1428 | /// "Athenæum" , |
1429 | /// ]); |
1430 | /// assert_eq!(got, None); |
1431 | /// ``` |
1432 | pub fn get_many_mut<Q: ?Sized, const N: usize>(&mut self, ks: [&Q; N]) -> Option<[&'_ mut V; N]> |
1433 | where |
1434 | K: Borrow<Q>, |
1435 | Q: Hash + Eq, |
1436 | { |
1437 | self.get_many_mut_inner(ks).map(|res| res.map(|(_, v)| v)) |
1438 | } |
1439 | |
1440 | /// Attempts to get mutable references to `N` values in the map at once, without validating that |
1441 | /// the values are unique. |
1442 | /// |
1443 | /// Returns an array of length `N` with the results of each query. `None` will be returned if |
1444 | /// any of the keys are missing. |
1445 | /// |
1446 | /// For a safe alternative see [`get_many_mut`](`HashMap::get_many_mut`). |
1447 | /// |
1448 | /// # Safety |
1449 | /// |
1450 | /// Calling this method with overlapping keys is *[undefined behavior]* even if the resulting |
1451 | /// references are not used. |
1452 | /// |
1453 | /// [undefined behavior]: https://doc.rust-lang.org/reference/behavior-considered-undefined.html |
1454 | /// |
1455 | /// # Examples |
1456 | /// |
1457 | /// ``` |
1458 | /// use hashbrown::HashMap; |
1459 | /// |
1460 | /// let mut libraries = HashMap::new(); |
1461 | /// libraries.insert("Bodleian Library" .to_string(), 1602); |
1462 | /// libraries.insert("Athenæum" .to_string(), 1807); |
1463 | /// libraries.insert("Herzogin-Anna-Amalia-Bibliothek" .to_string(), 1691); |
1464 | /// libraries.insert("Library of Congress" .to_string(), 1800); |
1465 | /// |
1466 | /// let got = libraries.get_many_mut([ |
1467 | /// "Athenæum" , |
1468 | /// "Library of Congress" , |
1469 | /// ]); |
1470 | /// assert_eq!( |
1471 | /// got, |
1472 | /// Some([ |
1473 | /// &mut 1807, |
1474 | /// &mut 1800, |
1475 | /// ]), |
1476 | /// ); |
1477 | /// |
1478 | /// // Missing keys result in None |
1479 | /// let got = libraries.get_many_mut([ |
1480 | /// "Athenæum" , |
1481 | /// "New York Public Library" , |
1482 | /// ]); |
1483 | /// assert_eq!(got, None); |
1484 | /// ``` |
1485 | pub unsafe fn get_many_unchecked_mut<Q: ?Sized, const N: usize>( |
1486 | &mut self, |
1487 | ks: [&Q; N], |
1488 | ) -> Option<[&'_ mut V; N]> |
1489 | where |
1490 | K: Borrow<Q>, |
1491 | Q: Hash + Eq, |
1492 | { |
1493 | self.get_many_unchecked_mut_inner(ks) |
1494 | .map(|res| res.map(|(_, v)| v)) |
1495 | } |
1496 | |
1497 | /// Attempts to get mutable references to `N` values in the map at once, with immutable |
1498 | /// references to the corresponding keys. |
1499 | /// |
1500 | /// Returns an array of length `N` with the results of each query. For soundness, at most one |
1501 | /// mutable reference will be returned to any value. `None` will be returned if any of the keys |
1502 | /// are duplicates or missing. |
1503 | /// |
1504 | /// # Examples |
1505 | /// |
1506 | /// ``` |
1507 | /// use hashbrown::HashMap; |
1508 | /// |
1509 | /// let mut libraries = HashMap::new(); |
1510 | /// libraries.insert("Bodleian Library" .to_string(), 1602); |
1511 | /// libraries.insert("Athenæum" .to_string(), 1807); |
1512 | /// libraries.insert("Herzogin-Anna-Amalia-Bibliothek" .to_string(), 1691); |
1513 | /// libraries.insert("Library of Congress" .to_string(), 1800); |
1514 | /// |
1515 | /// let got = libraries.get_many_key_value_mut([ |
1516 | /// "Bodleian Library" , |
1517 | /// "Herzogin-Anna-Amalia-Bibliothek" , |
1518 | /// ]); |
1519 | /// assert_eq!( |
1520 | /// got, |
1521 | /// Some([ |
1522 | /// (&"Bodleian Library" .to_string(), &mut 1602), |
1523 | /// (&"Herzogin-Anna-Amalia-Bibliothek" .to_string(), &mut 1691), |
1524 | /// ]), |
1525 | /// ); |
1526 | /// // Missing keys result in None |
1527 | /// let got = libraries.get_many_key_value_mut([ |
1528 | /// "Bodleian Library" , |
1529 | /// "Gewandhaus" , |
1530 | /// ]); |
1531 | /// assert_eq!(got, None); |
1532 | /// |
1533 | /// // Duplicate keys result in None |
1534 | /// let got = libraries.get_many_key_value_mut([ |
1535 | /// "Bodleian Library" , |
1536 | /// "Herzogin-Anna-Amalia-Bibliothek" , |
1537 | /// "Herzogin-Anna-Amalia-Bibliothek" , |
1538 | /// ]); |
1539 | /// assert_eq!(got, None); |
1540 | /// ``` |
1541 | pub fn get_many_key_value_mut<Q: ?Sized, const N: usize>( |
1542 | &mut self, |
1543 | ks: [&Q; N], |
1544 | ) -> Option<[(&'_ K, &'_ mut V); N]> |
1545 | where |
1546 | K: Borrow<Q>, |
1547 | Q: Hash + Eq, |
1548 | { |
1549 | self.get_many_mut_inner(ks) |
1550 | .map(|res| res.map(|(k, v)| (&*k, v))) |
1551 | } |
1552 | |
1553 | /// Attempts to get mutable references to `N` values in the map at once, with immutable |
1554 | /// references to the corresponding keys, without validating that the values are unique. |
1555 | /// |
1556 | /// Returns an array of length `N` with the results of each query. `None` will be returned if |
1557 | /// any of the keys are missing. |
1558 | /// |
1559 | /// For a safe alternative see [`get_many_key_value_mut`](`HashMap::get_many_key_value_mut`). |
1560 | /// |
1561 | /// # Safety |
1562 | /// |
1563 | /// Calling this method with overlapping keys is *[undefined behavior]* even if the resulting |
1564 | /// references are not used. |
1565 | /// |
1566 | /// [undefined behavior]: https://doc.rust-lang.org/reference/behavior-considered-undefined.html |
1567 | /// |
1568 | /// # Examples |
1569 | /// |
1570 | /// ``` |
1571 | /// use hashbrown::HashMap; |
1572 | /// |
1573 | /// let mut libraries = HashMap::new(); |
1574 | /// libraries.insert("Bodleian Library" .to_string(), 1602); |
1575 | /// libraries.insert("Athenæum" .to_string(), 1807); |
1576 | /// libraries.insert("Herzogin-Anna-Amalia-Bibliothek" .to_string(), 1691); |
1577 | /// libraries.insert("Library of Congress" .to_string(), 1800); |
1578 | /// |
1579 | /// let got = libraries.get_many_key_value_mut([ |
1580 | /// "Bodleian Library" , |
1581 | /// "Herzogin-Anna-Amalia-Bibliothek" , |
1582 | /// ]); |
1583 | /// assert_eq!( |
1584 | /// got, |
1585 | /// Some([ |
1586 | /// (&"Bodleian Library" .to_string(), &mut 1602), |
1587 | /// (&"Herzogin-Anna-Amalia-Bibliothek" .to_string(), &mut 1691), |
1588 | /// ]), |
1589 | /// ); |
1590 | /// // Missing keys result in None |
1591 | /// let got = libraries.get_many_key_value_mut([ |
1592 | /// "Bodleian Library" , |
1593 | /// "Gewandhaus" , |
1594 | /// ]); |
1595 | /// assert_eq!(got, None); |
1596 | /// ``` |
1597 | pub unsafe fn get_many_key_value_unchecked_mut<Q: ?Sized, const N: usize>( |
1598 | &mut self, |
1599 | ks: [&Q; N], |
1600 | ) -> Option<[(&'_ K, &'_ mut V); N]> |
1601 | where |
1602 | K: Borrow<Q>, |
1603 | Q: Hash + Eq, |
1604 | { |
1605 | self.get_many_unchecked_mut_inner(ks) |
1606 | .map(|res| res.map(|(k, v)| (&*k, v))) |
1607 | } |
1608 | |
1609 | fn get_many_mut_inner<Q: ?Sized, const N: usize>( |
1610 | &mut self, |
1611 | ks: [&Q; N], |
1612 | ) -> Option<[&'_ mut (K, V); N]> |
1613 | where |
1614 | K: Borrow<Q>, |
1615 | Q: Hash + Eq, |
1616 | { |
1617 | let hashes = self.build_hashes_inner(ks); |
1618 | self.table |
1619 | .get_many_mut(hashes, |i, (k, _)| ks[i].eq(k.borrow())) |
1620 | } |
1621 | |
1622 | unsafe fn get_many_unchecked_mut_inner<Q: ?Sized, const N: usize>( |
1623 | &mut self, |
1624 | ks: [&Q; N], |
1625 | ) -> Option<[&'_ mut (K, V); N]> |
1626 | where |
1627 | K: Borrow<Q>, |
1628 | Q: Hash + Eq, |
1629 | { |
1630 | let hashes = self.build_hashes_inner(ks); |
1631 | self.table |
1632 | .get_many_unchecked_mut(hashes, |i, (k, _)| ks[i].eq(k.borrow())) |
1633 | } |
1634 | |
1635 | fn build_hashes_inner<Q: ?Sized, const N: usize>(&self, ks: [&Q; N]) -> [u64; N] |
1636 | where |
1637 | K: Borrow<Q>, |
1638 | Q: Hash + Eq, |
1639 | { |
1640 | let mut hashes = [0_u64; N]; |
1641 | for i in 0..N { |
1642 | hashes[i] = make_hash::<K, Q, S>(&self.hash_builder, ks[i]); |
1643 | } |
1644 | hashes |
1645 | } |
1646 | |
1647 | /// Inserts a key-value pair into the map. |
1648 | /// |
1649 | /// If the map did not have this key present, [`None`] is returned. |
1650 | /// |
1651 | /// If the map did have this key present, the value is updated, and the old |
1652 | /// value is returned. The key is not updated, though; this matters for |
1653 | /// types that can be `==` without being identical. See the [`std::collections`] |
1654 | /// [module-level documentation] for more. |
1655 | /// |
1656 | /// [`None`]: https://doc.rust-lang.org/std/option/enum.Option.html#variant.None |
1657 | /// [`std::collections`]: https://doc.rust-lang.org/std/collections/index.html |
1658 | /// [module-level documentation]: https://doc.rust-lang.org/std/collections/index.html#insert-and-complex-keys |
1659 | /// |
1660 | /// # Examples |
1661 | /// |
1662 | /// ``` |
1663 | /// use hashbrown::HashMap; |
1664 | /// |
1665 | /// let mut map = HashMap::new(); |
1666 | /// assert_eq!(map.insert(37, "a" ), None); |
1667 | /// assert_eq!(map.is_empty(), false); |
1668 | /// |
1669 | /// map.insert(37, "b" ); |
1670 | /// assert_eq!(map.insert(37, "c" ), Some("b" )); |
1671 | /// assert_eq!(map[&37], "c" ); |
1672 | /// ``` |
1673 | #[cfg_attr (feature = "inline-more" , inline)] |
1674 | pub fn insert(&mut self, k: K, v: V) -> Option<V> { |
1675 | let hash = make_insert_hash::<K, S>(&self.hash_builder, &k); |
1676 | if let Some((_, item)) = self.table.get_mut(hash, equivalent_key(&k)) { |
1677 | Some(mem::replace(item, v)) |
1678 | } else { |
1679 | self.table |
1680 | .insert(hash, (k, v), make_hasher::<K, _, V, S>(&self.hash_builder)); |
1681 | None |
1682 | } |
1683 | } |
1684 | |
1685 | /// Insert a key-value pair into the map without checking |
1686 | /// if the key already exists in the map. |
1687 | /// |
1688 | /// Returns a reference to the key and value just inserted. |
1689 | /// |
1690 | /// This operation is safe if a key does not exist in the map. |
1691 | /// |
1692 | /// However, if a key exists in the map already, the behavior is unspecified: |
1693 | /// this operation may panic, loop forever, or any following operation with the map |
1694 | /// may panic, loop forever or return arbitrary result. |
1695 | /// |
1696 | /// That said, this operation (and following operations) are guaranteed to |
1697 | /// not violate memory safety. |
1698 | /// |
1699 | /// This operation is faster than regular insert, because it does not perform |
1700 | /// lookup before insertion. |
1701 | /// |
1702 | /// This operation is useful during initial population of the map. |
1703 | /// For example, when constructing a map from another map, we know |
1704 | /// that keys are unique. |
1705 | /// |
1706 | /// # Examples |
1707 | /// |
1708 | /// ``` |
1709 | /// use hashbrown::HashMap; |
1710 | /// |
1711 | /// let mut map1 = HashMap::new(); |
1712 | /// assert_eq!(map1.insert(1, "a" ), None); |
1713 | /// assert_eq!(map1.insert(2, "b" ), None); |
1714 | /// assert_eq!(map1.insert(3, "c" ), None); |
1715 | /// assert_eq!(map1.len(), 3); |
1716 | /// |
1717 | /// let mut map2 = HashMap::new(); |
1718 | /// |
1719 | /// for (key, value) in map1.into_iter() { |
1720 | /// map2.insert_unique_unchecked(key, value); |
1721 | /// } |
1722 | /// |
1723 | /// let (key, value) = map2.insert_unique_unchecked(4, "d" ); |
1724 | /// assert_eq!(key, &4); |
1725 | /// assert_eq!(value, &mut "d" ); |
1726 | /// *value = "e" ; |
1727 | /// |
1728 | /// assert_eq!(map2[&1], "a" ); |
1729 | /// assert_eq!(map2[&2], "b" ); |
1730 | /// assert_eq!(map2[&3], "c" ); |
1731 | /// assert_eq!(map2[&4], "e" ); |
1732 | /// assert_eq!(map2.len(), 4); |
1733 | /// ``` |
1734 | #[cfg_attr (feature = "inline-more" , inline)] |
1735 | pub fn insert_unique_unchecked(&mut self, k: K, v: V) -> (&K, &mut V) { |
1736 | let hash = make_insert_hash::<K, S>(&self.hash_builder, &k); |
1737 | let bucket = self |
1738 | .table |
1739 | .insert(hash, (k, v), make_hasher::<K, _, V, S>(&self.hash_builder)); |
1740 | let (k_ref, v_ref) = unsafe { bucket.as_mut() }; |
1741 | (k_ref, v_ref) |
1742 | } |
1743 | |
1744 | /// Tries to insert a key-value pair into the map, and returns |
1745 | /// a mutable reference to the value in the entry. |
1746 | /// |
1747 | /// # Errors |
1748 | /// |
1749 | /// If the map already had this key present, nothing is updated, and |
1750 | /// an error containing the occupied entry and the value is returned. |
1751 | /// |
1752 | /// # Examples |
1753 | /// |
1754 | /// Basic usage: |
1755 | /// |
1756 | /// ``` |
1757 | /// use hashbrown::HashMap; |
1758 | /// use hashbrown::hash_map::OccupiedError; |
1759 | /// |
1760 | /// let mut map = HashMap::new(); |
1761 | /// assert_eq!(map.try_insert(37, "a" ).unwrap(), &"a" ); |
1762 | /// |
1763 | /// match map.try_insert(37, "b" ) { |
1764 | /// Err(OccupiedError { entry, value }) => { |
1765 | /// assert_eq!(entry.key(), &37); |
1766 | /// assert_eq!(entry.get(), &"a" ); |
1767 | /// assert_eq!(value, "b" ); |
1768 | /// } |
1769 | /// _ => panic!() |
1770 | /// } |
1771 | /// ``` |
1772 | #[cfg_attr (feature = "inline-more" , inline)] |
1773 | pub fn try_insert( |
1774 | &mut self, |
1775 | key: K, |
1776 | value: V, |
1777 | ) -> Result<&mut V, OccupiedError<'_, K, V, S, A>> { |
1778 | match self.entry(key) { |
1779 | Entry::Occupied(entry) => Err(OccupiedError { entry, value }), |
1780 | Entry::Vacant(entry) => Ok(entry.insert(value)), |
1781 | } |
1782 | } |
1783 | |
1784 | /// Removes a key from the map, returning the value at the key if the key |
1785 | /// was previously in the map. Keeps the allocated memory for reuse. |
1786 | /// |
1787 | /// The key may be any borrowed form of the map's key type, but |
1788 | /// [`Hash`] and [`Eq`] on the borrowed form *must* match those for |
1789 | /// the key type. |
1790 | /// |
1791 | /// [`Eq`]: https://doc.rust-lang.org/std/cmp/trait.Eq.html |
1792 | /// [`Hash`]: https://doc.rust-lang.org/std/hash/trait.Hash.html |
1793 | /// |
1794 | /// # Examples |
1795 | /// |
1796 | /// ``` |
1797 | /// use hashbrown::HashMap; |
1798 | /// |
1799 | /// let mut map = HashMap::new(); |
1800 | /// // The map is empty |
1801 | /// assert!(map.is_empty() && map.capacity() == 0); |
1802 | /// |
1803 | /// map.insert(1, "a" ); |
1804 | /// let capacity_before_remove = map.capacity(); |
1805 | /// |
1806 | /// assert_eq!(map.remove(&1), Some("a" )); |
1807 | /// assert_eq!(map.remove(&1), None); |
1808 | /// |
1809 | /// // Now map holds none elements but capacity is equal to the old one |
1810 | /// assert!(map.len() == 0 && map.capacity() == capacity_before_remove); |
1811 | /// ``` |
1812 | #[cfg_attr (feature = "inline-more" , inline)] |
1813 | pub fn remove<Q: ?Sized>(&mut self, k: &Q) -> Option<V> |
1814 | where |
1815 | K: Borrow<Q>, |
1816 | Q: Hash + Eq, |
1817 | { |
1818 | // Avoid `Option::map` because it bloats LLVM IR. |
1819 | match self.remove_entry(k) { |
1820 | Some((_, v)) => Some(v), |
1821 | None => None, |
1822 | } |
1823 | } |
1824 | |
1825 | /// Removes a key from the map, returning the stored key and value if the |
1826 | /// key was previously in the map. Keeps the allocated memory for reuse. |
1827 | /// |
1828 | /// The key may be any borrowed form of the map's key type, but |
1829 | /// [`Hash`] and [`Eq`] on the borrowed form *must* match those for |
1830 | /// the key type. |
1831 | /// |
1832 | /// [`Eq`]: https://doc.rust-lang.org/std/cmp/trait.Eq.html |
1833 | /// [`Hash`]: https://doc.rust-lang.org/std/hash/trait.Hash.html |
1834 | /// |
1835 | /// # Examples |
1836 | /// |
1837 | /// ``` |
1838 | /// use hashbrown::HashMap; |
1839 | /// |
1840 | /// let mut map = HashMap::new(); |
1841 | /// // The map is empty |
1842 | /// assert!(map.is_empty() && map.capacity() == 0); |
1843 | /// |
1844 | /// map.insert(1, "a" ); |
1845 | /// let capacity_before_remove = map.capacity(); |
1846 | /// |
1847 | /// assert_eq!(map.remove_entry(&1), Some((1, "a" ))); |
1848 | /// assert_eq!(map.remove(&1), None); |
1849 | /// |
1850 | /// // Now map hold none elements but capacity is equal to the old one |
1851 | /// assert!(map.len() == 0 && map.capacity() == capacity_before_remove); |
1852 | /// ``` |
1853 | #[cfg_attr (feature = "inline-more" , inline)] |
1854 | pub fn remove_entry<Q: ?Sized>(&mut self, k: &Q) -> Option<(K, V)> |
1855 | where |
1856 | K: Borrow<Q>, |
1857 | Q: Hash + Eq, |
1858 | { |
1859 | let hash = make_hash::<K, Q, S>(&self.hash_builder, k); |
1860 | self.table.remove_entry(hash, equivalent_key(k)) |
1861 | } |
1862 | } |
1863 | |
1864 | impl<K, V, S, A: Allocator + Clone> HashMap<K, V, S, A> { |
1865 | /// Creates a raw entry builder for the HashMap. |
1866 | /// |
1867 | /// Raw entries provide the lowest level of control for searching and |
1868 | /// manipulating a map. They must be manually initialized with a hash and |
1869 | /// then manually searched. After this, insertions into a vacant entry |
1870 | /// still require an owned key to be provided. |
1871 | /// |
1872 | /// Raw entries are useful for such exotic situations as: |
1873 | /// |
1874 | /// * Hash memoization |
1875 | /// * Deferring the creation of an owned key until it is known to be required |
1876 | /// * Using a search key that doesn't work with the Borrow trait |
1877 | /// * Using custom comparison logic without newtype wrappers |
1878 | /// |
1879 | /// Because raw entries provide much more low-level control, it's much easier |
1880 | /// to put the HashMap into an inconsistent state which, while memory-safe, |
1881 | /// will cause the map to produce seemingly random results. Higher-level and |
1882 | /// more foolproof APIs like `entry` should be preferred when possible. |
1883 | /// |
1884 | /// In particular, the hash used to initialized the raw entry must still be |
1885 | /// consistent with the hash of the key that is ultimately stored in the entry. |
1886 | /// This is because implementations of HashMap may need to recompute hashes |
1887 | /// when resizing, at which point only the keys are available. |
1888 | /// |
1889 | /// Raw entries give mutable access to the keys. This must not be used |
1890 | /// to modify how the key would compare or hash, as the map will not re-evaluate |
1891 | /// where the key should go, meaning the keys may become "lost" if their |
1892 | /// location does not reflect their state. For instance, if you change a key |
1893 | /// so that the map now contains keys which compare equal, search may start |
1894 | /// acting erratically, with two keys randomly masking each other. Implementations |
1895 | /// are free to assume this doesn't happen (within the limits of memory-safety). |
1896 | /// |
1897 | /// # Examples |
1898 | /// |
1899 | /// ``` |
1900 | /// use core::hash::{BuildHasher, Hash}; |
1901 | /// use hashbrown::hash_map::{HashMap, RawEntryMut}; |
1902 | /// |
1903 | /// let mut map = HashMap::new(); |
1904 | /// map.extend([("a" , 100), ("b" , 200), ("c" , 300)]); |
1905 | /// |
1906 | /// fn compute_hash<K: Hash + ?Sized, S: BuildHasher>(hash_builder: &S, key: &K) -> u64 { |
1907 | /// use core::hash::Hasher; |
1908 | /// let mut state = hash_builder.build_hasher(); |
1909 | /// key.hash(&mut state); |
1910 | /// state.finish() |
1911 | /// } |
1912 | /// |
1913 | /// // Existing key (insert and update) |
1914 | /// match map.raw_entry_mut().from_key(&"a" ) { |
1915 | /// RawEntryMut::Vacant(_) => unreachable!(), |
1916 | /// RawEntryMut::Occupied(mut view) => { |
1917 | /// assert_eq!(view.get(), &100); |
1918 | /// let v = view.get_mut(); |
1919 | /// let new_v = (*v) * 10; |
1920 | /// *v = new_v; |
1921 | /// assert_eq!(view.insert(1111), 1000); |
1922 | /// } |
1923 | /// } |
1924 | /// |
1925 | /// assert_eq!(map[&"a" ], 1111); |
1926 | /// assert_eq!(map.len(), 3); |
1927 | /// |
1928 | /// // Existing key (take) |
1929 | /// let hash = compute_hash(map.hasher(), &"c" ); |
1930 | /// match map.raw_entry_mut().from_key_hashed_nocheck(hash, &"c" ) { |
1931 | /// RawEntryMut::Vacant(_) => unreachable!(), |
1932 | /// RawEntryMut::Occupied(view) => { |
1933 | /// assert_eq!(view.remove_entry(), ("c" , 300)); |
1934 | /// } |
1935 | /// } |
1936 | /// assert_eq!(map.raw_entry().from_key(&"c" ), None); |
1937 | /// assert_eq!(map.len(), 2); |
1938 | /// |
1939 | /// // Nonexistent key (insert and update) |
1940 | /// let key = "d" ; |
1941 | /// let hash = compute_hash(map.hasher(), &key); |
1942 | /// match map.raw_entry_mut().from_hash(hash, |q| *q == key) { |
1943 | /// RawEntryMut::Occupied(_) => unreachable!(), |
1944 | /// RawEntryMut::Vacant(view) => { |
1945 | /// let (k, value) = view.insert("d" , 4000); |
1946 | /// assert_eq!((*k, *value), ("d" , 4000)); |
1947 | /// *value = 40000; |
1948 | /// } |
1949 | /// } |
1950 | /// assert_eq!(map[&"d" ], 40000); |
1951 | /// assert_eq!(map.len(), 3); |
1952 | /// |
1953 | /// match map.raw_entry_mut().from_hash(hash, |q| *q == key) { |
1954 | /// RawEntryMut::Vacant(_) => unreachable!(), |
1955 | /// RawEntryMut::Occupied(view) => { |
1956 | /// assert_eq!(view.remove_entry(), ("d" , 40000)); |
1957 | /// } |
1958 | /// } |
1959 | /// assert_eq!(map.get(&"d" ), None); |
1960 | /// assert_eq!(map.len(), 2); |
1961 | /// ``` |
1962 | #[cfg_attr (feature = "inline-more" , inline)] |
1963 | pub fn raw_entry_mut(&mut self) -> RawEntryBuilderMut<'_, K, V, S, A> { |
1964 | RawEntryBuilderMut { map: self } |
1965 | } |
1966 | |
1967 | /// Creates a raw immutable entry builder for the HashMap. |
1968 | /// |
1969 | /// Raw entries provide the lowest level of control for searching and |
1970 | /// manipulating a map. They must be manually initialized with a hash and |
1971 | /// then manually searched. |
1972 | /// |
1973 | /// This is useful for |
1974 | /// * Hash memoization |
1975 | /// * Using a search key that doesn't work with the Borrow trait |
1976 | /// * Using custom comparison logic without newtype wrappers |
1977 | /// |
1978 | /// Unless you are in such a situation, higher-level and more foolproof APIs like |
1979 | /// `get` should be preferred. |
1980 | /// |
1981 | /// Immutable raw entries have very limited use; you might instead want `raw_entry_mut`. |
1982 | /// |
1983 | /// # Examples |
1984 | /// |
1985 | /// ``` |
1986 | /// use core::hash::{BuildHasher, Hash}; |
1987 | /// use hashbrown::HashMap; |
1988 | /// |
1989 | /// let mut map = HashMap::new(); |
1990 | /// map.extend([("a" , 100), ("b" , 200), ("c" , 300)]); |
1991 | /// |
1992 | /// fn compute_hash<K: Hash + ?Sized, S: BuildHasher>(hash_builder: &S, key: &K) -> u64 { |
1993 | /// use core::hash::Hasher; |
1994 | /// let mut state = hash_builder.build_hasher(); |
1995 | /// key.hash(&mut state); |
1996 | /// state.finish() |
1997 | /// } |
1998 | /// |
1999 | /// for k in ["a" , "b" , "c" , "d" , "e" , "f" ] { |
2000 | /// let hash = compute_hash(map.hasher(), k); |
2001 | /// let v = map.get(&k).cloned(); |
2002 | /// let kv = v.as_ref().map(|v| (&k, v)); |
2003 | /// |
2004 | /// println!("Key: {} and value: {:?}" , k, v); |
2005 | /// |
2006 | /// assert_eq!(map.raw_entry().from_key(&k), kv); |
2007 | /// assert_eq!(map.raw_entry().from_hash(hash, |q| *q == k), kv); |
2008 | /// assert_eq!(map.raw_entry().from_key_hashed_nocheck(hash, &k), kv); |
2009 | /// } |
2010 | /// ``` |
2011 | #[cfg_attr (feature = "inline-more" , inline)] |
2012 | pub fn raw_entry(&self) -> RawEntryBuilder<'_, K, V, S, A> { |
2013 | RawEntryBuilder { map: self } |
2014 | } |
2015 | |
2016 | /// Returns a mutable reference to the [`RawTable`] used underneath [`HashMap`]. |
2017 | /// This function is only available if the `raw` feature of the crate is enabled. |
2018 | /// |
2019 | /// # Note |
2020 | /// |
2021 | /// Calling the function safe, but using raw hash table API's may require |
2022 | /// unsafe functions or blocks. |
2023 | /// |
2024 | /// `RawTable` API gives the lowest level of control under the map that can be useful |
2025 | /// for extending the HashMap's API, but may lead to *[undefined behavior]*. |
2026 | /// |
2027 | /// [`HashMap`]: struct.HashMap.html |
2028 | /// [`RawTable`]: raw/struct.RawTable.html |
2029 | /// [undefined behavior]: https://doc.rust-lang.org/reference/behavior-considered-undefined.html |
2030 | /// |
2031 | /// # Examples |
2032 | /// |
2033 | /// ``` |
2034 | /// use core::hash::{BuildHasher, Hash}; |
2035 | /// use hashbrown::HashMap; |
2036 | /// |
2037 | /// let mut map = HashMap::new(); |
2038 | /// map.extend([("a" , 10), ("b" , 20), ("c" , 30)]); |
2039 | /// assert_eq!(map.len(), 3); |
2040 | /// |
2041 | /// // Let's imagine that we have a value and a hash of the key, but not the key itself. |
2042 | /// // However, if you want to remove the value from the map by hash and value, and you |
2043 | /// // know exactly that the value is unique, then you can create a function like this: |
2044 | /// fn remove_by_hash<K, V, S, F>( |
2045 | /// map: &mut HashMap<K, V, S>, |
2046 | /// hash: u64, |
2047 | /// is_match: F, |
2048 | /// ) -> Option<(K, V)> |
2049 | /// where |
2050 | /// F: Fn(&(K, V)) -> bool, |
2051 | /// { |
2052 | /// let raw_table = map.raw_table(); |
2053 | /// match raw_table.find(hash, is_match) { |
2054 | /// Some(bucket) => Some(unsafe { raw_table.remove(bucket) }), |
2055 | /// None => None, |
2056 | /// } |
2057 | /// } |
2058 | /// |
2059 | /// fn compute_hash<K: Hash + ?Sized, S: BuildHasher>(hash_builder: &S, key: &K) -> u64 { |
2060 | /// use core::hash::Hasher; |
2061 | /// let mut state = hash_builder.build_hasher(); |
2062 | /// key.hash(&mut state); |
2063 | /// state.finish() |
2064 | /// } |
2065 | /// |
2066 | /// let hash = compute_hash(map.hasher(), "a" ); |
2067 | /// assert_eq!(remove_by_hash(&mut map, hash, |(_, v)| *v == 10), Some(("a" , 10))); |
2068 | /// assert_eq!(map.get(&"a" ), None); |
2069 | /// assert_eq!(map.len(), 2); |
2070 | /// ``` |
2071 | #[cfg (feature = "raw" )] |
2072 | #[cfg_attr (feature = "inline-more" , inline)] |
2073 | pub fn raw_table(&mut self) -> &mut RawTable<(K, V), A> { |
2074 | &mut self.table |
2075 | } |
2076 | } |
2077 | |
2078 | impl<K, V, S, A> PartialEq for HashMap<K, V, S, A> |
2079 | where |
2080 | K: Eq + Hash, |
2081 | V: PartialEq, |
2082 | S: BuildHasher, |
2083 | A: Allocator + Clone, |
2084 | { |
2085 | fn eq(&self, other: &Self) -> bool { |
2086 | if self.len() != other.len() { |
2087 | return false; |
2088 | } |
2089 | |
2090 | self.iter() |
2091 | .all(|(key: &K, value: &V)| other.get(key).map_or(default:false, |v: &V| *value == *v)) |
2092 | } |
2093 | } |
2094 | |
2095 | impl<K, V, S, A> Eq for HashMap<K, V, S, A> |
2096 | where |
2097 | K: Eq + Hash, |
2098 | V: Eq, |
2099 | S: BuildHasher, |
2100 | A: Allocator + Clone, |
2101 | { |
2102 | } |
2103 | |
2104 | impl<K, V, S, A> Debug for HashMap<K, V, S, A> |
2105 | where |
2106 | K: Debug, |
2107 | V: Debug, |
2108 | A: Allocator + Clone, |
2109 | { |
2110 | fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { |
2111 | f.debug_map().entries(self.iter()).finish() |
2112 | } |
2113 | } |
2114 | |
2115 | impl<K, V, S, A> Default for HashMap<K, V, S, A> |
2116 | where |
2117 | S: Default, |
2118 | A: Default + Allocator + Clone, |
2119 | { |
2120 | /// Creates an empty `HashMap<K, V, S, A>`, with the `Default` value for the hasher and allocator. |
2121 | /// |
2122 | /// # Examples |
2123 | /// |
2124 | /// ``` |
2125 | /// use hashbrown::HashMap; |
2126 | /// use std::collections::hash_map::RandomState; |
2127 | /// |
2128 | /// // You can specify all types of HashMap, including hasher and allocator. |
2129 | /// // Created map is empty and don't allocate memory |
2130 | /// let map: HashMap<u32, String> = Default::default(); |
2131 | /// assert_eq!(map.capacity(), 0); |
2132 | /// let map: HashMap<u32, String, RandomState> = HashMap::default(); |
2133 | /// assert_eq!(map.capacity(), 0); |
2134 | /// ``` |
2135 | #[cfg_attr (feature = "inline-more" , inline)] |
2136 | fn default() -> Self { |
2137 | Self::with_hasher_in(hash_builder:Default::default(), alloc:Default::default()) |
2138 | } |
2139 | } |
2140 | |
2141 | impl<K, Q: ?Sized, V, S, A> Index<&Q> for HashMap<K, V, S, A> |
2142 | where |
2143 | K: Eq + Hash + Borrow<Q>, |
2144 | Q: Eq + Hash, |
2145 | S: BuildHasher, |
2146 | A: Allocator + Clone, |
2147 | { |
2148 | type Output = V; |
2149 | |
2150 | /// Returns a reference to the value corresponding to the supplied key. |
2151 | /// |
2152 | /// # Panics |
2153 | /// |
2154 | /// Panics if the key is not present in the `HashMap`. |
2155 | /// |
2156 | /// # Examples |
2157 | /// |
2158 | /// ``` |
2159 | /// use hashbrown::HashMap; |
2160 | /// |
2161 | /// let map: HashMap<_, _> = [("a" , "One" ), ("b" , "Two" )].into(); |
2162 | /// |
2163 | /// assert_eq!(map[&"a" ], "One" ); |
2164 | /// assert_eq!(map[&"b" ], "Two" ); |
2165 | /// ``` |
2166 | #[cfg_attr (feature = "inline-more" , inline)] |
2167 | fn index(&self, key: &Q) -> &V { |
2168 | self.get(key).expect(msg:"no entry found for key" ) |
2169 | } |
2170 | } |
2171 | |
2172 | // The default hasher is used to match the std implementation signature |
2173 | #[cfg (feature = "ahash" )] |
2174 | impl<K, V, A, const N: usize> From<[(K, V); N]> for HashMap<K, V, DefaultHashBuilder, A> |
2175 | where |
2176 | K: Eq + Hash, |
2177 | A: Default + Allocator + Clone, |
2178 | { |
2179 | /// # Examples |
2180 | /// |
2181 | /// ``` |
2182 | /// use hashbrown::HashMap; |
2183 | /// |
2184 | /// let map1 = HashMap::from([(1, 2), (3, 4)]); |
2185 | /// let map2: HashMap<_, _> = [(1, 2), (3, 4)].into(); |
2186 | /// assert_eq!(map1, map2); |
2187 | /// ``` |
2188 | fn from(arr: [(K, V); N]) -> Self { |
2189 | arr.into_iter().collect() |
2190 | } |
2191 | } |
2192 | |
2193 | /// An iterator over the entries of a `HashMap` in arbitrary order. |
2194 | /// The iterator element type is `(&'a K, &'a V)`. |
2195 | /// |
2196 | /// This `struct` is created by the [`iter`] method on [`HashMap`]. See its |
2197 | /// documentation for more. |
2198 | /// |
2199 | /// [`iter`]: struct.HashMap.html#method.iter |
2200 | /// [`HashMap`]: struct.HashMap.html |
2201 | /// |
2202 | /// # Examples |
2203 | /// |
2204 | /// ``` |
2205 | /// use hashbrown::HashMap; |
2206 | /// |
2207 | /// let map: HashMap<_, _> = [(1, "a" ), (2, "b" ), (3, "c" )].into(); |
2208 | /// |
2209 | /// let mut iter = map.iter(); |
2210 | /// let mut vec = vec![iter.next(), iter.next(), iter.next()]; |
2211 | /// |
2212 | /// // The `Iter` iterator produces items in arbitrary order, so the |
2213 | /// // items must be sorted to test them against a sorted array. |
2214 | /// vec.sort_unstable(); |
2215 | /// assert_eq!(vec, [Some((&1, &"a" )), Some((&2, &"b" )), Some((&3, &"c" ))]); |
2216 | /// |
2217 | /// // It is fused iterator |
2218 | /// assert_eq!(iter.next(), None); |
2219 | /// assert_eq!(iter.next(), None); |
2220 | /// ``` |
2221 | pub struct Iter<'a, K, V> { |
2222 | inner: RawIter<(K, V)>, |
2223 | marker: PhantomData<(&'a K, &'a V)>, |
2224 | } |
2225 | |
2226 | // FIXME(#26925) Remove in favor of `#[derive(Clone)]` |
2227 | impl<K, V> Clone for Iter<'_, K, V> { |
2228 | #[cfg_attr (feature = "inline-more" , inline)] |
2229 | fn clone(&self) -> Self { |
2230 | Iter { |
2231 | inner: self.inner.clone(), |
2232 | marker: PhantomData, |
2233 | } |
2234 | } |
2235 | } |
2236 | |
2237 | impl<K: Debug, V: Debug> fmt::Debug for Iter<'_, K, V> { |
2238 | fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { |
2239 | f.debug_list().entries(self.clone()).finish() |
2240 | } |
2241 | } |
2242 | |
2243 | /// A mutable iterator over the entries of a `HashMap` in arbitrary order. |
2244 | /// The iterator element type is `(&'a K, &'a mut V)`. |
2245 | /// |
2246 | /// This `struct` is created by the [`iter_mut`] method on [`HashMap`]. See its |
2247 | /// documentation for more. |
2248 | /// |
2249 | /// [`iter_mut`]: struct.HashMap.html#method.iter_mut |
2250 | /// [`HashMap`]: struct.HashMap.html |
2251 | /// |
2252 | /// # Examples |
2253 | /// |
2254 | /// ``` |
2255 | /// use hashbrown::HashMap; |
2256 | /// |
2257 | /// let mut map: HashMap<_, _> = [(1, "One" .to_owned()), (2, "Two" .into())].into(); |
2258 | /// |
2259 | /// let mut iter = map.iter_mut(); |
2260 | /// iter.next().map(|(_, v)| v.push_str(" Mississippi" )); |
2261 | /// iter.next().map(|(_, v)| v.push_str(" Mississippi" )); |
2262 | /// |
2263 | /// // It is fused iterator |
2264 | /// assert_eq!(iter.next(), None); |
2265 | /// assert_eq!(iter.next(), None); |
2266 | /// |
2267 | /// assert_eq!(map.get(&1).unwrap(), &"One Mississippi" .to_owned()); |
2268 | /// assert_eq!(map.get(&2).unwrap(), &"Two Mississippi" .to_owned()); |
2269 | /// ``` |
2270 | pub struct IterMut<'a, K, V> { |
2271 | inner: RawIter<(K, V)>, |
2272 | // To ensure invariance with respect to V |
2273 | marker: PhantomData<(&'a K, &'a mut V)>, |
2274 | } |
2275 | |
2276 | // We override the default Send impl which has K: Sync instead of K: Send. Both |
2277 | // are correct, but this one is more general since it allows keys which |
2278 | // implement Send but not Sync. |
2279 | unsafe impl<K: Send, V: Send> Send for IterMut<'_, K, V> {} |
2280 | |
2281 | impl<K, V> IterMut<'_, K, V> { |
2282 | /// Returns a iterator of references over the remaining items. |
2283 | #[cfg_attr (feature = "inline-more" , inline)] |
2284 | pub(super) fn iter(&self) -> Iter<'_, K, V> { |
2285 | Iter { |
2286 | inner: self.inner.clone(), |
2287 | marker: PhantomData, |
2288 | } |
2289 | } |
2290 | } |
2291 | |
2292 | /// An owning iterator over the entries of a `HashMap` in arbitrary order. |
2293 | /// The iterator element type is `(K, V)`. |
2294 | /// |
2295 | /// This `struct` is created by the [`into_iter`] method on [`HashMap`] |
2296 | /// (provided by the [`IntoIterator`] trait). See its documentation for more. |
2297 | /// The map cannot be used after calling that method. |
2298 | /// |
2299 | /// [`into_iter`]: struct.HashMap.html#method.into_iter |
2300 | /// [`HashMap`]: struct.HashMap.html |
2301 | /// [`IntoIterator`]: https://doc.rust-lang.org/core/iter/trait.IntoIterator.html |
2302 | /// |
2303 | /// # Examples |
2304 | /// |
2305 | /// ``` |
2306 | /// use hashbrown::HashMap; |
2307 | /// |
2308 | /// let map: HashMap<_, _> = [(1, "a" ), (2, "b" ), (3, "c" )].into(); |
2309 | /// |
2310 | /// let mut iter = map.into_iter(); |
2311 | /// let mut vec = vec![iter.next(), iter.next(), iter.next()]; |
2312 | /// |
2313 | /// // The `IntoIter` iterator produces items in arbitrary order, so the |
2314 | /// // items must be sorted to test them against a sorted array. |
2315 | /// vec.sort_unstable(); |
2316 | /// assert_eq!(vec, [Some((1, "a" )), Some((2, "b" )), Some((3, "c" ))]); |
2317 | /// |
2318 | /// // It is fused iterator |
2319 | /// assert_eq!(iter.next(), None); |
2320 | /// assert_eq!(iter.next(), None); |
2321 | /// ``` |
2322 | pub struct IntoIter<K, V, A: Allocator + Clone = Global> { |
2323 | inner: RawIntoIter<(K, V), A>, |
2324 | } |
2325 | |
2326 | impl<K, V, A: Allocator + Clone> IntoIter<K, V, A> { |
2327 | /// Returns a iterator of references over the remaining items. |
2328 | #[cfg_attr (feature = "inline-more" , inline)] |
2329 | pub(super) fn iter(&self) -> Iter<'_, K, V> { |
2330 | Iter { |
2331 | inner: self.inner.iter(), |
2332 | marker: PhantomData, |
2333 | } |
2334 | } |
2335 | } |
2336 | |
2337 | /// An owning iterator over the keys of a `HashMap` in arbitrary order. |
2338 | /// The iterator element type is `K`. |
2339 | /// |
2340 | /// This `struct` is created by the [`into_keys`] method on [`HashMap`]. |
2341 | /// See its documentation for more. |
2342 | /// The map cannot be used after calling that method. |
2343 | /// |
2344 | /// [`into_keys`]: struct.HashMap.html#method.into_keys |
2345 | /// [`HashMap`]: struct.HashMap.html |
2346 | /// |
2347 | /// # Examples |
2348 | /// |
2349 | /// ``` |
2350 | /// use hashbrown::HashMap; |
2351 | /// |
2352 | /// let map: HashMap<_, _> = [(1, "a" ), (2, "b" ), (3, "c" )].into(); |
2353 | /// |
2354 | /// let mut keys = map.into_keys(); |
2355 | /// let mut vec = vec![keys.next(), keys.next(), keys.next()]; |
2356 | /// |
2357 | /// // The `IntoKeys` iterator produces keys in arbitrary order, so the |
2358 | /// // keys must be sorted to test them against a sorted array. |
2359 | /// vec.sort_unstable(); |
2360 | /// assert_eq!(vec, [Some(1), Some(2), Some(3)]); |
2361 | /// |
2362 | /// // It is fused iterator |
2363 | /// assert_eq!(keys.next(), None); |
2364 | /// assert_eq!(keys.next(), None); |
2365 | /// ``` |
2366 | pub struct IntoKeys<K, V, A: Allocator + Clone = Global> { |
2367 | inner: IntoIter<K, V, A>, |
2368 | } |
2369 | |
2370 | impl<K, V, A: Allocator + Clone> Iterator for IntoKeys<K, V, A> { |
2371 | type Item = K; |
2372 | |
2373 | #[inline ] |
2374 | fn next(&mut self) -> Option<K> { |
2375 | self.inner.next().map(|(k: K, _)| k) |
2376 | } |
2377 | #[inline ] |
2378 | fn size_hint(&self) -> (usize, Option<usize>) { |
2379 | self.inner.size_hint() |
2380 | } |
2381 | } |
2382 | |
2383 | impl<K, V, A: Allocator + Clone> ExactSizeIterator for IntoKeys<K, V, A> { |
2384 | #[inline ] |
2385 | fn len(&self) -> usize { |
2386 | self.inner.len() |
2387 | } |
2388 | } |
2389 | |
2390 | impl<K, V, A: Allocator + Clone> FusedIterator for IntoKeys<K, V, A> {} |
2391 | |
2392 | impl<K: Debug, V: Debug, A: Allocator + Clone> fmt::Debug for IntoKeys<K, V, A> { |
2393 | fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { |
2394 | f&mut DebugList<'_, '_>.debug_list() |
2395 | .entries(self.inner.iter().map(|(k: &K, _)| k)) |
2396 | .finish() |
2397 | } |
2398 | } |
2399 | |
2400 | /// An owning iterator over the values of a `HashMap` in arbitrary order. |
2401 | /// The iterator element type is `V`. |
2402 | /// |
2403 | /// This `struct` is created by the [`into_values`] method on [`HashMap`]. |
2404 | /// See its documentation for more. The map cannot be used after calling that method. |
2405 | /// |
2406 | /// [`into_values`]: struct.HashMap.html#method.into_values |
2407 | /// [`HashMap`]: struct.HashMap.html |
2408 | /// |
2409 | /// # Examples |
2410 | /// |
2411 | /// ``` |
2412 | /// use hashbrown::HashMap; |
2413 | /// |
2414 | /// let map: HashMap<_, _> = [(1, "a" ), (2, "b" ), (3, "c" )].into(); |
2415 | /// |
2416 | /// let mut values = map.into_values(); |
2417 | /// let mut vec = vec![values.next(), values.next(), values.next()]; |
2418 | /// |
2419 | /// // The `IntoValues` iterator produces values in arbitrary order, so |
2420 | /// // the values must be sorted to test them against a sorted array. |
2421 | /// vec.sort_unstable(); |
2422 | /// assert_eq!(vec, [Some("a" ), Some("b" ), Some("c" )]); |
2423 | /// |
2424 | /// // It is fused iterator |
2425 | /// assert_eq!(values.next(), None); |
2426 | /// assert_eq!(values.next(), None); |
2427 | /// ``` |
2428 | pub struct IntoValues<K, V, A: Allocator + Clone = Global> { |
2429 | inner: IntoIter<K, V, A>, |
2430 | } |
2431 | |
2432 | impl<K, V, A: Allocator + Clone> Iterator for IntoValues<K, V, A> { |
2433 | type Item = V; |
2434 | |
2435 | #[inline ] |
2436 | fn next(&mut self) -> Option<V> { |
2437 | self.inner.next().map(|(_, v: V)| v) |
2438 | } |
2439 | #[inline ] |
2440 | fn size_hint(&self) -> (usize, Option<usize>) { |
2441 | self.inner.size_hint() |
2442 | } |
2443 | } |
2444 | |
2445 | impl<K, V, A: Allocator + Clone> ExactSizeIterator for IntoValues<K, V, A> { |
2446 | #[inline ] |
2447 | fn len(&self) -> usize { |
2448 | self.inner.len() |
2449 | } |
2450 | } |
2451 | |
2452 | impl<K, V, A: Allocator + Clone> FusedIterator for IntoValues<K, V, A> {} |
2453 | |
2454 | impl<K, V: Debug, A: Allocator + Clone> fmt::Debug for IntoValues<K, V, A> { |
2455 | fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { |
2456 | f&mut DebugList<'_, '_>.debug_list() |
2457 | .entries(self.inner.iter().map(|(_, v: &V)| v)) |
2458 | .finish() |
2459 | } |
2460 | } |
2461 | |
2462 | /// An iterator over the keys of a `HashMap` in arbitrary order. |
2463 | /// The iterator element type is `&'a K`. |
2464 | /// |
2465 | /// This `struct` is created by the [`keys`] method on [`HashMap`]. See its |
2466 | /// documentation for more. |
2467 | /// |
2468 | /// [`keys`]: struct.HashMap.html#method.keys |
2469 | /// [`HashMap`]: struct.HashMap.html |
2470 | /// |
2471 | /// # Examples |
2472 | /// |
2473 | /// ``` |
2474 | /// use hashbrown::HashMap; |
2475 | /// |
2476 | /// let map: HashMap<_, _> = [(1, "a" ), (2, "b" ), (3, "c" )].into(); |
2477 | /// |
2478 | /// let mut keys = map.keys(); |
2479 | /// let mut vec = vec![keys.next(), keys.next(), keys.next()]; |
2480 | /// |
2481 | /// // The `Keys` iterator produces keys in arbitrary order, so the |
2482 | /// // keys must be sorted to test them against a sorted array. |
2483 | /// vec.sort_unstable(); |
2484 | /// assert_eq!(vec, [Some(&1), Some(&2), Some(&3)]); |
2485 | /// |
2486 | /// // It is fused iterator |
2487 | /// assert_eq!(keys.next(), None); |
2488 | /// assert_eq!(keys.next(), None); |
2489 | /// ``` |
2490 | pub struct Keys<'a, K, V> { |
2491 | inner: Iter<'a, K, V>, |
2492 | } |
2493 | |
2494 | // FIXME(#26925) Remove in favor of `#[derive(Clone)]` |
2495 | impl<K, V> Clone for Keys<'_, K, V> { |
2496 | #[cfg_attr (feature = "inline-more" , inline)] |
2497 | fn clone(&self) -> Self { |
2498 | Keys { |
2499 | inner: self.inner.clone(), |
2500 | } |
2501 | } |
2502 | } |
2503 | |
2504 | impl<K: Debug, V> fmt::Debug for Keys<'_, K, V> { |
2505 | fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { |
2506 | f.debug_list().entries(self.clone()).finish() |
2507 | } |
2508 | } |
2509 | |
2510 | /// An iterator over the values of a `HashMap` in arbitrary order. |
2511 | /// The iterator element type is `&'a V`. |
2512 | /// |
2513 | /// This `struct` is created by the [`values`] method on [`HashMap`]. See its |
2514 | /// documentation for more. |
2515 | /// |
2516 | /// [`values`]: struct.HashMap.html#method.values |
2517 | /// [`HashMap`]: struct.HashMap.html |
2518 | /// |
2519 | /// # Examples |
2520 | /// |
2521 | /// ``` |
2522 | /// use hashbrown::HashMap; |
2523 | /// |
2524 | /// let map: HashMap<_, _> = [(1, "a" ), (2, "b" ), (3, "c" )].into(); |
2525 | /// |
2526 | /// let mut values = map.values(); |
2527 | /// let mut vec = vec![values.next(), values.next(), values.next()]; |
2528 | /// |
2529 | /// // The `Values` iterator produces values in arbitrary order, so the |
2530 | /// // values must be sorted to test them against a sorted array. |
2531 | /// vec.sort_unstable(); |
2532 | /// assert_eq!(vec, [Some(&"a" ), Some(&"b" ), Some(&"c" )]); |
2533 | /// |
2534 | /// // It is fused iterator |
2535 | /// assert_eq!(values.next(), None); |
2536 | /// assert_eq!(values.next(), None); |
2537 | /// ``` |
2538 | pub struct Values<'a, K, V> { |
2539 | inner: Iter<'a, K, V>, |
2540 | } |
2541 | |
2542 | // FIXME(#26925) Remove in favor of `#[derive(Clone)]` |
2543 | impl<K, V> Clone for Values<'_, K, V> { |
2544 | #[cfg_attr (feature = "inline-more" , inline)] |
2545 | fn clone(&self) -> Self { |
2546 | Values { |
2547 | inner: self.inner.clone(), |
2548 | } |
2549 | } |
2550 | } |
2551 | |
2552 | impl<K, V: Debug> fmt::Debug for Values<'_, K, V> { |
2553 | fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { |
2554 | f.debug_list().entries(self.clone()).finish() |
2555 | } |
2556 | } |
2557 | |
2558 | /// A draining iterator over the entries of a `HashMap` in arbitrary |
2559 | /// order. The iterator element type is `(K, V)`. |
2560 | /// |
2561 | /// This `struct` is created by the [`drain`] method on [`HashMap`]. See its |
2562 | /// documentation for more. |
2563 | /// |
2564 | /// [`drain`]: struct.HashMap.html#method.drain |
2565 | /// [`HashMap`]: struct.HashMap.html |
2566 | /// |
2567 | /// # Examples |
2568 | /// |
2569 | /// ``` |
2570 | /// use hashbrown::HashMap; |
2571 | /// |
2572 | /// let mut map: HashMap<_, _> = [(1, "a" ), (2, "b" ), (3, "c" )].into(); |
2573 | /// |
2574 | /// let mut drain_iter = map.drain(); |
2575 | /// let mut vec = vec![drain_iter.next(), drain_iter.next(), drain_iter.next()]; |
2576 | /// |
2577 | /// // The `Drain` iterator produces items in arbitrary order, so the |
2578 | /// // items must be sorted to test them against a sorted array. |
2579 | /// vec.sort_unstable(); |
2580 | /// assert_eq!(vec, [Some((1, "a" )), Some((2, "b" )), Some((3, "c" ))]); |
2581 | /// |
2582 | /// // It is fused iterator |
2583 | /// assert_eq!(drain_iter.next(), None); |
2584 | /// assert_eq!(drain_iter.next(), None); |
2585 | /// ``` |
2586 | pub struct Drain<'a, K, V, A: Allocator + Clone = Global> { |
2587 | inner: RawDrain<'a, (K, V), A>, |
2588 | } |
2589 | |
2590 | impl<K, V, A: Allocator + Clone> Drain<'_, K, V, A> { |
2591 | /// Returns a iterator of references over the remaining items. |
2592 | #[cfg_attr (feature = "inline-more" , inline)] |
2593 | pub(super) fn iter(&self) -> Iter<'_, K, V> { |
2594 | Iter { |
2595 | inner: self.inner.iter(), |
2596 | marker: PhantomData, |
2597 | } |
2598 | } |
2599 | } |
2600 | |
2601 | /// A draining iterator over entries of a `HashMap` which don't satisfy the predicate |
2602 | /// `f(&k, &mut v)` in arbitrary order. The iterator element type is `(K, V)`. |
2603 | /// |
2604 | /// This `struct` is created by the [`drain_filter`] method on [`HashMap`]. See its |
2605 | /// documentation for more. |
2606 | /// |
2607 | /// [`drain_filter`]: struct.HashMap.html#method.drain_filter |
2608 | /// [`HashMap`]: struct.HashMap.html |
2609 | /// |
2610 | /// # Examples |
2611 | /// |
2612 | /// ``` |
2613 | /// use hashbrown::HashMap; |
2614 | /// |
2615 | /// let mut map: HashMap<i32, &str> = [(1, "a" ), (2, "b" ), (3, "c" )].into(); |
2616 | /// |
2617 | /// let mut drain_filter = map.drain_filter(|k, _v| k % 2 != 0); |
2618 | /// let mut vec = vec![drain_filter.next(), drain_filter.next()]; |
2619 | /// |
2620 | /// // The `DrainFilter` iterator produces items in arbitrary order, so the |
2621 | /// // items must be sorted to test them against a sorted array. |
2622 | /// vec.sort_unstable(); |
2623 | /// assert_eq!(vec, [Some((1, "a" )),Some((3, "c" ))]); |
2624 | /// |
2625 | /// // It is fused iterator |
2626 | /// assert_eq!(drain_filter.next(), None); |
2627 | /// assert_eq!(drain_filter.next(), None); |
2628 | /// drop(drain_filter); |
2629 | /// |
2630 | /// assert_eq!(map.len(), 1); |
2631 | /// ``` |
2632 | pub struct DrainFilter<'a, K, V, F, A: Allocator + Clone = Global> |
2633 | where |
2634 | F: FnMut(&K, &mut V) -> bool, |
2635 | { |
2636 | f: F, |
2637 | inner: DrainFilterInner<'a, K, V, A>, |
2638 | } |
2639 | |
2640 | impl<'a, K, V, F, A> Drop for DrainFilter<'a, K, V, F, A> |
2641 | where |
2642 | F: FnMut(&K, &mut V) -> bool, |
2643 | A: Allocator + Clone, |
2644 | { |
2645 | #[cfg_attr (feature = "inline-more" , inline)] |
2646 | fn drop(&mut self) { |
2647 | while let Some(item: (K, V)) = self.next() { |
2648 | let guard: ConsumeAllOnDrop<'_, DrainFilter<'_, …, …, …, …>> = ConsumeAllOnDrop(self); |
2649 | drop(item); |
2650 | mem::forget(guard); |
2651 | } |
2652 | } |
2653 | } |
2654 | |
2655 | pub(super) struct ConsumeAllOnDrop<'a, T: Iterator>(pub &'a mut T); |
2656 | |
2657 | impl<T: Iterator> Drop for ConsumeAllOnDrop<'_, T> { |
2658 | #[cfg_attr (feature = "inline-more" , inline)] |
2659 | fn drop(&mut self) { |
2660 | self.0.for_each(drop); |
2661 | } |
2662 | } |
2663 | |
2664 | impl<K, V, F, A> Iterator for DrainFilter<'_, K, V, F, A> |
2665 | where |
2666 | F: FnMut(&K, &mut V) -> bool, |
2667 | A: Allocator + Clone, |
2668 | { |
2669 | type Item = (K, V); |
2670 | |
2671 | #[cfg_attr (feature = "inline-more" , inline)] |
2672 | fn next(&mut self) -> Option<Self::Item> { |
2673 | self.inner.next(&mut self.f) |
2674 | } |
2675 | |
2676 | #[inline ] |
2677 | fn size_hint(&self) -> (usize, Option<usize>) { |
2678 | (0, self.inner.iter.size_hint().1) |
2679 | } |
2680 | } |
2681 | |
2682 | impl<K, V, F> FusedIterator for DrainFilter<'_, K, V, F> where F: FnMut(&K, &mut V) -> bool {} |
2683 | |
2684 | /// Portions of `DrainFilter` shared with `set::DrainFilter` |
2685 | pub(super) struct DrainFilterInner<'a, K, V, A: Allocator + Clone> { |
2686 | pub iter: RawIter<(K, V)>, |
2687 | pub table: &'a mut RawTable<(K, V), A>, |
2688 | } |
2689 | |
2690 | impl<K, V, A: Allocator + Clone> DrainFilterInner<'_, K, V, A> { |
2691 | #[cfg_attr (feature = "inline-more" , inline)] |
2692 | pub(super) fn next<F>(&mut self, f: &mut F) -> Option<(K, V)> |
2693 | where |
2694 | F: FnMut(&K, &mut V) -> bool, |
2695 | { |
2696 | unsafe { |
2697 | for item: Bucket<(K, V)> in &mut self.iter { |
2698 | let &mut (ref key: &K, ref mut value: &mut V) = item.as_mut(); |
2699 | if f(key, value) { |
2700 | return Some(self.table.remove(item)); |
2701 | } |
2702 | } |
2703 | } |
2704 | None |
2705 | } |
2706 | } |
2707 | |
2708 | /// A mutable iterator over the values of a `HashMap` in arbitrary order. |
2709 | /// The iterator element type is `&'a mut V`. |
2710 | /// |
2711 | /// This `struct` is created by the [`values_mut`] method on [`HashMap`]. See its |
2712 | /// documentation for more. |
2713 | /// |
2714 | /// [`values_mut`]: struct.HashMap.html#method.values_mut |
2715 | /// [`HashMap`]: struct.HashMap.html |
2716 | /// |
2717 | /// # Examples |
2718 | /// |
2719 | /// ``` |
2720 | /// use hashbrown::HashMap; |
2721 | /// |
2722 | /// let mut map: HashMap<_, _> = [(1, "One" .to_owned()), (2, "Two" .into())].into(); |
2723 | /// |
2724 | /// let mut values = map.values_mut(); |
2725 | /// values.next().map(|v| v.push_str(" Mississippi" )); |
2726 | /// values.next().map(|v| v.push_str(" Mississippi" )); |
2727 | /// |
2728 | /// // It is fused iterator |
2729 | /// assert_eq!(values.next(), None); |
2730 | /// assert_eq!(values.next(), None); |
2731 | /// |
2732 | /// assert_eq!(map.get(&1).unwrap(), &"One Mississippi" .to_owned()); |
2733 | /// assert_eq!(map.get(&2).unwrap(), &"Two Mississippi" .to_owned()); |
2734 | /// ``` |
2735 | pub struct ValuesMut<'a, K, V> { |
2736 | inner: IterMut<'a, K, V>, |
2737 | } |
2738 | |
2739 | /// A builder for computing where in a [`HashMap`] a key-value pair would be stored. |
2740 | /// |
2741 | /// See the [`HashMap::raw_entry_mut`] docs for usage examples. |
2742 | /// |
2743 | /// [`HashMap::raw_entry_mut`]: struct.HashMap.html#method.raw_entry_mut |
2744 | /// |
2745 | /// # Examples |
2746 | /// |
2747 | /// ``` |
2748 | /// use hashbrown::hash_map::{RawEntryBuilderMut, RawEntryMut::Vacant, RawEntryMut::Occupied}; |
2749 | /// use hashbrown::HashMap; |
2750 | /// use core::hash::{BuildHasher, Hash}; |
2751 | /// |
2752 | /// let mut map = HashMap::new(); |
2753 | /// map.extend([(1, 11), (2, 12), (3, 13), (4, 14), (5, 15), (6, 16)]); |
2754 | /// assert_eq!(map.len(), 6); |
2755 | /// |
2756 | /// fn compute_hash<K: Hash + ?Sized, S: BuildHasher>(hash_builder: &S, key: &K) -> u64 { |
2757 | /// use core::hash::Hasher; |
2758 | /// let mut state = hash_builder.build_hasher(); |
2759 | /// key.hash(&mut state); |
2760 | /// state.finish() |
2761 | /// } |
2762 | /// |
2763 | /// let builder: RawEntryBuilderMut<_, _, _> = map.raw_entry_mut(); |
2764 | /// |
2765 | /// // Existing key |
2766 | /// match builder.from_key(&6) { |
2767 | /// Vacant(_) => unreachable!(), |
2768 | /// Occupied(view) => assert_eq!(view.get(), &16), |
2769 | /// } |
2770 | /// |
2771 | /// for key in 0..12 { |
2772 | /// let hash = compute_hash(map.hasher(), &key); |
2773 | /// let value = map.get(&key).cloned(); |
2774 | /// let key_value = value.as_ref().map(|v| (&key, v)); |
2775 | /// |
2776 | /// println!("Key: {} and value: {:?}" , key, value); |
2777 | /// |
2778 | /// match map.raw_entry_mut().from_key(&key) { |
2779 | /// Occupied(mut o) => assert_eq!(Some(o.get_key_value()), key_value), |
2780 | /// Vacant(_) => assert_eq!(value, None), |
2781 | /// } |
2782 | /// match map.raw_entry_mut().from_key_hashed_nocheck(hash, &key) { |
2783 | /// Occupied(mut o) => assert_eq!(Some(o.get_key_value()), key_value), |
2784 | /// Vacant(_) => assert_eq!(value, None), |
2785 | /// } |
2786 | /// match map.raw_entry_mut().from_hash(hash, |q| *q == key) { |
2787 | /// Occupied(mut o) => assert_eq!(Some(o.get_key_value()), key_value), |
2788 | /// Vacant(_) => assert_eq!(value, None), |
2789 | /// } |
2790 | /// } |
2791 | /// |
2792 | /// assert_eq!(map.len(), 6); |
2793 | /// ``` |
2794 | pub struct RawEntryBuilderMut<'a, K, V, S, A: Allocator + Clone = Global> { |
2795 | map: &'a mut HashMap<K, V, S, A>, |
2796 | } |
2797 | |
2798 | /// A view into a single entry in a map, which may either be vacant or occupied. |
2799 | /// |
2800 | /// This is a lower-level version of [`Entry`]. |
2801 | /// |
2802 | /// This `enum` is constructed through the [`raw_entry_mut`] method on [`HashMap`], |
2803 | /// then calling one of the methods of that [`RawEntryBuilderMut`]. |
2804 | /// |
2805 | /// [`HashMap`]: struct.HashMap.html |
2806 | /// [`Entry`]: enum.Entry.html |
2807 | /// [`raw_entry_mut`]: struct.HashMap.html#method.raw_entry_mut |
2808 | /// [`RawEntryBuilderMut`]: struct.RawEntryBuilderMut.html |
2809 | /// |
2810 | /// # Examples |
2811 | /// |
2812 | /// ``` |
2813 | /// use core::hash::{BuildHasher, Hash}; |
2814 | /// use hashbrown::hash_map::{HashMap, RawEntryMut, RawOccupiedEntryMut}; |
2815 | /// |
2816 | /// let mut map = HashMap::new(); |
2817 | /// map.extend([('a' , 1), ('b' , 2), ('c' , 3)]); |
2818 | /// assert_eq!(map.len(), 3); |
2819 | /// |
2820 | /// fn compute_hash<K: Hash + ?Sized, S: BuildHasher>(hash_builder: &S, key: &K) -> u64 { |
2821 | /// use core::hash::Hasher; |
2822 | /// let mut state = hash_builder.build_hasher(); |
2823 | /// key.hash(&mut state); |
2824 | /// state.finish() |
2825 | /// } |
2826 | /// |
2827 | /// // Existing key (insert) |
2828 | /// let raw: RawEntryMut<_, _, _> = map.raw_entry_mut().from_key(&'a' ); |
2829 | /// let _raw_o: RawOccupiedEntryMut<_, _, _> = raw.insert('a' , 10); |
2830 | /// assert_eq!(map.len(), 3); |
2831 | /// |
2832 | /// // Nonexistent key (insert) |
2833 | /// map.raw_entry_mut().from_key(&'d' ).insert('d' , 40); |
2834 | /// assert_eq!(map.len(), 4); |
2835 | /// |
2836 | /// // Existing key (or_insert) |
2837 | /// let hash = compute_hash(map.hasher(), &'b' ); |
2838 | /// let kv = map |
2839 | /// .raw_entry_mut() |
2840 | /// .from_key_hashed_nocheck(hash, &'b' ) |
2841 | /// .or_insert('b' , 20); |
2842 | /// assert_eq!(kv, (&mut 'b' , &mut 2)); |
2843 | /// *kv.1 = 20; |
2844 | /// assert_eq!(map.len(), 4); |
2845 | /// |
2846 | /// // Nonexistent key (or_insert) |
2847 | /// let hash = compute_hash(map.hasher(), &'e' ); |
2848 | /// let kv = map |
2849 | /// .raw_entry_mut() |
2850 | /// .from_key_hashed_nocheck(hash, &'e' ) |
2851 | /// .or_insert('e' , 50); |
2852 | /// assert_eq!(kv, (&mut 'e' , &mut 50)); |
2853 | /// assert_eq!(map.len(), 5); |
2854 | /// |
2855 | /// // Existing key (or_insert_with) |
2856 | /// let hash = compute_hash(map.hasher(), &'c' ); |
2857 | /// let kv = map |
2858 | /// .raw_entry_mut() |
2859 | /// .from_hash(hash, |q| q == &'c' ) |
2860 | /// .or_insert_with(|| ('c' , 30)); |
2861 | /// assert_eq!(kv, (&mut 'c' , &mut 3)); |
2862 | /// *kv.1 = 30; |
2863 | /// assert_eq!(map.len(), 5); |
2864 | /// |
2865 | /// // Nonexistent key (or_insert_with) |
2866 | /// let hash = compute_hash(map.hasher(), &'f' ); |
2867 | /// let kv = map |
2868 | /// .raw_entry_mut() |
2869 | /// .from_hash(hash, |q| q == &'f' ) |
2870 | /// .or_insert_with(|| ('f' , 60)); |
2871 | /// assert_eq!(kv, (&mut 'f' , &mut 60)); |
2872 | /// assert_eq!(map.len(), 6); |
2873 | /// |
2874 | /// println!("Our HashMap: {:?}" , map); |
2875 | /// |
2876 | /// let mut vec: Vec<_> = map.iter().map(|(&k, &v)| (k, v)).collect(); |
2877 | /// // The `Iter` iterator produces items in arbitrary order, so the |
2878 | /// // items must be sorted to test them against a sorted array. |
2879 | /// vec.sort_unstable(); |
2880 | /// assert_eq!(vec, [('a' , 10), ('b' , 20), ('c' , 30), ('d' , 40), ('e' , 50), ('f' , 60)]); |
2881 | /// ``` |
2882 | pub enum RawEntryMut<'a, K, V, S, A: Allocator + Clone = Global> { |
2883 | /// An occupied entry. |
2884 | /// |
2885 | /// # Examples |
2886 | /// |
2887 | /// ``` |
2888 | /// use hashbrown::{hash_map::RawEntryMut, HashMap}; |
2889 | /// let mut map: HashMap<_, _> = [("a" , 100), ("b" , 200)].into(); |
2890 | /// |
2891 | /// match map.raw_entry_mut().from_key(&"a" ) { |
2892 | /// RawEntryMut::Vacant(_) => unreachable!(), |
2893 | /// RawEntryMut::Occupied(_) => { } |
2894 | /// } |
2895 | /// ``` |
2896 | Occupied(RawOccupiedEntryMut<'a, K, V, S, A>), |
2897 | /// A vacant entry. |
2898 | /// |
2899 | /// # Examples |
2900 | /// |
2901 | /// ``` |
2902 | /// use hashbrown::{hash_map::RawEntryMut, HashMap}; |
2903 | /// let mut map: HashMap<&str, i32> = HashMap::new(); |
2904 | /// |
2905 | /// match map.raw_entry_mut().from_key("a" ) { |
2906 | /// RawEntryMut::Occupied(_) => unreachable!(), |
2907 | /// RawEntryMut::Vacant(_) => { } |
2908 | /// } |
2909 | /// ``` |
2910 | Vacant(RawVacantEntryMut<'a, K, V, S, A>), |
2911 | } |
2912 | |
2913 | /// A view into an occupied entry in a `HashMap`. |
2914 | /// It is part of the [`RawEntryMut`] enum. |
2915 | /// |
2916 | /// [`RawEntryMut`]: enum.RawEntryMut.html |
2917 | /// |
2918 | /// # Examples |
2919 | /// |
2920 | /// ``` |
2921 | /// use core::hash::{BuildHasher, Hash}; |
2922 | /// use hashbrown::hash_map::{HashMap, RawEntryMut, RawOccupiedEntryMut}; |
2923 | /// |
2924 | /// let mut map = HashMap::new(); |
2925 | /// map.extend([("a" , 10), ("b" , 20), ("c" , 30)]); |
2926 | /// |
2927 | /// fn compute_hash<K: Hash + ?Sized, S: BuildHasher>(hash_builder: &S, key: &K) -> u64 { |
2928 | /// use core::hash::Hasher; |
2929 | /// let mut state = hash_builder.build_hasher(); |
2930 | /// key.hash(&mut state); |
2931 | /// state.finish() |
2932 | /// } |
2933 | /// |
2934 | /// let _raw_o: RawOccupiedEntryMut<_, _, _> = map.raw_entry_mut().from_key(&"a" ).insert("a" , 100); |
2935 | /// assert_eq!(map.len(), 3); |
2936 | /// |
2937 | /// // Existing key (insert and update) |
2938 | /// match map.raw_entry_mut().from_key(&"a" ) { |
2939 | /// RawEntryMut::Vacant(_) => unreachable!(), |
2940 | /// RawEntryMut::Occupied(mut view) => { |
2941 | /// assert_eq!(view.get(), &100); |
2942 | /// let v = view.get_mut(); |
2943 | /// let new_v = (*v) * 10; |
2944 | /// *v = new_v; |
2945 | /// assert_eq!(view.insert(1111), 1000); |
2946 | /// } |
2947 | /// } |
2948 | /// |
2949 | /// assert_eq!(map[&"a" ], 1111); |
2950 | /// assert_eq!(map.len(), 3); |
2951 | /// |
2952 | /// // Existing key (take) |
2953 | /// let hash = compute_hash(map.hasher(), &"c" ); |
2954 | /// match map.raw_entry_mut().from_key_hashed_nocheck(hash, &"c" ) { |
2955 | /// RawEntryMut::Vacant(_) => unreachable!(), |
2956 | /// RawEntryMut::Occupied(view) => { |
2957 | /// assert_eq!(view.remove_entry(), ("c" , 30)); |
2958 | /// } |
2959 | /// } |
2960 | /// assert_eq!(map.raw_entry().from_key(&"c" ), None); |
2961 | /// assert_eq!(map.len(), 2); |
2962 | /// |
2963 | /// let hash = compute_hash(map.hasher(), &"b" ); |
2964 | /// match map.raw_entry_mut().from_hash(hash, |q| *q == "b" ) { |
2965 | /// RawEntryMut::Vacant(_) => unreachable!(), |
2966 | /// RawEntryMut::Occupied(view) => { |
2967 | /// assert_eq!(view.remove_entry(), ("b" , 20)); |
2968 | /// } |
2969 | /// } |
2970 | /// assert_eq!(map.get(&"b" ), None); |
2971 | /// assert_eq!(map.len(), 1); |
2972 | /// ``` |
2973 | pub struct RawOccupiedEntryMut<'a, K, V, S, A: Allocator + Clone = Global> { |
2974 | elem: Bucket<(K, V)>, |
2975 | table: &'a mut RawTable<(K, V), A>, |
2976 | hash_builder: &'a S, |
2977 | } |
2978 | |
2979 | unsafe impl<K, V, S, A> Send for RawOccupiedEntryMut<'_, K, V, S, A> |
2980 | where |
2981 | K: Send, |
2982 | V: Send, |
2983 | S: Send, |
2984 | A: Send + Allocator + Clone, |
2985 | { |
2986 | } |
2987 | unsafe impl<K, V, S, A> Sync for RawOccupiedEntryMut<'_, K, V, S, A> |
2988 | where |
2989 | K: Sync, |
2990 | V: Sync, |
2991 | S: Sync, |
2992 | A: Sync + Allocator + Clone, |
2993 | { |
2994 | } |
2995 | |
2996 | /// A view into a vacant entry in a `HashMap`. |
2997 | /// It is part of the [`RawEntryMut`] enum. |
2998 | /// |
2999 | /// [`RawEntryMut`]: enum.RawEntryMut.html |
3000 | /// |
3001 | /// # Examples |
3002 | /// |
3003 | /// ``` |
3004 | /// use core::hash::{BuildHasher, Hash}; |
3005 | /// use hashbrown::hash_map::{HashMap, RawEntryMut, RawVacantEntryMut}; |
3006 | /// |
3007 | /// let mut map = HashMap::<&str, i32>::new(); |
3008 | /// |
3009 | /// fn compute_hash<K: Hash + ?Sized, S: BuildHasher>(hash_builder: &S, key: &K) -> u64 { |
3010 | /// use core::hash::Hasher; |
3011 | /// let mut state = hash_builder.build_hasher(); |
3012 | /// key.hash(&mut state); |
3013 | /// state.finish() |
3014 | /// } |
3015 | /// |
3016 | /// let raw_v: RawVacantEntryMut<_, _, _> = match map.raw_entry_mut().from_key(&"a" ) { |
3017 | /// RawEntryMut::Vacant(view) => view, |
3018 | /// RawEntryMut::Occupied(_) => unreachable!(), |
3019 | /// }; |
3020 | /// raw_v.insert("a" , 10); |
3021 | /// assert!(map[&"a" ] == 10 && map.len() == 1); |
3022 | /// |
3023 | /// // Nonexistent key (insert and update) |
3024 | /// let hash = compute_hash(map.hasher(), &"b" ); |
3025 | /// match map.raw_entry_mut().from_key_hashed_nocheck(hash, &"b" ) { |
3026 | /// RawEntryMut::Occupied(_) => unreachable!(), |
3027 | /// RawEntryMut::Vacant(view) => { |
3028 | /// let (k, value) = view.insert("b" , 2); |
3029 | /// assert_eq!((*k, *value), ("b" , 2)); |
3030 | /// *value = 20; |
3031 | /// } |
3032 | /// } |
3033 | /// assert!(map[&"b" ] == 20 && map.len() == 2); |
3034 | /// |
3035 | /// let hash = compute_hash(map.hasher(), &"c" ); |
3036 | /// match map.raw_entry_mut().from_hash(hash, |q| *q == "c" ) { |
3037 | /// RawEntryMut::Occupied(_) => unreachable!(), |
3038 | /// RawEntryMut::Vacant(view) => { |
3039 | /// assert_eq!(view.insert("c" , 30), (&mut "c" , &mut 30)); |
3040 | /// } |
3041 | /// } |
3042 | /// assert!(map[&"c" ] == 30 && map.len() == 3); |
3043 | /// ``` |
3044 | pub struct RawVacantEntryMut<'a, K, V, S, A: Allocator + Clone = Global> { |
3045 | table: &'a mut RawTable<(K, V), A>, |
3046 | hash_builder: &'a S, |
3047 | } |
3048 | |
3049 | /// A builder for computing where in a [`HashMap`] a key-value pair would be stored. |
3050 | /// |
3051 | /// See the [`HashMap::raw_entry`] docs for usage examples. |
3052 | /// |
3053 | /// [`HashMap::raw_entry`]: struct.HashMap.html#method.raw_entry |
3054 | /// |
3055 | /// # Examples |
3056 | /// |
3057 | /// ``` |
3058 | /// use hashbrown::hash_map::{HashMap, RawEntryBuilder}; |
3059 | /// use core::hash::{BuildHasher, Hash}; |
3060 | /// |
3061 | /// let mut map = HashMap::new(); |
3062 | /// map.extend([(1, 10), (2, 20), (3, 30)]); |
3063 | /// |
3064 | /// fn compute_hash<K: Hash + ?Sized, S: BuildHasher>(hash_builder: &S, key: &K) -> u64 { |
3065 | /// use core::hash::Hasher; |
3066 | /// let mut state = hash_builder.build_hasher(); |
3067 | /// key.hash(&mut state); |
3068 | /// state.finish() |
3069 | /// } |
3070 | /// |
3071 | /// for k in 0..6 { |
3072 | /// let hash = compute_hash(map.hasher(), &k); |
3073 | /// let v = map.get(&k).cloned(); |
3074 | /// let kv = v.as_ref().map(|v| (&k, v)); |
3075 | /// |
3076 | /// println!("Key: {} and value: {:?}" , k, v); |
3077 | /// let builder: RawEntryBuilder<_, _, _> = map.raw_entry(); |
3078 | /// assert_eq!(builder.from_key(&k), kv); |
3079 | /// assert_eq!(map.raw_entry().from_hash(hash, |q| *q == k), kv); |
3080 | /// assert_eq!(map.raw_entry().from_key_hashed_nocheck(hash, &k), kv); |
3081 | /// } |
3082 | /// ``` |
3083 | pub struct RawEntryBuilder<'a, K, V, S, A: Allocator + Clone = Global> { |
3084 | map: &'a HashMap<K, V, S, A>, |
3085 | } |
3086 | |
3087 | impl<'a, K, V, S, A: Allocator + Clone> RawEntryBuilderMut<'a, K, V, S, A> { |
3088 | /// Creates a `RawEntryMut` from the given key. |
3089 | /// |
3090 | /// # Examples |
3091 | /// |
3092 | /// ``` |
3093 | /// use hashbrown::hash_map::{HashMap, RawEntryMut}; |
3094 | /// |
3095 | /// let mut map: HashMap<&str, u32> = HashMap::new(); |
3096 | /// let key = "a" ; |
3097 | /// let entry: RawEntryMut<&str, u32, _> = map.raw_entry_mut().from_key(&key); |
3098 | /// entry.insert(key, 100); |
3099 | /// assert_eq!(map[&"a" ], 100); |
3100 | /// ``` |
3101 | #[cfg_attr (feature = "inline-more" , inline)] |
3102 | #[allow (clippy::wrong_self_convention)] |
3103 | pub fn from_key<Q: ?Sized>(self, k: &Q) -> RawEntryMut<'a, K, V, S, A> |
3104 | where |
3105 | S: BuildHasher, |
3106 | K: Borrow<Q>, |
3107 | Q: Hash + Eq, |
3108 | { |
3109 | let hash = make_hash::<K, Q, S>(&self.map.hash_builder, k); |
3110 | self.from_key_hashed_nocheck(hash, k) |
3111 | } |
3112 | |
3113 | /// Creates a `RawEntryMut` from the given key and its hash. |
3114 | /// |
3115 | /// # Examples |
3116 | /// |
3117 | /// ``` |
3118 | /// use core::hash::{BuildHasher, Hash}; |
3119 | /// use hashbrown::hash_map::{HashMap, RawEntryMut}; |
3120 | /// |
3121 | /// fn compute_hash<K: Hash + ?Sized, S: BuildHasher>(hash_builder: &S, key: &K) -> u64 { |
3122 | /// use core::hash::Hasher; |
3123 | /// let mut state = hash_builder.build_hasher(); |
3124 | /// key.hash(&mut state); |
3125 | /// state.finish() |
3126 | /// } |
3127 | /// |
3128 | /// let mut map: HashMap<&str, u32> = HashMap::new(); |
3129 | /// let key = "a" ; |
3130 | /// let hash = compute_hash(map.hasher(), &key); |
3131 | /// let entry: RawEntryMut<&str, u32, _> = map.raw_entry_mut().from_key_hashed_nocheck(hash, &key); |
3132 | /// entry.insert(key, 100); |
3133 | /// assert_eq!(map[&"a" ], 100); |
3134 | /// ``` |
3135 | #[inline ] |
3136 | #[allow (clippy::wrong_self_convention)] |
3137 | pub fn from_key_hashed_nocheck<Q: ?Sized>(self, hash: u64, k: &Q) -> RawEntryMut<'a, K, V, S, A> |
3138 | where |
3139 | K: Borrow<Q>, |
3140 | Q: Eq, |
3141 | { |
3142 | self.from_hash(hash, equivalent(k)) |
3143 | } |
3144 | } |
3145 | |
3146 | impl<'a, K, V, S, A: Allocator + Clone> RawEntryBuilderMut<'a, K, V, S, A> { |
3147 | /// Creates a `RawEntryMut` from the given hash and matching function. |
3148 | /// |
3149 | /// # Examples |
3150 | /// |
3151 | /// ``` |
3152 | /// use core::hash::{BuildHasher, Hash}; |
3153 | /// use hashbrown::hash_map::{HashMap, RawEntryMut}; |
3154 | /// |
3155 | /// fn compute_hash<K: Hash + ?Sized, S: BuildHasher>(hash_builder: &S, key: &K) -> u64 { |
3156 | /// use core::hash::Hasher; |
3157 | /// let mut state = hash_builder.build_hasher(); |
3158 | /// key.hash(&mut state); |
3159 | /// state.finish() |
3160 | /// } |
3161 | /// |
3162 | /// let mut map: HashMap<&str, u32> = HashMap::new(); |
3163 | /// let key = "a" ; |
3164 | /// let hash = compute_hash(map.hasher(), &key); |
3165 | /// let entry: RawEntryMut<&str, u32, _> = map.raw_entry_mut().from_hash(hash, |k| k == &key); |
3166 | /// entry.insert(key, 100); |
3167 | /// assert_eq!(map[&"a" ], 100); |
3168 | /// ``` |
3169 | #[cfg_attr (feature = "inline-more" , inline)] |
3170 | #[allow (clippy::wrong_self_convention)] |
3171 | pub fn from_hash<F>(self, hash: u64, is_match: F) -> RawEntryMut<'a, K, V, S, A> |
3172 | where |
3173 | for<'b> F: FnMut(&'b K) -> bool, |
3174 | { |
3175 | self.search(hash, is_match) |
3176 | } |
3177 | |
3178 | #[cfg_attr (feature = "inline-more" , inline)] |
3179 | fn search<F>(self, hash: u64, mut is_match: F) -> RawEntryMut<'a, K, V, S, A> |
3180 | where |
3181 | for<'b> F: FnMut(&'b K) -> bool, |
3182 | { |
3183 | match self.map.table.find(hash, |(k, _)| is_match(k)) { |
3184 | Some(elem) => RawEntryMut::Occupied(RawOccupiedEntryMut { |
3185 | elem, |
3186 | table: &mut self.map.table, |
3187 | hash_builder: &self.map.hash_builder, |
3188 | }), |
3189 | None => RawEntryMut::Vacant(RawVacantEntryMut { |
3190 | table: &mut self.map.table, |
3191 | hash_builder: &self.map.hash_builder, |
3192 | }), |
3193 | } |
3194 | } |
3195 | } |
3196 | |
3197 | impl<'a, K, V, S, A: Allocator + Clone> RawEntryBuilder<'a, K, V, S, A> { |
3198 | /// Access an immutable entry by key. |
3199 | /// |
3200 | /// # Examples |
3201 | /// |
3202 | /// ``` |
3203 | /// use hashbrown::HashMap; |
3204 | /// |
3205 | /// let map: HashMap<&str, u32> = [("a" , 100), ("b" , 200)].into(); |
3206 | /// let key = "a" ; |
3207 | /// assert_eq!(map.raw_entry().from_key(&key), Some((&"a" , &100))); |
3208 | /// ``` |
3209 | #[cfg_attr (feature = "inline-more" , inline)] |
3210 | #[allow (clippy::wrong_self_convention)] |
3211 | pub fn from_key<Q: ?Sized>(self, k: &Q) -> Option<(&'a K, &'a V)> |
3212 | where |
3213 | S: BuildHasher, |
3214 | K: Borrow<Q>, |
3215 | Q: Hash + Eq, |
3216 | { |
3217 | let hash = make_hash::<K, Q, S>(&self.map.hash_builder, k); |
3218 | self.from_key_hashed_nocheck(hash, k) |
3219 | } |
3220 | |
3221 | /// Access an immutable entry by a key and its hash. |
3222 | /// |
3223 | /// # Examples |
3224 | /// |
3225 | /// ``` |
3226 | /// use core::hash::{BuildHasher, Hash}; |
3227 | /// use hashbrown::HashMap; |
3228 | /// |
3229 | /// fn compute_hash<K: Hash + ?Sized, S: BuildHasher>(hash_builder: &S, key: &K) -> u64 { |
3230 | /// use core::hash::Hasher; |
3231 | /// let mut state = hash_builder.build_hasher(); |
3232 | /// key.hash(&mut state); |
3233 | /// state.finish() |
3234 | /// } |
3235 | /// |
3236 | /// let map: HashMap<&str, u32> = [("a" , 100), ("b" , 200)].into(); |
3237 | /// let key = "a" ; |
3238 | /// let hash = compute_hash(map.hasher(), &key); |
3239 | /// assert_eq!(map.raw_entry().from_key_hashed_nocheck(hash, &key), Some((&"a" , &100))); |
3240 | /// ``` |
3241 | #[cfg_attr (feature = "inline-more" , inline)] |
3242 | #[allow (clippy::wrong_self_convention)] |
3243 | pub fn from_key_hashed_nocheck<Q: ?Sized>(self, hash: u64, k: &Q) -> Option<(&'a K, &'a V)> |
3244 | where |
3245 | K: Borrow<Q>, |
3246 | Q: Eq, |
3247 | { |
3248 | self.from_hash(hash, equivalent(k)) |
3249 | } |
3250 | |
3251 | #[cfg_attr (feature = "inline-more" , inline)] |
3252 | fn search<F>(self, hash: u64, mut is_match: F) -> Option<(&'a K, &'a V)> |
3253 | where |
3254 | F: FnMut(&K) -> bool, |
3255 | { |
3256 | match self.map.table.get(hash, |(k, _)| is_match(k)) { |
3257 | Some(&(ref key, ref value)) => Some((key, value)), |
3258 | None => None, |
3259 | } |
3260 | } |
3261 | |
3262 | /// Access an immutable entry by hash and matching function. |
3263 | /// |
3264 | /// # Examples |
3265 | /// |
3266 | /// ``` |
3267 | /// use core::hash::{BuildHasher, Hash}; |
3268 | /// use hashbrown::HashMap; |
3269 | /// |
3270 | /// fn compute_hash<K: Hash + ?Sized, S: BuildHasher>(hash_builder: &S, key: &K) -> u64 { |
3271 | /// use core::hash::Hasher; |
3272 | /// let mut state = hash_builder.build_hasher(); |
3273 | /// key.hash(&mut state); |
3274 | /// state.finish() |
3275 | /// } |
3276 | /// |
3277 | /// let map: HashMap<&str, u32> = [("a" , 100), ("b" , 200)].into(); |
3278 | /// let key = "a" ; |
3279 | /// let hash = compute_hash(map.hasher(), &key); |
3280 | /// assert_eq!(map.raw_entry().from_hash(hash, |k| k == &key), Some((&"a" , &100))); |
3281 | /// ``` |
3282 | #[cfg_attr (feature = "inline-more" , inline)] |
3283 | #[allow (clippy::wrong_self_convention)] |
3284 | pub fn from_hash<F>(self, hash: u64, is_match: F) -> Option<(&'a K, &'a V)> |
3285 | where |
3286 | F: FnMut(&K) -> bool, |
3287 | { |
3288 | self.search(hash, is_match) |
3289 | } |
3290 | } |
3291 | |
3292 | impl<'a, K, V, S, A: Allocator + Clone> RawEntryMut<'a, K, V, S, A> { |
3293 | /// Sets the value of the entry, and returns a RawOccupiedEntryMut. |
3294 | /// |
3295 | /// # Examples |
3296 | /// |
3297 | /// ``` |
3298 | /// use hashbrown::HashMap; |
3299 | /// |
3300 | /// let mut map: HashMap<&str, u32> = HashMap::new(); |
3301 | /// let entry = map.raw_entry_mut().from_key("horseyland" ).insert("horseyland" , 37); |
3302 | /// |
3303 | /// assert_eq!(entry.remove_entry(), ("horseyland" , 37)); |
3304 | /// ``` |
3305 | #[cfg_attr (feature = "inline-more" , inline)] |
3306 | pub fn insert(self, key: K, value: V) -> RawOccupiedEntryMut<'a, K, V, S, A> |
3307 | where |
3308 | K: Hash, |
3309 | S: BuildHasher, |
3310 | { |
3311 | match self { |
3312 | RawEntryMut::Occupied(mut entry) => { |
3313 | entry.insert(value); |
3314 | entry |
3315 | } |
3316 | RawEntryMut::Vacant(entry) => entry.insert_entry(key, value), |
3317 | } |
3318 | } |
3319 | |
3320 | /// Ensures a value is in the entry by inserting the default if empty, and returns |
3321 | /// mutable references to the key and value in the entry. |
3322 | /// |
3323 | /// # Examples |
3324 | /// |
3325 | /// ``` |
3326 | /// use hashbrown::HashMap; |
3327 | /// |
3328 | /// let mut map: HashMap<&str, u32> = HashMap::new(); |
3329 | /// |
3330 | /// map.raw_entry_mut().from_key("poneyland" ).or_insert("poneyland" , 3); |
3331 | /// assert_eq!(map["poneyland" ], 3); |
3332 | /// |
3333 | /// *map.raw_entry_mut().from_key("poneyland" ).or_insert("poneyland" , 10).1 *= 2; |
3334 | /// assert_eq!(map["poneyland" ], 6); |
3335 | /// ``` |
3336 | #[cfg_attr (feature = "inline-more" , inline)] |
3337 | pub fn or_insert(self, default_key: K, default_val: V) -> (&'a mut K, &'a mut V) |
3338 | where |
3339 | K: Hash, |
3340 | S: BuildHasher, |
3341 | { |
3342 | match self { |
3343 | RawEntryMut::Occupied(entry) => entry.into_key_value(), |
3344 | RawEntryMut::Vacant(entry) => entry.insert(default_key, default_val), |
3345 | } |
3346 | } |
3347 | |
3348 | /// Ensures a value is in the entry by inserting the result of the default function if empty, |
3349 | /// and returns mutable references to the key and value in the entry. |
3350 | /// |
3351 | /// # Examples |
3352 | /// |
3353 | /// ``` |
3354 | /// use hashbrown::HashMap; |
3355 | /// |
3356 | /// let mut map: HashMap<&str, String> = HashMap::new(); |
3357 | /// |
3358 | /// map.raw_entry_mut().from_key("poneyland" ).or_insert_with(|| { |
3359 | /// ("poneyland" , "hoho" .to_string()) |
3360 | /// }); |
3361 | /// |
3362 | /// assert_eq!(map["poneyland" ], "hoho" .to_string()); |
3363 | /// ``` |
3364 | #[cfg_attr (feature = "inline-more" , inline)] |
3365 | pub fn or_insert_with<F>(self, default: F) -> (&'a mut K, &'a mut V) |
3366 | where |
3367 | F: FnOnce() -> (K, V), |
3368 | K: Hash, |
3369 | S: BuildHasher, |
3370 | { |
3371 | match self { |
3372 | RawEntryMut::Occupied(entry) => entry.into_key_value(), |
3373 | RawEntryMut::Vacant(entry) => { |
3374 | let (k, v) = default(); |
3375 | entry.insert(k, v) |
3376 | } |
3377 | } |
3378 | } |
3379 | |
3380 | /// Provides in-place mutable access to an occupied entry before any |
3381 | /// potential inserts into the map. |
3382 | /// |
3383 | /// # Examples |
3384 | /// |
3385 | /// ``` |
3386 | /// use hashbrown::HashMap; |
3387 | /// |
3388 | /// let mut map: HashMap<&str, u32> = HashMap::new(); |
3389 | /// |
3390 | /// map.raw_entry_mut() |
3391 | /// .from_key("poneyland" ) |
3392 | /// .and_modify(|_k, v| { *v += 1 }) |
3393 | /// .or_insert("poneyland" , 42); |
3394 | /// assert_eq!(map["poneyland" ], 42); |
3395 | /// |
3396 | /// map.raw_entry_mut() |
3397 | /// .from_key("poneyland" ) |
3398 | /// .and_modify(|_k, v| { *v += 1 }) |
3399 | /// .or_insert("poneyland" , 0); |
3400 | /// assert_eq!(map["poneyland" ], 43); |
3401 | /// ``` |
3402 | #[cfg_attr (feature = "inline-more" , inline)] |
3403 | pub fn and_modify<F>(self, f: F) -> Self |
3404 | where |
3405 | F: FnOnce(&mut K, &mut V), |
3406 | { |
3407 | match self { |
3408 | RawEntryMut::Occupied(mut entry) => { |
3409 | { |
3410 | let (k, v) = entry.get_key_value_mut(); |
3411 | f(k, v); |
3412 | } |
3413 | RawEntryMut::Occupied(entry) |
3414 | } |
3415 | RawEntryMut::Vacant(entry) => RawEntryMut::Vacant(entry), |
3416 | } |
3417 | } |
3418 | |
3419 | /// Provides shared access to the key and owned access to the value of |
3420 | /// an occupied entry and allows to replace or remove it based on the |
3421 | /// value of the returned option. |
3422 | /// |
3423 | /// # Examples |
3424 | /// |
3425 | /// ``` |
3426 | /// use hashbrown::HashMap; |
3427 | /// use hashbrown::hash_map::RawEntryMut; |
3428 | /// |
3429 | /// let mut map: HashMap<&str, u32> = HashMap::new(); |
3430 | /// |
3431 | /// let entry = map |
3432 | /// .raw_entry_mut() |
3433 | /// .from_key("poneyland" ) |
3434 | /// .and_replace_entry_with(|_k, _v| panic!()); |
3435 | /// |
3436 | /// match entry { |
3437 | /// RawEntryMut::Vacant(_) => {}, |
3438 | /// RawEntryMut::Occupied(_) => panic!(), |
3439 | /// } |
3440 | /// |
3441 | /// map.insert("poneyland" , 42); |
3442 | /// |
3443 | /// let entry = map |
3444 | /// .raw_entry_mut() |
3445 | /// .from_key("poneyland" ) |
3446 | /// .and_replace_entry_with(|k, v| { |
3447 | /// assert_eq!(k, &"poneyland" ); |
3448 | /// assert_eq!(v, 42); |
3449 | /// Some(v + 1) |
3450 | /// }); |
3451 | /// |
3452 | /// match entry { |
3453 | /// RawEntryMut::Occupied(e) => { |
3454 | /// assert_eq!(e.key(), &"poneyland" ); |
3455 | /// assert_eq!(e.get(), &43); |
3456 | /// }, |
3457 | /// RawEntryMut::Vacant(_) => panic!(), |
3458 | /// } |
3459 | /// |
3460 | /// assert_eq!(map["poneyland" ], 43); |
3461 | /// |
3462 | /// let entry = map |
3463 | /// .raw_entry_mut() |
3464 | /// .from_key("poneyland" ) |
3465 | /// .and_replace_entry_with(|_k, _v| None); |
3466 | /// |
3467 | /// match entry { |
3468 | /// RawEntryMut::Vacant(_) => {}, |
3469 | /// RawEntryMut::Occupied(_) => panic!(), |
3470 | /// } |
3471 | /// |
3472 | /// assert!(!map.contains_key("poneyland" )); |
3473 | /// ``` |
3474 | #[cfg_attr (feature = "inline-more" , inline)] |
3475 | pub fn and_replace_entry_with<F>(self, f: F) -> Self |
3476 | where |
3477 | F: FnOnce(&K, V) -> Option<V>, |
3478 | { |
3479 | match self { |
3480 | RawEntryMut::Occupied(entry) => entry.replace_entry_with(f), |
3481 | RawEntryMut::Vacant(_) => self, |
3482 | } |
3483 | } |
3484 | } |
3485 | |
3486 | impl<'a, K, V, S, A: Allocator + Clone> RawOccupiedEntryMut<'a, K, V, S, A> { |
3487 | /// Gets a reference to the key in the entry. |
3488 | /// |
3489 | /// # Examples |
3490 | /// |
3491 | /// ``` |
3492 | /// use hashbrown::hash_map::{HashMap, RawEntryMut}; |
3493 | /// |
3494 | /// let mut map: HashMap<&str, u32> = [("a" , 100), ("b" , 200)].into(); |
3495 | /// |
3496 | /// match map.raw_entry_mut().from_key(&"a" ) { |
3497 | /// RawEntryMut::Vacant(_) => panic!(), |
3498 | /// RawEntryMut::Occupied(o) => assert_eq!(o.key(), &"a" ) |
3499 | /// } |
3500 | /// ``` |
3501 | #[cfg_attr (feature = "inline-more" , inline)] |
3502 | pub fn key(&self) -> &K { |
3503 | unsafe { &self.elem.as_ref().0 } |
3504 | } |
3505 | |
3506 | /// Gets a mutable reference to the key in the entry. |
3507 | /// |
3508 | /// # Examples |
3509 | /// |
3510 | /// ``` |
3511 | /// use hashbrown::hash_map::{HashMap, RawEntryMut}; |
3512 | /// use std::rc::Rc; |
3513 | /// |
3514 | /// let key_one = Rc::new("a" ); |
3515 | /// let key_two = Rc::new("a" ); |
3516 | /// |
3517 | /// let mut map: HashMap<Rc<&str>, u32> = HashMap::new(); |
3518 | /// map.insert(key_one.clone(), 10); |
3519 | /// |
3520 | /// assert_eq!(map[&key_one], 10); |
3521 | /// assert!(Rc::strong_count(&key_one) == 2 && Rc::strong_count(&key_two) == 1); |
3522 | /// |
3523 | /// match map.raw_entry_mut().from_key(&key_one) { |
3524 | /// RawEntryMut::Vacant(_) => panic!(), |
3525 | /// RawEntryMut::Occupied(mut o) => { |
3526 | /// *o.key_mut() = key_two.clone(); |
3527 | /// } |
3528 | /// } |
3529 | /// assert_eq!(map[&key_two], 10); |
3530 | /// assert!(Rc::strong_count(&key_one) == 1 && Rc::strong_count(&key_two) == 2); |
3531 | /// ``` |
3532 | #[cfg_attr (feature = "inline-more" , inline)] |
3533 | pub fn key_mut(&mut self) -> &mut K { |
3534 | unsafe { &mut self.elem.as_mut().0 } |
3535 | } |
3536 | |
3537 | /// Converts the entry into a mutable reference to the key in the entry |
3538 | /// with a lifetime bound to the map itself. |
3539 | /// |
3540 | /// # Examples |
3541 | /// |
3542 | /// ``` |
3543 | /// use hashbrown::hash_map::{HashMap, RawEntryMut}; |
3544 | /// use std::rc::Rc; |
3545 | /// |
3546 | /// let key_one = Rc::new("a" ); |
3547 | /// let key_two = Rc::new("a" ); |
3548 | /// |
3549 | /// let mut map: HashMap<Rc<&str>, u32> = HashMap::new(); |
3550 | /// map.insert(key_one.clone(), 10); |
3551 | /// |
3552 | /// assert_eq!(map[&key_one], 10); |
3553 | /// assert!(Rc::strong_count(&key_one) == 2 && Rc::strong_count(&key_two) == 1); |
3554 | /// |
3555 | /// let inside_key: &mut Rc<&str>; |
3556 | /// |
3557 | /// match map.raw_entry_mut().from_key(&key_one) { |
3558 | /// RawEntryMut::Vacant(_) => panic!(), |
3559 | /// RawEntryMut::Occupied(o) => inside_key = o.into_key(), |
3560 | /// } |
3561 | /// *inside_key = key_two.clone(); |
3562 | /// |
3563 | /// assert_eq!(map[&key_two], 10); |
3564 | /// assert!(Rc::strong_count(&key_one) == 1 && Rc::strong_count(&key_two) == 2); |
3565 | /// ``` |
3566 | #[cfg_attr (feature = "inline-more" , inline)] |
3567 | pub fn into_key(self) -> &'a mut K { |
3568 | unsafe { &mut self.elem.as_mut().0 } |
3569 | } |
3570 | |
3571 | /// Gets a reference to the value in the entry. |
3572 | /// |
3573 | /// # Examples |
3574 | /// |
3575 | /// ``` |
3576 | /// use hashbrown::hash_map::{HashMap, RawEntryMut}; |
3577 | /// |
3578 | /// let mut map: HashMap<&str, u32> = [("a" , 100), ("b" , 200)].into(); |
3579 | /// |
3580 | /// match map.raw_entry_mut().from_key(&"a" ) { |
3581 | /// RawEntryMut::Vacant(_) => panic!(), |
3582 | /// RawEntryMut::Occupied(o) => assert_eq!(o.get(), &100), |
3583 | /// } |
3584 | /// ``` |
3585 | #[cfg_attr (feature = "inline-more" , inline)] |
3586 | pub fn get(&self) -> &V { |
3587 | unsafe { &self.elem.as_ref().1 } |
3588 | } |
3589 | |
3590 | /// Converts the OccupiedEntry into a mutable reference to the value in the entry |
3591 | /// with a lifetime bound to the map itself. |
3592 | /// |
3593 | /// # Examples |
3594 | /// |
3595 | /// ``` |
3596 | /// use hashbrown::hash_map::{HashMap, RawEntryMut}; |
3597 | /// |
3598 | /// let mut map: HashMap<&str, u32> = [("a" , 100), ("b" , 200)].into(); |
3599 | /// |
3600 | /// let value: &mut u32; |
3601 | /// |
3602 | /// match map.raw_entry_mut().from_key(&"a" ) { |
3603 | /// RawEntryMut::Vacant(_) => panic!(), |
3604 | /// RawEntryMut::Occupied(o) => value = o.into_mut(), |
3605 | /// } |
3606 | /// *value += 900; |
3607 | /// |
3608 | /// assert_eq!(map[&"a" ], 1000); |
3609 | /// ``` |
3610 | #[cfg_attr (feature = "inline-more" , inline)] |
3611 | pub fn into_mut(self) -> &'a mut V { |
3612 | unsafe { &mut self.elem.as_mut().1 } |
3613 | } |
3614 | |
3615 | /// Gets a mutable reference to the value in the entry. |
3616 | /// |
3617 | /// # Examples |
3618 | /// |
3619 | /// ``` |
3620 | /// use hashbrown::hash_map::{HashMap, RawEntryMut}; |
3621 | /// |
3622 | /// let mut map: HashMap<&str, u32> = [("a" , 100), ("b" , 200)].into(); |
3623 | /// |
3624 | /// match map.raw_entry_mut().from_key(&"a" ) { |
3625 | /// RawEntryMut::Vacant(_) => panic!(), |
3626 | /// RawEntryMut::Occupied(mut o) => *o.get_mut() += 900, |
3627 | /// } |
3628 | /// |
3629 | /// assert_eq!(map[&"a" ], 1000); |
3630 | /// ``` |
3631 | #[cfg_attr (feature = "inline-more" , inline)] |
3632 | pub fn get_mut(&mut self) -> &mut V { |
3633 | unsafe { &mut self.elem.as_mut().1 } |
3634 | } |
3635 | |
3636 | /// Gets a reference to the key and value in the entry. |
3637 | /// |
3638 | /// # Examples |
3639 | /// |
3640 | /// ``` |
3641 | /// use hashbrown::hash_map::{HashMap, RawEntryMut}; |
3642 | /// |
3643 | /// let mut map: HashMap<&str, u32> = [("a" , 100), ("b" , 200)].into(); |
3644 | /// |
3645 | /// match map.raw_entry_mut().from_key(&"a" ) { |
3646 | /// RawEntryMut::Vacant(_) => panic!(), |
3647 | /// RawEntryMut::Occupied(o) => assert_eq!(o.get_key_value(), (&"a" , &100)), |
3648 | /// } |
3649 | /// ``` |
3650 | #[cfg_attr (feature = "inline-more" , inline)] |
3651 | pub fn get_key_value(&self) -> (&K, &V) { |
3652 | unsafe { |
3653 | let &(ref key, ref value) = self.elem.as_ref(); |
3654 | (key, value) |
3655 | } |
3656 | } |
3657 | |
3658 | /// Gets a mutable reference to the key and value in the entry. |
3659 | /// |
3660 | /// # Examples |
3661 | /// |
3662 | /// ``` |
3663 | /// use hashbrown::hash_map::{HashMap, RawEntryMut}; |
3664 | /// use std::rc::Rc; |
3665 | /// |
3666 | /// let key_one = Rc::new("a" ); |
3667 | /// let key_two = Rc::new("a" ); |
3668 | /// |
3669 | /// let mut map: HashMap<Rc<&str>, u32> = HashMap::new(); |
3670 | /// map.insert(key_one.clone(), 10); |
3671 | /// |
3672 | /// assert_eq!(map[&key_one], 10); |
3673 | /// assert!(Rc::strong_count(&key_one) == 2 && Rc::strong_count(&key_two) == 1); |
3674 | /// |
3675 | /// match map.raw_entry_mut().from_key(&key_one) { |
3676 | /// RawEntryMut::Vacant(_) => panic!(), |
3677 | /// RawEntryMut::Occupied(mut o) => { |
3678 | /// let (inside_key, inside_value) = o.get_key_value_mut(); |
3679 | /// *inside_key = key_two.clone(); |
3680 | /// *inside_value = 100; |
3681 | /// } |
3682 | /// } |
3683 | /// assert_eq!(map[&key_two], 100); |
3684 | /// assert!(Rc::strong_count(&key_one) == 1 && Rc::strong_count(&key_two) == 2); |
3685 | /// ``` |
3686 | #[cfg_attr (feature = "inline-more" , inline)] |
3687 | pub fn get_key_value_mut(&mut self) -> (&mut K, &mut V) { |
3688 | unsafe { |
3689 | let &mut (ref mut key, ref mut value) = self.elem.as_mut(); |
3690 | (key, value) |
3691 | } |
3692 | } |
3693 | |
3694 | /// Converts the OccupiedEntry into a mutable reference to the key and value in the entry |
3695 | /// with a lifetime bound to the map itself. |
3696 | /// |
3697 | /// # Examples |
3698 | /// |
3699 | /// ``` |
3700 | /// use hashbrown::hash_map::{HashMap, RawEntryMut}; |
3701 | /// use std::rc::Rc; |
3702 | /// |
3703 | /// let key_one = Rc::new("a" ); |
3704 | /// let key_two = Rc::new("a" ); |
3705 | /// |
3706 | /// let mut map: HashMap<Rc<&str>, u32> = HashMap::new(); |
3707 | /// map.insert(key_one.clone(), 10); |
3708 | /// |
3709 | /// assert_eq!(map[&key_one], 10); |
3710 | /// assert!(Rc::strong_count(&key_one) == 2 && Rc::strong_count(&key_two) == 1); |
3711 | /// |
3712 | /// let inside_key: &mut Rc<&str>; |
3713 | /// let inside_value: &mut u32; |
3714 | /// match map.raw_entry_mut().from_key(&key_one) { |
3715 | /// RawEntryMut::Vacant(_) => panic!(), |
3716 | /// RawEntryMut::Occupied(o) => { |
3717 | /// let tuple = o.into_key_value(); |
3718 | /// inside_key = tuple.0; |
3719 | /// inside_value = tuple.1; |
3720 | /// } |
3721 | /// } |
3722 | /// *inside_key = key_two.clone(); |
3723 | /// *inside_value = 100; |
3724 | /// assert_eq!(map[&key_two], 100); |
3725 | /// assert!(Rc::strong_count(&key_one) == 1 && Rc::strong_count(&key_two) == 2); |
3726 | /// ``` |
3727 | #[cfg_attr (feature = "inline-more" , inline)] |
3728 | pub fn into_key_value(self) -> (&'a mut K, &'a mut V) { |
3729 | unsafe { |
3730 | let &mut (ref mut key, ref mut value) = self.elem.as_mut(); |
3731 | (key, value) |
3732 | } |
3733 | } |
3734 | |
3735 | /// Sets the value of the entry, and returns the entry's old value. |
3736 | /// |
3737 | /// # Examples |
3738 | /// |
3739 | /// ``` |
3740 | /// use hashbrown::hash_map::{HashMap, RawEntryMut}; |
3741 | /// |
3742 | /// let mut map: HashMap<&str, u32> = [("a" , 100), ("b" , 200)].into(); |
3743 | /// |
3744 | /// match map.raw_entry_mut().from_key(&"a" ) { |
3745 | /// RawEntryMut::Vacant(_) => panic!(), |
3746 | /// RawEntryMut::Occupied(mut o) => assert_eq!(o.insert(1000), 100), |
3747 | /// } |
3748 | /// |
3749 | /// assert_eq!(map[&"a" ], 1000); |
3750 | /// ``` |
3751 | #[cfg_attr (feature = "inline-more" , inline)] |
3752 | pub fn insert(&mut self, value: V) -> V { |
3753 | mem::replace(self.get_mut(), value) |
3754 | } |
3755 | |
3756 | /// Sets the value of the entry, and returns the entry's old value. |
3757 | /// |
3758 | /// # Examples |
3759 | /// |
3760 | /// ``` |
3761 | /// use hashbrown::hash_map::{HashMap, RawEntryMut}; |
3762 | /// use std::rc::Rc; |
3763 | /// |
3764 | /// let key_one = Rc::new("a" ); |
3765 | /// let key_two = Rc::new("a" ); |
3766 | /// |
3767 | /// let mut map: HashMap<Rc<&str>, u32> = HashMap::new(); |
3768 | /// map.insert(key_one.clone(), 10); |
3769 | /// |
3770 | /// assert_eq!(map[&key_one], 10); |
3771 | /// assert!(Rc::strong_count(&key_one) == 2 && Rc::strong_count(&key_two) == 1); |
3772 | /// |
3773 | /// match map.raw_entry_mut().from_key(&key_one) { |
3774 | /// RawEntryMut::Vacant(_) => panic!(), |
3775 | /// RawEntryMut::Occupied(mut o) => { |
3776 | /// let old_key = o.insert_key(key_two.clone()); |
3777 | /// assert!(Rc::ptr_eq(&old_key, &key_one)); |
3778 | /// } |
3779 | /// } |
3780 | /// assert_eq!(map[&key_two], 10); |
3781 | /// assert!(Rc::strong_count(&key_one) == 1 && Rc::strong_count(&key_two) == 2); |
3782 | /// ``` |
3783 | #[cfg_attr (feature = "inline-more" , inline)] |
3784 | pub fn insert_key(&mut self, key: K) -> K { |
3785 | mem::replace(self.key_mut(), key) |
3786 | } |
3787 | |
3788 | /// Takes the value out of the entry, and returns it. |
3789 | /// |
3790 | /// # Examples |
3791 | /// |
3792 | /// ``` |
3793 | /// use hashbrown::hash_map::{HashMap, RawEntryMut}; |
3794 | /// |
3795 | /// let mut map: HashMap<&str, u32> = [("a" , 100), ("b" , 200)].into(); |
3796 | /// |
3797 | /// match map.raw_entry_mut().from_key(&"a" ) { |
3798 | /// RawEntryMut::Vacant(_) => panic!(), |
3799 | /// RawEntryMut::Occupied(o) => assert_eq!(o.remove(), 100), |
3800 | /// } |
3801 | /// assert_eq!(map.get(&"a" ), None); |
3802 | /// ``` |
3803 | #[cfg_attr (feature = "inline-more" , inline)] |
3804 | pub fn remove(self) -> V { |
3805 | self.remove_entry().1 |
3806 | } |
3807 | |
3808 | /// Take the ownership of the key and value from the map. |
3809 | /// |
3810 | /// # Examples |
3811 | /// |
3812 | /// ``` |
3813 | /// use hashbrown::hash_map::{HashMap, RawEntryMut}; |
3814 | /// |
3815 | /// let mut map: HashMap<&str, u32> = [("a" , 100), ("b" , 200)].into(); |
3816 | /// |
3817 | /// match map.raw_entry_mut().from_key(&"a" ) { |
3818 | /// RawEntryMut::Vacant(_) => panic!(), |
3819 | /// RawEntryMut::Occupied(o) => assert_eq!(o.remove_entry(), ("a" , 100)), |
3820 | /// } |
3821 | /// assert_eq!(map.get(&"a" ), None); |
3822 | /// ``` |
3823 | #[cfg_attr (feature = "inline-more" , inline)] |
3824 | pub fn remove_entry(self) -> (K, V) { |
3825 | unsafe { self.table.remove(self.elem) } |
3826 | } |
3827 | |
3828 | /// Provides shared access to the key and owned access to the value of |
3829 | /// the entry and allows to replace or remove it based on the |
3830 | /// value of the returned option. |
3831 | /// |
3832 | /// # Examples |
3833 | /// |
3834 | /// ``` |
3835 | /// use hashbrown::hash_map::{HashMap, RawEntryMut}; |
3836 | /// |
3837 | /// let mut map: HashMap<&str, u32> = [("a" , 100), ("b" , 200)].into(); |
3838 | /// |
3839 | /// let raw_entry = match map.raw_entry_mut().from_key(&"a" ) { |
3840 | /// RawEntryMut::Vacant(_) => panic!(), |
3841 | /// RawEntryMut::Occupied(o) => o.replace_entry_with(|k, v| { |
3842 | /// assert_eq!(k, &"a" ); |
3843 | /// assert_eq!(v, 100); |
3844 | /// Some(v + 900) |
3845 | /// }), |
3846 | /// }; |
3847 | /// let raw_entry = match raw_entry { |
3848 | /// RawEntryMut::Vacant(_) => panic!(), |
3849 | /// RawEntryMut::Occupied(o) => o.replace_entry_with(|k, v| { |
3850 | /// assert_eq!(k, &"a" ); |
3851 | /// assert_eq!(v, 1000); |
3852 | /// None |
3853 | /// }), |
3854 | /// }; |
3855 | /// match raw_entry { |
3856 | /// RawEntryMut::Vacant(_) => { }, |
3857 | /// RawEntryMut::Occupied(_) => panic!(), |
3858 | /// }; |
3859 | /// assert_eq!(map.get(&"a" ), None); |
3860 | /// ``` |
3861 | #[cfg_attr (feature = "inline-more" , inline)] |
3862 | pub fn replace_entry_with<F>(self, f: F) -> RawEntryMut<'a, K, V, S, A> |
3863 | where |
3864 | F: FnOnce(&K, V) -> Option<V>, |
3865 | { |
3866 | unsafe { |
3867 | let still_occupied = self |
3868 | .table |
3869 | .replace_bucket_with(self.elem.clone(), |(key, value)| { |
3870 | f(&key, value).map(|new_value| (key, new_value)) |
3871 | }); |
3872 | |
3873 | if still_occupied { |
3874 | RawEntryMut::Occupied(self) |
3875 | } else { |
3876 | RawEntryMut::Vacant(RawVacantEntryMut { |
3877 | table: self.table, |
3878 | hash_builder: self.hash_builder, |
3879 | }) |
3880 | } |
3881 | } |
3882 | } |
3883 | } |
3884 | |
3885 | impl<'a, K, V, S, A: Allocator + Clone> RawVacantEntryMut<'a, K, V, S, A> { |
3886 | /// Sets the value of the entry with the VacantEntry's key, |
3887 | /// and returns a mutable reference to it. |
3888 | /// |
3889 | /// # Examples |
3890 | /// |
3891 | /// ``` |
3892 | /// use hashbrown::hash_map::{HashMap, RawEntryMut}; |
3893 | /// |
3894 | /// let mut map: HashMap<&str, u32> = [("a" , 100), ("b" , 200)].into(); |
3895 | /// |
3896 | /// match map.raw_entry_mut().from_key(&"c" ) { |
3897 | /// RawEntryMut::Occupied(_) => panic!(), |
3898 | /// RawEntryMut::Vacant(v) => assert_eq!(v.insert("c" , 300), (&mut "c" , &mut 300)), |
3899 | /// } |
3900 | /// |
3901 | /// assert_eq!(map[&"c" ], 300); |
3902 | /// ``` |
3903 | #[cfg_attr (feature = "inline-more" , inline)] |
3904 | pub fn insert(self, key: K, value: V) -> (&'a mut K, &'a mut V) |
3905 | where |
3906 | K: Hash, |
3907 | S: BuildHasher, |
3908 | { |
3909 | let hash = make_insert_hash::<K, S>(self.hash_builder, &key); |
3910 | self.insert_hashed_nocheck(hash, key, value) |
3911 | } |
3912 | |
3913 | /// Sets the value of the entry with the VacantEntry's key, |
3914 | /// and returns a mutable reference to it. |
3915 | /// |
3916 | /// # Examples |
3917 | /// |
3918 | /// ``` |
3919 | /// use core::hash::{BuildHasher, Hash}; |
3920 | /// use hashbrown::hash_map::{HashMap, RawEntryMut}; |
3921 | /// |
3922 | /// fn compute_hash<K: Hash + ?Sized, S: BuildHasher>(hash_builder: &S, key: &K) -> u64 { |
3923 | /// use core::hash::Hasher; |
3924 | /// let mut state = hash_builder.build_hasher(); |
3925 | /// key.hash(&mut state); |
3926 | /// state.finish() |
3927 | /// } |
3928 | /// |
3929 | /// let mut map: HashMap<&str, u32> = [("a" , 100), ("b" , 200)].into(); |
3930 | /// let key = "c" ; |
3931 | /// let hash = compute_hash(map.hasher(), &key); |
3932 | /// |
3933 | /// match map.raw_entry_mut().from_key_hashed_nocheck(hash, &key) { |
3934 | /// RawEntryMut::Occupied(_) => panic!(), |
3935 | /// RawEntryMut::Vacant(v) => assert_eq!( |
3936 | /// v.insert_hashed_nocheck(hash, key, 300), |
3937 | /// (&mut "c" , &mut 300) |
3938 | /// ), |
3939 | /// } |
3940 | /// |
3941 | /// assert_eq!(map[&"c" ], 300); |
3942 | /// ``` |
3943 | #[cfg_attr (feature = "inline-more" , inline)] |
3944 | #[allow (clippy::shadow_unrelated)] |
3945 | pub fn insert_hashed_nocheck(self, hash: u64, key: K, value: V) -> (&'a mut K, &'a mut V) |
3946 | where |
3947 | K: Hash, |
3948 | S: BuildHasher, |
3949 | { |
3950 | let &mut (ref mut k, ref mut v) = self.table.insert_entry( |
3951 | hash, |
3952 | (key, value), |
3953 | make_hasher::<K, _, V, S>(self.hash_builder), |
3954 | ); |
3955 | (k, v) |
3956 | } |
3957 | |
3958 | /// Set the value of an entry with a custom hasher function. |
3959 | /// |
3960 | /// # Examples |
3961 | /// |
3962 | /// ``` |
3963 | /// use core::hash::{BuildHasher, Hash}; |
3964 | /// use hashbrown::hash_map::{HashMap, RawEntryMut}; |
3965 | /// |
3966 | /// fn make_hasher<K, S>(hash_builder: &S) -> impl Fn(&K) -> u64 + '_ |
3967 | /// where |
3968 | /// K: Hash + ?Sized, |
3969 | /// S: BuildHasher, |
3970 | /// { |
3971 | /// move |key: &K| { |
3972 | /// use core::hash::Hasher; |
3973 | /// let mut state = hash_builder.build_hasher(); |
3974 | /// key.hash(&mut state); |
3975 | /// state.finish() |
3976 | /// } |
3977 | /// } |
3978 | /// |
3979 | /// let mut map: HashMap<&str, u32> = HashMap::new(); |
3980 | /// let key = "a" ; |
3981 | /// let hash_builder = map.hasher().clone(); |
3982 | /// let hash = make_hasher(&hash_builder)(&key); |
3983 | /// |
3984 | /// match map.raw_entry_mut().from_hash(hash, |q| q == &key) { |
3985 | /// RawEntryMut::Occupied(_) => panic!(), |
3986 | /// RawEntryMut::Vacant(v) => assert_eq!( |
3987 | /// v.insert_with_hasher(hash, key, 100, make_hasher(&hash_builder)), |
3988 | /// (&mut "a" , &mut 100) |
3989 | /// ), |
3990 | /// } |
3991 | /// map.extend([("b" , 200), ("c" , 300), ("d" , 400), ("e" , 500), ("f" , 600)]); |
3992 | /// assert_eq!(map[&"a" ], 100); |
3993 | /// ``` |
3994 | #[cfg_attr (feature = "inline-more" , inline)] |
3995 | pub fn insert_with_hasher<H>( |
3996 | self, |
3997 | hash: u64, |
3998 | key: K, |
3999 | value: V, |
4000 | hasher: H, |
4001 | ) -> (&'a mut K, &'a mut V) |
4002 | where |
4003 | H: Fn(&K) -> u64, |
4004 | { |
4005 | let &mut (ref mut k, ref mut v) = self |
4006 | .table |
4007 | .insert_entry(hash, (key, value), |x| hasher(&x.0)); |
4008 | (k, v) |
4009 | } |
4010 | |
4011 | #[cfg_attr (feature = "inline-more" , inline)] |
4012 | fn insert_entry(self, key: K, value: V) -> RawOccupiedEntryMut<'a, K, V, S, A> |
4013 | where |
4014 | K: Hash, |
4015 | S: BuildHasher, |
4016 | { |
4017 | let hash = make_insert_hash::<K, S>(self.hash_builder, &key); |
4018 | let elem = self.table.insert( |
4019 | hash, |
4020 | (key, value), |
4021 | make_hasher::<K, _, V, S>(self.hash_builder), |
4022 | ); |
4023 | RawOccupiedEntryMut { |
4024 | elem, |
4025 | table: self.table, |
4026 | hash_builder: self.hash_builder, |
4027 | } |
4028 | } |
4029 | } |
4030 | |
4031 | impl<K, V, S, A: Allocator + Clone> Debug for RawEntryBuilderMut<'_, K, V, S, A> { |
4032 | fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { |
4033 | f.debug_struct(name:"RawEntryBuilder" ).finish() |
4034 | } |
4035 | } |
4036 | |
4037 | impl<K: Debug, V: Debug, S, A: Allocator + Clone> Debug for RawEntryMut<'_, K, V, S, A> { |
4038 | fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { |
4039 | match *self { |
4040 | RawEntryMut::Vacant(ref v: &RawVacantEntryMut<'_, K, …, …, …>) => f.debug_tuple(name:"RawEntry" ).field(v).finish(), |
4041 | RawEntryMut::Occupied(ref o: &RawOccupiedEntryMut<'_, …, …, …, …>) => f.debug_tuple(name:"RawEntry" ).field(o).finish(), |
4042 | } |
4043 | } |
4044 | } |
4045 | |
4046 | impl<K: Debug, V: Debug, S, A: Allocator + Clone> Debug for RawOccupiedEntryMut<'_, K, V, S, A> { |
4047 | fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { |
4048 | f&mut DebugStruct<'_, '_>.debug_struct("RawOccupiedEntryMut" ) |
4049 | .field("key" , self.key()) |
4050 | .field(name:"value" , self.get()) |
4051 | .finish() |
4052 | } |
4053 | } |
4054 | |
4055 | impl<K, V, S, A: Allocator + Clone> Debug for RawVacantEntryMut<'_, K, V, S, A> { |
4056 | fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { |
4057 | f.debug_struct(name:"RawVacantEntryMut" ).finish() |
4058 | } |
4059 | } |
4060 | |
4061 | impl<K, V, S, A: Allocator + Clone> Debug for RawEntryBuilder<'_, K, V, S, A> { |
4062 | fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { |
4063 | f.debug_struct(name:"RawEntryBuilder" ).finish() |
4064 | } |
4065 | } |
4066 | |
4067 | /// A view into a single entry in a map, which may either be vacant or occupied. |
4068 | /// |
4069 | /// This `enum` is constructed from the [`entry`] method on [`HashMap`]. |
4070 | /// |
4071 | /// [`HashMap`]: struct.HashMap.html |
4072 | /// [`entry`]: struct.HashMap.html#method.entry |
4073 | /// |
4074 | /// # Examples |
4075 | /// |
4076 | /// ``` |
4077 | /// use hashbrown::hash_map::{Entry, HashMap, OccupiedEntry}; |
4078 | /// |
4079 | /// let mut map = HashMap::new(); |
4080 | /// map.extend([("a" , 10), ("b" , 20), ("c" , 30)]); |
4081 | /// assert_eq!(map.len(), 3); |
4082 | /// |
4083 | /// // Existing key (insert) |
4084 | /// let entry: Entry<_, _, _> = map.entry("a" ); |
4085 | /// let _raw_o: OccupiedEntry<_, _, _> = entry.insert(1); |
4086 | /// assert_eq!(map.len(), 3); |
4087 | /// // Nonexistent key (insert) |
4088 | /// map.entry("d" ).insert(4); |
4089 | /// |
4090 | /// // Existing key (or_insert) |
4091 | /// let v = map.entry("b" ).or_insert(2); |
4092 | /// assert_eq!(std::mem::replace(v, 2), 20); |
4093 | /// // Nonexistent key (or_insert) |
4094 | /// map.entry("e" ).or_insert(5); |
4095 | /// |
4096 | /// // Existing key (or_insert_with) |
4097 | /// let v = map.entry("c" ).or_insert_with(|| 3); |
4098 | /// assert_eq!(std::mem::replace(v, 3), 30); |
4099 | /// // Nonexistent key (or_insert_with) |
4100 | /// map.entry("f" ).or_insert_with(|| 6); |
4101 | /// |
4102 | /// println!("Our HashMap: {:?}" , map); |
4103 | /// |
4104 | /// let mut vec: Vec<_> = map.iter().map(|(&k, &v)| (k, v)).collect(); |
4105 | /// // The `Iter` iterator produces items in arbitrary order, so the |
4106 | /// // items must be sorted to test them against a sorted array. |
4107 | /// vec.sort_unstable(); |
4108 | /// assert_eq!(vec, [("a" , 1), ("b" , 2), ("c" , 3), ("d" , 4), ("e" , 5), ("f" , 6)]); |
4109 | /// ``` |
4110 | pub enum Entry<'a, K, V, S, A = Global> |
4111 | where |
4112 | A: Allocator + Clone, |
4113 | { |
4114 | /// An occupied entry. |
4115 | /// |
4116 | /// # Examples |
4117 | /// |
4118 | /// ``` |
4119 | /// use hashbrown::hash_map::{Entry, HashMap}; |
4120 | /// let mut map: HashMap<_, _> = [("a" , 100), ("b" , 200)].into(); |
4121 | /// |
4122 | /// match map.entry("a" ) { |
4123 | /// Entry::Vacant(_) => unreachable!(), |
4124 | /// Entry::Occupied(_) => { } |
4125 | /// } |
4126 | /// ``` |
4127 | Occupied(OccupiedEntry<'a, K, V, S, A>), |
4128 | |
4129 | /// A vacant entry. |
4130 | /// |
4131 | /// # Examples |
4132 | /// |
4133 | /// ``` |
4134 | /// use hashbrown::hash_map::{Entry, HashMap}; |
4135 | /// let mut map: HashMap<&str, i32> = HashMap::new(); |
4136 | /// |
4137 | /// match map.entry("a" ) { |
4138 | /// Entry::Occupied(_) => unreachable!(), |
4139 | /// Entry::Vacant(_) => { } |
4140 | /// } |
4141 | /// ``` |
4142 | Vacant(VacantEntry<'a, K, V, S, A>), |
4143 | } |
4144 | |
4145 | impl<K: Debug, V: Debug, S, A: Allocator + Clone> Debug for Entry<'_, K, V, S, A> { |
4146 | fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { |
4147 | match *self { |
4148 | Entry::Vacant(ref v: &VacantEntry<'_, K, V, S, …>) => f.debug_tuple(name:"Entry" ).field(v).finish(), |
4149 | Entry::Occupied(ref o: &OccupiedEntry<'_, K, V, …, …>) => f.debug_tuple(name:"Entry" ).field(o).finish(), |
4150 | } |
4151 | } |
4152 | } |
4153 | |
4154 | /// A view into an occupied entry in a `HashMap`. |
4155 | /// It is part of the [`Entry`] enum. |
4156 | /// |
4157 | /// [`Entry`]: enum.Entry.html |
4158 | /// |
4159 | /// # Examples |
4160 | /// |
4161 | /// ``` |
4162 | /// use hashbrown::hash_map::{Entry, HashMap, OccupiedEntry}; |
4163 | /// |
4164 | /// let mut map = HashMap::new(); |
4165 | /// map.extend([("a" , 10), ("b" , 20), ("c" , 30)]); |
4166 | /// |
4167 | /// let _entry_o: OccupiedEntry<_, _, _> = map.entry("a" ).insert(100); |
4168 | /// assert_eq!(map.len(), 3); |
4169 | /// |
4170 | /// // Existing key (insert and update) |
4171 | /// match map.entry("a" ) { |
4172 | /// Entry::Vacant(_) => unreachable!(), |
4173 | /// Entry::Occupied(mut view) => { |
4174 | /// assert_eq!(view.get(), &100); |
4175 | /// let v = view.get_mut(); |
4176 | /// *v *= 10; |
4177 | /// assert_eq!(view.insert(1111), 1000); |
4178 | /// } |
4179 | /// } |
4180 | /// |
4181 | /// assert_eq!(map[&"a" ], 1111); |
4182 | /// assert_eq!(map.len(), 3); |
4183 | /// |
4184 | /// // Existing key (take) |
4185 | /// match map.entry("c" ) { |
4186 | /// Entry::Vacant(_) => unreachable!(), |
4187 | /// Entry::Occupied(view) => { |
4188 | /// assert_eq!(view.remove_entry(), ("c" , 30)); |
4189 | /// } |
4190 | /// } |
4191 | /// assert_eq!(map.get(&"c" ), None); |
4192 | /// assert_eq!(map.len(), 2); |
4193 | /// ``` |
4194 | pub struct OccupiedEntry<'a, K, V, S, A: Allocator + Clone = Global> { |
4195 | hash: u64, |
4196 | key: Option<K>, |
4197 | elem: Bucket<(K, V)>, |
4198 | table: &'a mut HashMap<K, V, S, A>, |
4199 | } |
4200 | |
4201 | unsafe impl<K, V, S, A> Send for OccupiedEntry<'_, K, V, S, A> |
4202 | where |
4203 | K: Send, |
4204 | V: Send, |
4205 | S: Send, |
4206 | A: Send + Allocator + Clone, |
4207 | { |
4208 | } |
4209 | unsafe impl<K, V, S, A> Sync for OccupiedEntry<'_, K, V, S, A> |
4210 | where |
4211 | K: Sync, |
4212 | V: Sync, |
4213 | S: Sync, |
4214 | A: Sync + Allocator + Clone, |
4215 | { |
4216 | } |
4217 | |
4218 | impl<K: Debug, V: Debug, S, A: Allocator + Clone> Debug for OccupiedEntry<'_, K, V, S, A> { |
4219 | fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { |
4220 | f&mut DebugStruct<'_, '_>.debug_struct("OccupiedEntry" ) |
4221 | .field("key" , self.key()) |
4222 | .field(name:"value" , self.get()) |
4223 | .finish() |
4224 | } |
4225 | } |
4226 | |
4227 | /// A view into a vacant entry in a `HashMap`. |
4228 | /// It is part of the [`Entry`] enum. |
4229 | /// |
4230 | /// [`Entry`]: enum.Entry.html |
4231 | /// |
4232 | /// # Examples |
4233 | /// |
4234 | /// ``` |
4235 | /// use hashbrown::hash_map::{Entry, HashMap, VacantEntry}; |
4236 | /// |
4237 | /// let mut map = HashMap::<&str, i32>::new(); |
4238 | /// |
4239 | /// let entry_v: VacantEntry<_, _, _> = match map.entry("a" ) { |
4240 | /// Entry::Vacant(view) => view, |
4241 | /// Entry::Occupied(_) => unreachable!(), |
4242 | /// }; |
4243 | /// entry_v.insert(10); |
4244 | /// assert!(map[&"a" ] == 10 && map.len() == 1); |
4245 | /// |
4246 | /// // Nonexistent key (insert and update) |
4247 | /// match map.entry("b" ) { |
4248 | /// Entry::Occupied(_) => unreachable!(), |
4249 | /// Entry::Vacant(view) => { |
4250 | /// let value = view.insert(2); |
4251 | /// assert_eq!(*value, 2); |
4252 | /// *value = 20; |
4253 | /// } |
4254 | /// } |
4255 | /// assert!(map[&"b" ] == 20 && map.len() == 2); |
4256 | /// ``` |
4257 | pub struct VacantEntry<'a, K, V, S, A: Allocator + Clone = Global> { |
4258 | hash: u64, |
4259 | key: K, |
4260 | table: &'a mut HashMap<K, V, S, A>, |
4261 | } |
4262 | |
4263 | impl<K: Debug, V, S, A: Allocator + Clone> Debug for VacantEntry<'_, K, V, S, A> { |
4264 | fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { |
4265 | f.debug_tuple(name:"VacantEntry" ).field(self.key()).finish() |
4266 | } |
4267 | } |
4268 | |
4269 | /// A view into a single entry in a map, which may either be vacant or occupied, |
4270 | /// with any borrowed form of the map's key type. |
4271 | /// |
4272 | /// |
4273 | /// This `enum` is constructed from the [`entry_ref`] method on [`HashMap`]. |
4274 | /// |
4275 | /// [`Hash`] and [`Eq`] on the borrowed form of the map's key type *must* match those |
4276 | /// for the key type. It also require that key may be constructed from the borrowed |
4277 | /// form through the [`From`] trait. |
4278 | /// |
4279 | /// [`HashMap`]: struct.HashMap.html |
4280 | /// [`entry_ref`]: struct.HashMap.html#method.entry_ref |
4281 | /// [`Eq`]: https://doc.rust-lang.org/std/cmp/trait.Eq.html |
4282 | /// [`Hash`]: https://doc.rust-lang.org/std/hash/trait.Hash.html |
4283 | /// [`From`]: https://doc.rust-lang.org/std/convert/trait.From.html |
4284 | /// |
4285 | /// # Examples |
4286 | /// |
4287 | /// ``` |
4288 | /// use hashbrown::hash_map::{EntryRef, HashMap, OccupiedEntryRef}; |
4289 | /// |
4290 | /// let mut map = HashMap::new(); |
4291 | /// map.extend([("a" .to_owned(), 10), ("b" .into(), 20), ("c" .into(), 30)]); |
4292 | /// assert_eq!(map.len(), 3); |
4293 | /// |
4294 | /// // Existing key (insert) |
4295 | /// let key = String::from("a" ); |
4296 | /// let entry: EntryRef<_, _, _, _> = map.entry_ref(&key); |
4297 | /// let _raw_o: OccupiedEntryRef<_, _, _, _> = entry.insert(1); |
4298 | /// assert_eq!(map.len(), 3); |
4299 | /// // Nonexistent key (insert) |
4300 | /// map.entry_ref("d" ).insert(4); |
4301 | /// |
4302 | /// // Existing key (or_insert) |
4303 | /// let v = map.entry_ref("b" ).or_insert(2); |
4304 | /// assert_eq!(std::mem::replace(v, 2), 20); |
4305 | /// // Nonexistent key (or_insert) |
4306 | /// map.entry_ref("e" ).or_insert(5); |
4307 | /// |
4308 | /// // Existing key (or_insert_with) |
4309 | /// let v = map.entry_ref("c" ).or_insert_with(|| 3); |
4310 | /// assert_eq!(std::mem::replace(v, 3), 30); |
4311 | /// // Nonexistent key (or_insert_with) |
4312 | /// map.entry_ref("f" ).or_insert_with(|| 6); |
4313 | /// |
4314 | /// println!("Our HashMap: {:?}" , map); |
4315 | /// |
4316 | /// for (key, value) in ["a" , "b" , "c" , "d" , "e" , "f" ].into_iter().zip(1..=6) { |
4317 | /// assert_eq!(map[key], value) |
4318 | /// } |
4319 | /// assert_eq!(map.len(), 6); |
4320 | /// ``` |
4321 | pub enum EntryRef<'a, 'b, K, Q: ?Sized, V, S, A = Global> |
4322 | where |
4323 | A: Allocator + Clone, |
4324 | { |
4325 | /// An occupied entry. |
4326 | /// |
4327 | /// # Examples |
4328 | /// |
4329 | /// ``` |
4330 | /// use hashbrown::hash_map::{EntryRef, HashMap}; |
4331 | /// let mut map: HashMap<_, _> = [("a" .to_owned(), 100), ("b" .into(), 200)].into(); |
4332 | /// |
4333 | /// match map.entry_ref("a" ) { |
4334 | /// EntryRef::Vacant(_) => unreachable!(), |
4335 | /// EntryRef::Occupied(_) => { } |
4336 | /// } |
4337 | /// ``` |
4338 | Occupied(OccupiedEntryRef<'a, 'b, K, Q, V, S, A>), |
4339 | |
4340 | /// A vacant entry. |
4341 | /// |
4342 | /// # Examples |
4343 | /// |
4344 | /// ``` |
4345 | /// use hashbrown::hash_map::{EntryRef, HashMap}; |
4346 | /// let mut map: HashMap<String, i32> = HashMap::new(); |
4347 | /// |
4348 | /// match map.entry_ref("a" ) { |
4349 | /// EntryRef::Occupied(_) => unreachable!(), |
4350 | /// EntryRef::Vacant(_) => { } |
4351 | /// } |
4352 | /// ``` |
4353 | Vacant(VacantEntryRef<'a, 'b, K, Q, V, S, A>), |
4354 | } |
4355 | |
4356 | impl<K: Borrow<Q>, Q: ?Sized + Debug, V: Debug, S, A: Allocator + Clone> Debug |
4357 | for EntryRef<'_, '_, K, Q, V, S, A> |
4358 | { |
4359 | fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { |
4360 | match *self { |
4361 | EntryRef::Vacant(ref v: &VacantEntryRef<'_, '_, K, …, …, …, …>) => f.debug_tuple(name:"EntryRef" ).field(v).finish(), |
4362 | EntryRef::Occupied(ref o: &OccupiedEntryRef<'_, '_, …, …, …, …, …>) => f.debug_tuple(name:"EntryRef" ).field(o).finish(), |
4363 | } |
4364 | } |
4365 | } |
4366 | |
4367 | enum KeyOrRef<'a, K, Q: ?Sized> { |
4368 | Borrowed(&'a Q), |
4369 | Owned(K), |
4370 | } |
4371 | |
4372 | impl<'a, K, Q: ?Sized> KeyOrRef<'a, K, Q> { |
4373 | fn into_owned(self) -> K |
4374 | where |
4375 | K: From<&'a Q>, |
4376 | { |
4377 | match self { |
4378 | Self::Borrowed(borrowed: &Q) => borrowed.into(), |
4379 | Self::Owned(owned: K) => owned, |
4380 | } |
4381 | } |
4382 | } |
4383 | |
4384 | impl<'a, K: Borrow<Q>, Q: ?Sized> AsRef<Q> for KeyOrRef<'a, K, Q> { |
4385 | fn as_ref(&self) -> &Q { |
4386 | match self { |
4387 | Self::Borrowed(borrowed: &&Q) => borrowed, |
4388 | Self::Owned(owned: &K) => owned.borrow(), |
4389 | } |
4390 | } |
4391 | } |
4392 | |
4393 | /// A view into an occupied entry in a `HashMap`. |
4394 | /// It is part of the [`EntryRef`] enum. |
4395 | /// |
4396 | /// [`EntryRef`]: enum.EntryRef.html |
4397 | /// |
4398 | /// # Examples |
4399 | /// |
4400 | /// ``` |
4401 | /// use hashbrown::hash_map::{EntryRef, HashMap, OccupiedEntryRef}; |
4402 | /// |
4403 | /// let mut map = HashMap::new(); |
4404 | /// map.extend([("a" .to_owned(), 10), ("b" .into(), 20), ("c" .into(), 30)]); |
4405 | /// |
4406 | /// let key = String::from("a" ); |
4407 | /// let _entry_o: OccupiedEntryRef<_, _, _, _> = map.entry_ref(&key).insert(100); |
4408 | /// assert_eq!(map.len(), 3); |
4409 | /// |
4410 | /// // Existing key (insert and update) |
4411 | /// match map.entry_ref("a" ) { |
4412 | /// EntryRef::Vacant(_) => unreachable!(), |
4413 | /// EntryRef::Occupied(mut view) => { |
4414 | /// assert_eq!(view.get(), &100); |
4415 | /// let v = view.get_mut(); |
4416 | /// *v *= 10; |
4417 | /// assert_eq!(view.insert(1111), 1000); |
4418 | /// } |
4419 | /// } |
4420 | /// |
4421 | /// assert_eq!(map["a" ], 1111); |
4422 | /// assert_eq!(map.len(), 3); |
4423 | /// |
4424 | /// // Existing key (take) |
4425 | /// match map.entry_ref("c" ) { |
4426 | /// EntryRef::Vacant(_) => unreachable!(), |
4427 | /// EntryRef::Occupied(view) => { |
4428 | /// assert_eq!(view.remove_entry(), ("c" .to_owned(), 30)); |
4429 | /// } |
4430 | /// } |
4431 | /// assert_eq!(map.get("c" ), None); |
4432 | /// assert_eq!(map.len(), 2); |
4433 | /// ``` |
4434 | pub struct OccupiedEntryRef<'a, 'b, K, Q: ?Sized, V, S, A: Allocator + Clone = Global> { |
4435 | hash: u64, |
4436 | key: Option<KeyOrRef<'b, K, Q>>, |
4437 | elem: Bucket<(K, V)>, |
4438 | table: &'a mut HashMap<K, V, S, A>, |
4439 | } |
4440 | |
4441 | unsafe impl<'a, 'b, K, Q, V, S, A> Send for OccupiedEntryRef<'a, 'b, K, Q, V, S, A> |
4442 | where |
4443 | K: Send, |
4444 | Q: Sync + ?Sized, |
4445 | V: Send, |
4446 | S: Send, |
4447 | A: Send + Allocator + Clone, |
4448 | { |
4449 | } |
4450 | unsafe impl<'a, 'b, K, Q, V, S, A> Sync for OccupiedEntryRef<'a, 'b, K, Q, V, S, A> |
4451 | where |
4452 | K: Sync, |
4453 | Q: Sync + ?Sized, |
4454 | V: Sync, |
4455 | S: Sync, |
4456 | A: Sync + Allocator + Clone, |
4457 | { |
4458 | } |
4459 | |
4460 | impl<K: Borrow<Q>, Q: ?Sized + Debug, V: Debug, S, A: Allocator + Clone> Debug |
4461 | for OccupiedEntryRef<'_, '_, K, Q, V, S, A> |
4462 | { |
4463 | fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { |
4464 | f&mut DebugStruct<'_, '_>.debug_struct("OccupiedEntryRef" ) |
4465 | .field("key" , &self.key()) |
4466 | .field(name:"value" , &self.get()) |
4467 | .finish() |
4468 | } |
4469 | } |
4470 | |
4471 | /// A view into a vacant entry in a `HashMap`. |
4472 | /// It is part of the [`EntryRef`] enum. |
4473 | /// |
4474 | /// [`EntryRef`]: enum.EntryRef.html |
4475 | /// |
4476 | /// # Examples |
4477 | /// |
4478 | /// ``` |
4479 | /// use hashbrown::hash_map::{EntryRef, HashMap, VacantEntryRef}; |
4480 | /// |
4481 | /// let mut map = HashMap::<String, i32>::new(); |
4482 | /// |
4483 | /// let entry_v: VacantEntryRef<_, _, _, _> = match map.entry_ref("a" ) { |
4484 | /// EntryRef::Vacant(view) => view, |
4485 | /// EntryRef::Occupied(_) => unreachable!(), |
4486 | /// }; |
4487 | /// entry_v.insert(10); |
4488 | /// assert!(map["a" ] == 10 && map.len() == 1); |
4489 | /// |
4490 | /// // Nonexistent key (insert and update) |
4491 | /// match map.entry_ref("b" ) { |
4492 | /// EntryRef::Occupied(_) => unreachable!(), |
4493 | /// EntryRef::Vacant(view) => { |
4494 | /// let value = view.insert(2); |
4495 | /// assert_eq!(*value, 2); |
4496 | /// *value = 20; |
4497 | /// } |
4498 | /// } |
4499 | /// assert!(map["b" ] == 20 && map.len() == 2); |
4500 | /// ``` |
4501 | pub struct VacantEntryRef<'a, 'b, K, Q: ?Sized, V, S, A: Allocator + Clone = Global> { |
4502 | hash: u64, |
4503 | key: KeyOrRef<'b, K, Q>, |
4504 | table: &'a mut HashMap<K, V, S, A>, |
4505 | } |
4506 | |
4507 | impl<K: Borrow<Q>, Q: ?Sized + Debug, V, S, A: Allocator + Clone> Debug |
4508 | for VacantEntryRef<'_, '_, K, Q, V, S, A> |
4509 | { |
4510 | fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { |
4511 | f.debug_tuple(name:"VacantEntryRef" ).field(&self.key()).finish() |
4512 | } |
4513 | } |
4514 | |
4515 | /// The error returned by [`try_insert`](HashMap::try_insert) when the key already exists. |
4516 | /// |
4517 | /// Contains the occupied entry, and the value that was not inserted. |
4518 | /// |
4519 | /// # Examples |
4520 | /// |
4521 | /// ``` |
4522 | /// use hashbrown::hash_map::{HashMap, OccupiedError}; |
4523 | /// |
4524 | /// let mut map: HashMap<_, _> = [("a" , 10), ("b" , 20)].into(); |
4525 | /// |
4526 | /// // try_insert method returns mutable reference to the value if keys are vacant, |
4527 | /// // but if the map did have key present, nothing is updated, and the provided |
4528 | /// // value is returned inside `Err(_)` variant |
4529 | /// match map.try_insert("a" , 100) { |
4530 | /// Err(OccupiedError { mut entry, value }) => { |
4531 | /// assert_eq!(entry.key(), &"a" ); |
4532 | /// assert_eq!(value, 100); |
4533 | /// assert_eq!(entry.insert(100), 10) |
4534 | /// } |
4535 | /// _ => unreachable!(), |
4536 | /// } |
4537 | /// assert_eq!(map[&"a" ], 100); |
4538 | /// ``` |
4539 | pub struct OccupiedError<'a, K, V, S, A: Allocator + Clone = Global> { |
4540 | /// The entry in the map that was already occupied. |
4541 | pub entry: OccupiedEntry<'a, K, V, S, A>, |
4542 | /// The value which was not inserted, because the entry was already occupied. |
4543 | pub value: V, |
4544 | } |
4545 | |
4546 | impl<K: Debug, V: Debug, S, A: Allocator + Clone> Debug for OccupiedError<'_, K, V, S, A> { |
4547 | fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { |
4548 | f&mut DebugStruct<'_, '_>.debug_struct("OccupiedError" ) |
4549 | .field("key" , self.entry.key()) |
4550 | .field("old_value" , self.entry.get()) |
4551 | .field(name:"new_value" , &self.value) |
4552 | .finish() |
4553 | } |
4554 | } |
4555 | |
4556 | impl<'a, K: Debug, V: Debug, S, A: Allocator + Clone> fmt::Display |
4557 | for OccupiedError<'a, K, V, S, A> |
4558 | { |
4559 | fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { |
4560 | write!( |
4561 | f, |
4562 | "failed to insert {:?}, key {:?} already exists with value {:?}" , |
4563 | self.value, |
4564 | self.entry.key(), |
4565 | self.entry.get(), |
4566 | ) |
4567 | } |
4568 | } |
4569 | |
4570 | impl<'a, K, V, S, A: Allocator + Clone> IntoIterator for &'a HashMap<K, V, S, A> { |
4571 | type Item = (&'a K, &'a V); |
4572 | type IntoIter = Iter<'a, K, V>; |
4573 | |
4574 | /// Creates an iterator over the entries of a `HashMap` in arbitrary order. |
4575 | /// The iterator element type is `(&'a K, &'a V)`. |
4576 | /// |
4577 | /// Return the same `Iter` struct as by the [`iter`] method on [`HashMap`]. |
4578 | /// |
4579 | /// [`iter`]: struct.HashMap.html#method.iter |
4580 | /// [`HashMap`]: struct.HashMap.html |
4581 | /// |
4582 | /// # Examples |
4583 | /// |
4584 | /// ``` |
4585 | /// use hashbrown::HashMap; |
4586 | /// let map_one: HashMap<_, _> = [(1, "a" ), (2, "b" ), (3, "c" )].into(); |
4587 | /// let mut map_two = HashMap::new(); |
4588 | /// |
4589 | /// for (key, value) in &map_one { |
4590 | /// println!("Key: {}, Value: {}" , key, value); |
4591 | /// map_two.insert_unique_unchecked(*key, *value); |
4592 | /// } |
4593 | /// |
4594 | /// assert_eq!(map_one, map_two); |
4595 | /// ``` |
4596 | #[cfg_attr (feature = "inline-more" , inline)] |
4597 | fn into_iter(self) -> Iter<'a, K, V> { |
4598 | self.iter() |
4599 | } |
4600 | } |
4601 | |
4602 | impl<'a, K, V, S, A: Allocator + Clone> IntoIterator for &'a mut HashMap<K, V, S, A> { |
4603 | type Item = (&'a K, &'a mut V); |
4604 | type IntoIter = IterMut<'a, K, V>; |
4605 | |
4606 | /// Creates an iterator over the entries of a `HashMap` in arbitrary order |
4607 | /// with mutable references to the values. The iterator element type is |
4608 | /// `(&'a K, &'a mut V)`. |
4609 | /// |
4610 | /// Return the same `IterMut` struct as by the [`iter_mut`] method on |
4611 | /// [`HashMap`]. |
4612 | /// |
4613 | /// [`iter_mut`]: struct.HashMap.html#method.iter_mut |
4614 | /// [`HashMap`]: struct.HashMap.html |
4615 | /// |
4616 | /// # Examples |
4617 | /// |
4618 | /// ``` |
4619 | /// use hashbrown::HashMap; |
4620 | /// let mut map: HashMap<_, _> = [("a" , 1), ("b" , 2), ("c" , 3)].into(); |
4621 | /// |
4622 | /// for (key, value) in &mut map { |
4623 | /// println!("Key: {}, Value: {}" , key, value); |
4624 | /// *value *= 2; |
4625 | /// } |
4626 | /// |
4627 | /// let mut vec = map.iter().collect::<Vec<_>>(); |
4628 | /// // The `Iter` iterator produces items in arbitrary order, so the |
4629 | /// // items must be sorted to test them against a sorted array. |
4630 | /// vec.sort_unstable(); |
4631 | /// assert_eq!(vec, [(&"a" , &2), (&"b" , &4), (&"c" , &6)]); |
4632 | /// ``` |
4633 | #[cfg_attr (feature = "inline-more" , inline)] |
4634 | fn into_iter(self) -> IterMut<'a, K, V> { |
4635 | self.iter_mut() |
4636 | } |
4637 | } |
4638 | |
4639 | impl<K, V, S, A: Allocator + Clone> IntoIterator for HashMap<K, V, S, A> { |
4640 | type Item = (K, V); |
4641 | type IntoIter = IntoIter<K, V, A>; |
4642 | |
4643 | /// Creates a consuming iterator, that is, one that moves each key-value |
4644 | /// pair out of the map in arbitrary order. The map cannot be used after |
4645 | /// calling this. |
4646 | /// |
4647 | /// # Examples |
4648 | /// |
4649 | /// ``` |
4650 | /// use hashbrown::HashMap; |
4651 | /// |
4652 | /// let map: HashMap<_, _> = [("a" , 1), ("b" , 2), ("c" , 3)].into(); |
4653 | /// |
4654 | /// // Not possible with .iter() |
4655 | /// let mut vec: Vec<(&str, i32)> = map.into_iter().collect(); |
4656 | /// // The `IntoIter` iterator produces items in arbitrary order, so |
4657 | /// // the items must be sorted to test them against a sorted array. |
4658 | /// vec.sort_unstable(); |
4659 | /// assert_eq!(vec, [("a" , 1), ("b" , 2), ("c" , 3)]); |
4660 | /// ``` |
4661 | #[cfg_attr (feature = "inline-more" , inline)] |
4662 | fn into_iter(self) -> IntoIter<K, V, A> { |
4663 | IntoIter { |
4664 | inner: self.table.into_iter(), |
4665 | } |
4666 | } |
4667 | } |
4668 | |
4669 | impl<'a, K, V> Iterator for Iter<'a, K, V> { |
4670 | type Item = (&'a K, &'a V); |
4671 | |
4672 | #[cfg_attr (feature = "inline-more" , inline)] |
4673 | fn next(&mut self) -> Option<(&'a K, &'a V)> { |
4674 | // Avoid `Option::map` because it bloats LLVM IR. |
4675 | match self.inner.next() { |
4676 | Some(x: Bucket<(K, V)>) => unsafe { |
4677 | let r: &(K, V) = x.as_ref(); |
4678 | Some((&r.0, &r.1)) |
4679 | }, |
4680 | None => None, |
4681 | } |
4682 | } |
4683 | #[cfg_attr (feature = "inline-more" , inline)] |
4684 | fn size_hint(&self) -> (usize, Option<usize>) { |
4685 | self.inner.size_hint() |
4686 | } |
4687 | } |
4688 | impl<K, V> ExactSizeIterator for Iter<'_, K, V> { |
4689 | #[cfg_attr (feature = "inline-more" , inline)] |
4690 | fn len(&self) -> usize { |
4691 | self.inner.len() |
4692 | } |
4693 | } |
4694 | |
4695 | impl<K, V> FusedIterator for Iter<'_, K, V> {} |
4696 | |
4697 | impl<'a, K, V> Iterator for IterMut<'a, K, V> { |
4698 | type Item = (&'a K, &'a mut V); |
4699 | |
4700 | #[cfg_attr (feature = "inline-more" , inline)] |
4701 | fn next(&mut self) -> Option<(&'a K, &'a mut V)> { |
4702 | // Avoid `Option::map` because it bloats LLVM IR. |
4703 | match self.inner.next() { |
4704 | Some(x: Bucket<(K, V)>) => unsafe { |
4705 | let r: &mut (K, V) = x.as_mut(); |
4706 | Some((&r.0, &mut r.1)) |
4707 | }, |
4708 | None => None, |
4709 | } |
4710 | } |
4711 | #[cfg_attr (feature = "inline-more" , inline)] |
4712 | fn size_hint(&self) -> (usize, Option<usize>) { |
4713 | self.inner.size_hint() |
4714 | } |
4715 | } |
4716 | impl<K, V> ExactSizeIterator for IterMut<'_, K, V> { |
4717 | #[cfg_attr (feature = "inline-more" , inline)] |
4718 | fn len(&self) -> usize { |
4719 | self.inner.len() |
4720 | } |
4721 | } |
4722 | impl<K, V> FusedIterator for IterMut<'_, K, V> {} |
4723 | |
4724 | impl<K, V> fmt::Debug for IterMut<'_, K, V> |
4725 | where |
4726 | K: fmt::Debug, |
4727 | V: fmt::Debug, |
4728 | { |
4729 | fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { |
4730 | f.debug_list().entries(self.iter()).finish() |
4731 | } |
4732 | } |
4733 | |
4734 | impl<K, V, A: Allocator + Clone> Iterator for IntoIter<K, V, A> { |
4735 | type Item = (K, V); |
4736 | |
4737 | #[cfg_attr (feature = "inline-more" , inline)] |
4738 | fn next(&mut self) -> Option<(K, V)> { |
4739 | self.inner.next() |
4740 | } |
4741 | #[cfg_attr (feature = "inline-more" , inline)] |
4742 | fn size_hint(&self) -> (usize, Option<usize>) { |
4743 | self.inner.size_hint() |
4744 | } |
4745 | } |
4746 | impl<K, V, A: Allocator + Clone> ExactSizeIterator for IntoIter<K, V, A> { |
4747 | #[cfg_attr (feature = "inline-more" , inline)] |
4748 | fn len(&self) -> usize { |
4749 | self.inner.len() |
4750 | } |
4751 | } |
4752 | impl<K, V, A: Allocator + Clone> FusedIterator for IntoIter<K, V, A> {} |
4753 | |
4754 | impl<K: Debug, V: Debug, A: Allocator + Clone> fmt::Debug for IntoIter<K, V, A> { |
4755 | fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { |
4756 | f.debug_list().entries(self.iter()).finish() |
4757 | } |
4758 | } |
4759 | |
4760 | impl<'a, K, V> Iterator for Keys<'a, K, V> { |
4761 | type Item = &'a K; |
4762 | |
4763 | #[cfg_attr (feature = "inline-more" , inline)] |
4764 | fn next(&mut self) -> Option<&'a K> { |
4765 | // Avoid `Option::map` because it bloats LLVM IR. |
4766 | match self.inner.next() { |
4767 | Some((k: &K, _)) => Some(k), |
4768 | None => None, |
4769 | } |
4770 | } |
4771 | #[cfg_attr (feature = "inline-more" , inline)] |
4772 | fn size_hint(&self) -> (usize, Option<usize>) { |
4773 | self.inner.size_hint() |
4774 | } |
4775 | } |
4776 | impl<K, V> ExactSizeIterator for Keys<'_, K, V> { |
4777 | #[cfg_attr (feature = "inline-more" , inline)] |
4778 | fn len(&self) -> usize { |
4779 | self.inner.len() |
4780 | } |
4781 | } |
4782 | impl<K, V> FusedIterator for Keys<'_, K, V> {} |
4783 | |
4784 | impl<'a, K, V> Iterator for Values<'a, K, V> { |
4785 | type Item = &'a V; |
4786 | |
4787 | #[cfg_attr (feature = "inline-more" , inline)] |
4788 | fn next(&mut self) -> Option<&'a V> { |
4789 | // Avoid `Option::map` because it bloats LLVM IR. |
4790 | match self.inner.next() { |
4791 | Some((_, v: &V)) => Some(v), |
4792 | None => None, |
4793 | } |
4794 | } |
4795 | #[cfg_attr (feature = "inline-more" , inline)] |
4796 | fn size_hint(&self) -> (usize, Option<usize>) { |
4797 | self.inner.size_hint() |
4798 | } |
4799 | } |
4800 | impl<K, V> ExactSizeIterator for Values<'_, K, V> { |
4801 | #[cfg_attr (feature = "inline-more" , inline)] |
4802 | fn len(&self) -> usize { |
4803 | self.inner.len() |
4804 | } |
4805 | } |
4806 | impl<K, V> FusedIterator for Values<'_, K, V> {} |
4807 | |
4808 | impl<'a, K, V> Iterator for ValuesMut<'a, K, V> { |
4809 | type Item = &'a mut V; |
4810 | |
4811 | #[cfg_attr (feature = "inline-more" , inline)] |
4812 | fn next(&mut self) -> Option<&'a mut V> { |
4813 | // Avoid `Option::map` because it bloats LLVM IR. |
4814 | match self.inner.next() { |
4815 | Some((_, v: &mut V)) => Some(v), |
4816 | None => None, |
4817 | } |
4818 | } |
4819 | #[cfg_attr (feature = "inline-more" , inline)] |
4820 | fn size_hint(&self) -> (usize, Option<usize>) { |
4821 | self.inner.size_hint() |
4822 | } |
4823 | } |
4824 | impl<K, V> ExactSizeIterator for ValuesMut<'_, K, V> { |
4825 | #[cfg_attr (feature = "inline-more" , inline)] |
4826 | fn len(&self) -> usize { |
4827 | self.inner.len() |
4828 | } |
4829 | } |
4830 | impl<K, V> FusedIterator for ValuesMut<'_, K, V> {} |
4831 | |
4832 | impl<K, V: Debug> fmt::Debug for ValuesMut<'_, K, V> { |
4833 | fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { |
4834 | f&mut DebugList<'_, '_>.debug_list() |
4835 | .entries(self.inner.iter().map(|(_, val: &V)| val)) |
4836 | .finish() |
4837 | } |
4838 | } |
4839 | |
4840 | impl<'a, K, V, A: Allocator + Clone> Iterator for Drain<'a, K, V, A> { |
4841 | type Item = (K, V); |
4842 | |
4843 | #[cfg_attr (feature = "inline-more" , inline)] |
4844 | fn next(&mut self) -> Option<(K, V)> { |
4845 | self.inner.next() |
4846 | } |
4847 | #[cfg_attr (feature = "inline-more" , inline)] |
4848 | fn size_hint(&self) -> (usize, Option<usize>) { |
4849 | self.inner.size_hint() |
4850 | } |
4851 | } |
4852 | impl<K, V, A: Allocator + Clone> ExactSizeIterator for Drain<'_, K, V, A> { |
4853 | #[cfg_attr (feature = "inline-more" , inline)] |
4854 | fn len(&self) -> usize { |
4855 | self.inner.len() |
4856 | } |
4857 | } |
4858 | impl<K, V, A: Allocator + Clone> FusedIterator for Drain<'_, K, V, A> {} |
4859 | |
4860 | impl<K, V, A> fmt::Debug for Drain<'_, K, V, A> |
4861 | where |
4862 | K: fmt::Debug, |
4863 | V: fmt::Debug, |
4864 | A: Allocator + Clone, |
4865 | { |
4866 | fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { |
4867 | f.debug_list().entries(self.iter()).finish() |
4868 | } |
4869 | } |
4870 | |
4871 | impl<'a, K, V, S, A: Allocator + Clone> Entry<'a, K, V, S, A> { |
4872 | /// Sets the value of the entry, and returns an OccupiedEntry. |
4873 | /// |
4874 | /// # Examples |
4875 | /// |
4876 | /// ``` |
4877 | /// use hashbrown::HashMap; |
4878 | /// |
4879 | /// let mut map: HashMap<&str, u32> = HashMap::new(); |
4880 | /// let entry = map.entry("horseyland" ).insert(37); |
4881 | /// |
4882 | /// assert_eq!(entry.key(), &"horseyland" ); |
4883 | /// ``` |
4884 | #[cfg_attr (feature = "inline-more" , inline)] |
4885 | pub fn insert(self, value: V) -> OccupiedEntry<'a, K, V, S, A> |
4886 | where |
4887 | K: Hash, |
4888 | S: BuildHasher, |
4889 | { |
4890 | match self { |
4891 | Entry::Occupied(mut entry) => { |
4892 | entry.insert(value); |
4893 | entry |
4894 | } |
4895 | Entry::Vacant(entry) => entry.insert_entry(value), |
4896 | } |
4897 | } |
4898 | |
4899 | /// Ensures a value is in the entry by inserting the default if empty, and returns |
4900 | /// a mutable reference to the value in the entry. |
4901 | /// |
4902 | /// # Examples |
4903 | /// |
4904 | /// ``` |
4905 | /// use hashbrown::HashMap; |
4906 | /// |
4907 | /// let mut map: HashMap<&str, u32> = HashMap::new(); |
4908 | /// |
4909 | /// // nonexistent key |
4910 | /// map.entry("poneyland" ).or_insert(3); |
4911 | /// assert_eq!(map["poneyland" ], 3); |
4912 | /// |
4913 | /// // existing key |
4914 | /// *map.entry("poneyland" ).or_insert(10) *= 2; |
4915 | /// assert_eq!(map["poneyland" ], 6); |
4916 | /// ``` |
4917 | #[cfg_attr (feature = "inline-more" , inline)] |
4918 | pub fn or_insert(self, default: V) -> &'a mut V |
4919 | where |
4920 | K: Hash, |
4921 | S: BuildHasher, |
4922 | { |
4923 | match self { |
4924 | Entry::Occupied(entry) => entry.into_mut(), |
4925 | Entry::Vacant(entry) => entry.insert(default), |
4926 | } |
4927 | } |
4928 | |
4929 | /// Ensures a value is in the entry by inserting the result of the default function if empty, |
4930 | /// and returns a mutable reference to the value in the entry. |
4931 | /// |
4932 | /// # Examples |
4933 | /// |
4934 | /// ``` |
4935 | /// use hashbrown::HashMap; |
4936 | /// |
4937 | /// let mut map: HashMap<&str, u32> = HashMap::new(); |
4938 | /// |
4939 | /// // nonexistent key |
4940 | /// map.entry("poneyland" ).or_insert_with(|| 3); |
4941 | /// assert_eq!(map["poneyland" ], 3); |
4942 | /// |
4943 | /// // existing key |
4944 | /// *map.entry("poneyland" ).or_insert_with(|| 10) *= 2; |
4945 | /// assert_eq!(map["poneyland" ], 6); |
4946 | /// ``` |
4947 | #[cfg_attr (feature = "inline-more" , inline)] |
4948 | pub fn or_insert_with<F: FnOnce() -> V>(self, default: F) -> &'a mut V |
4949 | where |
4950 | K: Hash, |
4951 | S: BuildHasher, |
4952 | { |
4953 | match self { |
4954 | Entry::Occupied(entry) => entry.into_mut(), |
4955 | Entry::Vacant(entry) => entry.insert(default()), |
4956 | } |
4957 | } |
4958 | |
4959 | /// Ensures a value is in the entry by inserting, if empty, the result of the default function. |
4960 | /// This method allows for generating key-derived values for insertion by providing the default |
4961 | /// function a reference to the key that was moved during the `.entry(key)` method call. |
4962 | /// |
4963 | /// The reference to the moved key is provided so that cloning or copying the key is |
4964 | /// unnecessary, unlike with `.or_insert_with(|| ... )`. |
4965 | /// |
4966 | /// # Examples |
4967 | /// |
4968 | /// ``` |
4969 | /// use hashbrown::HashMap; |
4970 | /// |
4971 | /// let mut map: HashMap<&str, usize> = HashMap::new(); |
4972 | /// |
4973 | /// // nonexistent key |
4974 | /// map.entry("poneyland" ).or_insert_with_key(|key| key.chars().count()); |
4975 | /// assert_eq!(map["poneyland" ], 9); |
4976 | /// |
4977 | /// // existing key |
4978 | /// *map.entry("poneyland" ).or_insert_with_key(|key| key.chars().count() * 10) *= 2; |
4979 | /// assert_eq!(map["poneyland" ], 18); |
4980 | /// ``` |
4981 | #[cfg_attr (feature = "inline-more" , inline)] |
4982 | pub fn or_insert_with_key<F: FnOnce(&K) -> V>(self, default: F) -> &'a mut V |
4983 | where |
4984 | K: Hash, |
4985 | S: BuildHasher, |
4986 | { |
4987 | match self { |
4988 | Entry::Occupied(entry) => entry.into_mut(), |
4989 | Entry::Vacant(entry) => { |
4990 | let value = default(entry.key()); |
4991 | entry.insert(value) |
4992 | } |
4993 | } |
4994 | } |
4995 | |
4996 | /// Returns a reference to this entry's key. |
4997 | /// |
4998 | /// # Examples |
4999 | /// |
5000 | /// ``` |
5001 | /// use hashbrown::HashMap; |
5002 | /// |
5003 | /// let mut map: HashMap<&str, u32> = HashMap::new(); |
5004 | /// map.entry("poneyland" ).or_insert(3); |
5005 | /// // existing key |
5006 | /// assert_eq!(map.entry("poneyland" ).key(), &"poneyland" ); |
5007 | /// // nonexistent key |
5008 | /// assert_eq!(map.entry("horseland" ).key(), &"horseland" ); |
5009 | /// ``` |
5010 | #[cfg_attr (feature = "inline-more" , inline)] |
5011 | pub fn key(&self) -> &K { |
5012 | match *self { |
5013 | Entry::Occupied(ref entry) => entry.key(), |
5014 | Entry::Vacant(ref entry) => entry.key(), |
5015 | } |
5016 | } |
5017 | |
5018 | /// Provides in-place mutable access to an occupied entry before any |
5019 | /// potential inserts into the map. |
5020 | /// |
5021 | /// # Examples |
5022 | /// |
5023 | /// ``` |
5024 | /// use hashbrown::HashMap; |
5025 | /// |
5026 | /// let mut map: HashMap<&str, u32> = HashMap::new(); |
5027 | /// |
5028 | /// map.entry("poneyland" ) |
5029 | /// .and_modify(|e| { *e += 1 }) |
5030 | /// .or_insert(42); |
5031 | /// assert_eq!(map["poneyland" ], 42); |
5032 | /// |
5033 | /// map.entry("poneyland" ) |
5034 | /// .and_modify(|e| { *e += 1 }) |
5035 | /// .or_insert(42); |
5036 | /// assert_eq!(map["poneyland" ], 43); |
5037 | /// ``` |
5038 | #[cfg_attr (feature = "inline-more" , inline)] |
5039 | pub fn and_modify<F>(self, f: F) -> Self |
5040 | where |
5041 | F: FnOnce(&mut V), |
5042 | { |
5043 | match self { |
5044 | Entry::Occupied(mut entry) => { |
5045 | f(entry.get_mut()); |
5046 | Entry::Occupied(entry) |
5047 | } |
5048 | Entry::Vacant(entry) => Entry::Vacant(entry), |
5049 | } |
5050 | } |
5051 | |
5052 | /// Provides shared access to the key and owned access to the value of |
5053 | /// an occupied entry and allows to replace or remove it based on the |
5054 | /// value of the returned option. |
5055 | /// |
5056 | /// # Examples |
5057 | /// |
5058 | /// ``` |
5059 | /// use hashbrown::HashMap; |
5060 | /// use hashbrown::hash_map::Entry; |
5061 | /// |
5062 | /// let mut map: HashMap<&str, u32> = HashMap::new(); |
5063 | /// |
5064 | /// let entry = map |
5065 | /// .entry("poneyland" ) |
5066 | /// .and_replace_entry_with(|_k, _v| panic!()); |
5067 | /// |
5068 | /// match entry { |
5069 | /// Entry::Vacant(e) => { |
5070 | /// assert_eq!(e.key(), &"poneyland" ); |
5071 | /// } |
5072 | /// Entry::Occupied(_) => panic!(), |
5073 | /// } |
5074 | /// |
5075 | /// map.insert("poneyland" , 42); |
5076 | /// |
5077 | /// let entry = map |
5078 | /// .entry("poneyland" ) |
5079 | /// .and_replace_entry_with(|k, v| { |
5080 | /// assert_eq!(k, &"poneyland" ); |
5081 | /// assert_eq!(v, 42); |
5082 | /// Some(v + 1) |
5083 | /// }); |
5084 | /// |
5085 | /// match entry { |
5086 | /// Entry::Occupied(e) => { |
5087 | /// assert_eq!(e.key(), &"poneyland" ); |
5088 | /// assert_eq!(e.get(), &43); |
5089 | /// } |
5090 | /// Entry::Vacant(_) => panic!(), |
5091 | /// } |
5092 | /// |
5093 | /// assert_eq!(map["poneyland" ], 43); |
5094 | /// |
5095 | /// let entry = map |
5096 | /// .entry("poneyland" ) |
5097 | /// .and_replace_entry_with(|_k, _v| None); |
5098 | /// |
5099 | /// match entry { |
5100 | /// Entry::Vacant(e) => assert_eq!(e.key(), &"poneyland" ), |
5101 | /// Entry::Occupied(_) => panic!(), |
5102 | /// } |
5103 | /// |
5104 | /// assert!(!map.contains_key("poneyland" )); |
5105 | /// ``` |
5106 | #[cfg_attr (feature = "inline-more" , inline)] |
5107 | pub fn and_replace_entry_with<F>(self, f: F) -> Self |
5108 | where |
5109 | F: FnOnce(&K, V) -> Option<V>, |
5110 | { |
5111 | match self { |
5112 | Entry::Occupied(entry) => entry.replace_entry_with(f), |
5113 | Entry::Vacant(_) => self, |
5114 | } |
5115 | } |
5116 | } |
5117 | |
5118 | impl<'a, K, V: Default, S, A: Allocator + Clone> Entry<'a, K, V, S, A> { |
5119 | /// Ensures a value is in the entry by inserting the default value if empty, |
5120 | /// and returns a mutable reference to the value in the entry. |
5121 | /// |
5122 | /// # Examples |
5123 | /// |
5124 | /// ``` |
5125 | /// use hashbrown::HashMap; |
5126 | /// |
5127 | /// let mut map: HashMap<&str, Option<u32>> = HashMap::new(); |
5128 | /// |
5129 | /// // nonexistent key |
5130 | /// map.entry("poneyland" ).or_default(); |
5131 | /// assert_eq!(map["poneyland" ], None); |
5132 | /// |
5133 | /// map.insert("horseland" , Some(3)); |
5134 | /// |
5135 | /// // existing key |
5136 | /// assert_eq!(map.entry("horseland" ).or_default(), &mut Some(3)); |
5137 | /// ``` |
5138 | #[cfg_attr (feature = "inline-more" , inline)] |
5139 | pub fn or_default(self) -> &'a mut V |
5140 | where |
5141 | K: Hash, |
5142 | S: BuildHasher, |
5143 | { |
5144 | match self { |
5145 | Entry::Occupied(entry) => entry.into_mut(), |
5146 | Entry::Vacant(entry) => entry.insert(Default::default()), |
5147 | } |
5148 | } |
5149 | } |
5150 | |
5151 | impl<'a, K, V, S, A: Allocator + Clone> OccupiedEntry<'a, K, V, S, A> { |
5152 | /// Gets a reference to the key in the entry. |
5153 | /// |
5154 | /// # Examples |
5155 | /// |
5156 | /// ``` |
5157 | /// use hashbrown::hash_map::{Entry, HashMap}; |
5158 | /// |
5159 | /// let mut map: HashMap<&str, u32> = HashMap::new(); |
5160 | /// map.entry("poneyland" ).or_insert(12); |
5161 | /// |
5162 | /// match map.entry("poneyland" ) { |
5163 | /// Entry::Vacant(_) => panic!(), |
5164 | /// Entry::Occupied(entry) => assert_eq!(entry.key(), &"poneyland" ), |
5165 | /// } |
5166 | /// ``` |
5167 | #[cfg_attr (feature = "inline-more" , inline)] |
5168 | pub fn key(&self) -> &K { |
5169 | unsafe { &self.elem.as_ref().0 } |
5170 | } |
5171 | |
5172 | /// Take the ownership of the key and value from the map. |
5173 | /// Keeps the allocated memory for reuse. |
5174 | /// |
5175 | /// # Examples |
5176 | /// |
5177 | /// ``` |
5178 | /// use hashbrown::HashMap; |
5179 | /// use hashbrown::hash_map::Entry; |
5180 | /// |
5181 | /// let mut map: HashMap<&str, u32> = HashMap::new(); |
5182 | /// // The map is empty |
5183 | /// assert!(map.is_empty() && map.capacity() == 0); |
5184 | /// |
5185 | /// map.entry("poneyland" ).or_insert(12); |
5186 | /// let capacity_before_remove = map.capacity(); |
5187 | /// |
5188 | /// if let Entry::Occupied(o) = map.entry("poneyland" ) { |
5189 | /// // We delete the entry from the map. |
5190 | /// assert_eq!(o.remove_entry(), ("poneyland" , 12)); |
5191 | /// } |
5192 | /// |
5193 | /// assert_eq!(map.contains_key("poneyland" ), false); |
5194 | /// // Now map hold none elements but capacity is equal to the old one |
5195 | /// assert!(map.len() == 0 && map.capacity() == capacity_before_remove); |
5196 | /// ``` |
5197 | #[cfg_attr (feature = "inline-more" , inline)] |
5198 | pub fn remove_entry(self) -> (K, V) { |
5199 | unsafe { self.table.table.remove(self.elem) } |
5200 | } |
5201 | |
5202 | /// Gets a reference to the value in the entry. |
5203 | /// |
5204 | /// # Examples |
5205 | /// |
5206 | /// ``` |
5207 | /// use hashbrown::HashMap; |
5208 | /// use hashbrown::hash_map::Entry; |
5209 | /// |
5210 | /// let mut map: HashMap<&str, u32> = HashMap::new(); |
5211 | /// map.entry("poneyland" ).or_insert(12); |
5212 | /// |
5213 | /// match map.entry("poneyland" ) { |
5214 | /// Entry::Vacant(_) => panic!(), |
5215 | /// Entry::Occupied(entry) => assert_eq!(entry.get(), &12), |
5216 | /// } |
5217 | /// ``` |
5218 | #[cfg_attr (feature = "inline-more" , inline)] |
5219 | pub fn get(&self) -> &V { |
5220 | unsafe { &self.elem.as_ref().1 } |
5221 | } |
5222 | |
5223 | /// Gets a mutable reference to the value in the entry. |
5224 | /// |
5225 | /// If you need a reference to the `OccupiedEntry` which may outlive the |
5226 | /// destruction of the `Entry` value, see [`into_mut`]. |
5227 | /// |
5228 | /// [`into_mut`]: #method.into_mut |
5229 | /// |
5230 | /// # Examples |
5231 | /// |
5232 | /// ``` |
5233 | /// use hashbrown::HashMap; |
5234 | /// use hashbrown::hash_map::Entry; |
5235 | /// |
5236 | /// let mut map: HashMap<&str, u32> = HashMap::new(); |
5237 | /// map.entry("poneyland" ).or_insert(12); |
5238 | /// |
5239 | /// assert_eq!(map["poneyland" ], 12); |
5240 | /// if let Entry::Occupied(mut o) = map.entry("poneyland" ) { |
5241 | /// *o.get_mut() += 10; |
5242 | /// assert_eq!(*o.get(), 22); |
5243 | /// |
5244 | /// // We can use the same Entry multiple times. |
5245 | /// *o.get_mut() += 2; |
5246 | /// } |
5247 | /// |
5248 | /// assert_eq!(map["poneyland" ], 24); |
5249 | /// ``` |
5250 | #[cfg_attr (feature = "inline-more" , inline)] |
5251 | pub fn get_mut(&mut self) -> &mut V { |
5252 | unsafe { &mut self.elem.as_mut().1 } |
5253 | } |
5254 | |
5255 | /// Converts the OccupiedEntry into a mutable reference to the value in the entry |
5256 | /// with a lifetime bound to the map itself. |
5257 | /// |
5258 | /// If you need multiple references to the `OccupiedEntry`, see [`get_mut`]. |
5259 | /// |
5260 | /// [`get_mut`]: #method.get_mut |
5261 | /// |
5262 | /// # Examples |
5263 | /// |
5264 | /// ``` |
5265 | /// use hashbrown::hash_map::{Entry, HashMap}; |
5266 | /// |
5267 | /// let mut map: HashMap<&str, u32> = HashMap::new(); |
5268 | /// map.entry("poneyland" ).or_insert(12); |
5269 | /// |
5270 | /// assert_eq!(map["poneyland" ], 12); |
5271 | /// |
5272 | /// let value: &mut u32; |
5273 | /// match map.entry("poneyland" ) { |
5274 | /// Entry::Occupied(entry) => value = entry.into_mut(), |
5275 | /// Entry::Vacant(_) => panic!(), |
5276 | /// } |
5277 | /// *value += 10; |
5278 | /// |
5279 | /// assert_eq!(map["poneyland" ], 22); |
5280 | /// ``` |
5281 | #[cfg_attr (feature = "inline-more" , inline)] |
5282 | pub fn into_mut(self) -> &'a mut V { |
5283 | unsafe { &mut self.elem.as_mut().1 } |
5284 | } |
5285 | |
5286 | /// Sets the value of the entry, and returns the entry's old value. |
5287 | /// |
5288 | /// # Examples |
5289 | /// |
5290 | /// ``` |
5291 | /// use hashbrown::HashMap; |
5292 | /// use hashbrown::hash_map::Entry; |
5293 | /// |
5294 | /// let mut map: HashMap<&str, u32> = HashMap::new(); |
5295 | /// map.entry("poneyland" ).or_insert(12); |
5296 | /// |
5297 | /// if let Entry::Occupied(mut o) = map.entry("poneyland" ) { |
5298 | /// assert_eq!(o.insert(15), 12); |
5299 | /// } |
5300 | /// |
5301 | /// assert_eq!(map["poneyland" ], 15); |
5302 | /// ``` |
5303 | #[cfg_attr (feature = "inline-more" , inline)] |
5304 | pub fn insert(&mut self, value: V) -> V { |
5305 | mem::replace(self.get_mut(), value) |
5306 | } |
5307 | |
5308 | /// Takes the value out of the entry, and returns it. |
5309 | /// Keeps the allocated memory for reuse. |
5310 | /// |
5311 | /// # Examples |
5312 | /// |
5313 | /// ``` |
5314 | /// use hashbrown::HashMap; |
5315 | /// use hashbrown::hash_map::Entry; |
5316 | /// |
5317 | /// let mut map: HashMap<&str, u32> = HashMap::new(); |
5318 | /// // The map is empty |
5319 | /// assert!(map.is_empty() && map.capacity() == 0); |
5320 | /// |
5321 | /// map.entry("poneyland" ).or_insert(12); |
5322 | /// let capacity_before_remove = map.capacity(); |
5323 | /// |
5324 | /// if let Entry::Occupied(o) = map.entry("poneyland" ) { |
5325 | /// assert_eq!(o.remove(), 12); |
5326 | /// } |
5327 | /// |
5328 | /// assert_eq!(map.contains_key("poneyland" ), false); |
5329 | /// // Now map hold none elements but capacity is equal to the old one |
5330 | /// assert!(map.len() == 0 && map.capacity() == capacity_before_remove); |
5331 | /// ``` |
5332 | #[cfg_attr (feature = "inline-more" , inline)] |
5333 | pub fn remove(self) -> V { |
5334 | self.remove_entry().1 |
5335 | } |
5336 | |
5337 | /// Replaces the entry, returning the old key and value. The new key in the hash map will be |
5338 | /// the key used to create this entry. |
5339 | /// |
5340 | /// # Panics |
5341 | /// |
5342 | /// Will panic if this OccupiedEntry was created through [`Entry::insert`]. |
5343 | /// |
5344 | /// # Examples |
5345 | /// |
5346 | /// ``` |
5347 | /// use hashbrown::hash_map::{Entry, HashMap}; |
5348 | /// use std::rc::Rc; |
5349 | /// |
5350 | /// let mut map: HashMap<Rc<String>, u32> = HashMap::new(); |
5351 | /// let key_one = Rc::new("Stringthing" .to_string()); |
5352 | /// let key_two = Rc::new("Stringthing" .to_string()); |
5353 | /// |
5354 | /// map.insert(key_one.clone(), 15); |
5355 | /// assert!(Rc::strong_count(&key_one) == 2 && Rc::strong_count(&key_two) == 1); |
5356 | /// |
5357 | /// match map.entry(key_two.clone()) { |
5358 | /// Entry::Occupied(entry) => { |
5359 | /// let (old_key, old_value): (Rc<String>, u32) = entry.replace_entry(16); |
5360 | /// assert!(Rc::ptr_eq(&key_one, &old_key) && old_value == 15); |
5361 | /// } |
5362 | /// Entry::Vacant(_) => panic!(), |
5363 | /// } |
5364 | /// |
5365 | /// assert!(Rc::strong_count(&key_one) == 1 && Rc::strong_count(&key_two) == 2); |
5366 | /// assert_eq!(map[&"Stringthing" .to_owned()], 16); |
5367 | /// ``` |
5368 | #[cfg_attr (feature = "inline-more" , inline)] |
5369 | pub fn replace_entry(self, value: V) -> (K, V) { |
5370 | let entry = unsafe { self.elem.as_mut() }; |
5371 | |
5372 | let old_key = mem::replace(&mut entry.0, self.key.unwrap()); |
5373 | let old_value = mem::replace(&mut entry.1, value); |
5374 | |
5375 | (old_key, old_value) |
5376 | } |
5377 | |
5378 | /// Replaces the key in the hash map with the key used to create this entry. |
5379 | /// |
5380 | /// # Panics |
5381 | /// |
5382 | /// Will panic if this OccupiedEntry was created through [`Entry::insert`]. |
5383 | /// |
5384 | /// # Examples |
5385 | /// |
5386 | /// ``` |
5387 | /// use hashbrown::hash_map::{Entry, HashMap}; |
5388 | /// use std::rc::Rc; |
5389 | /// |
5390 | /// let mut map: HashMap<Rc<String>, usize> = HashMap::with_capacity(6); |
5391 | /// let mut keys_one: Vec<Rc<String>> = Vec::with_capacity(6); |
5392 | /// let mut keys_two: Vec<Rc<String>> = Vec::with_capacity(6); |
5393 | /// |
5394 | /// for (value, key) in ["a" , "b" , "c" , "d" , "e" , "f" ].into_iter().enumerate() { |
5395 | /// let rc_key = Rc::new(key.to_owned()); |
5396 | /// keys_one.push(rc_key.clone()); |
5397 | /// map.insert(rc_key.clone(), value); |
5398 | /// keys_two.push(Rc::new(key.to_owned())); |
5399 | /// } |
5400 | /// |
5401 | /// assert!( |
5402 | /// keys_one.iter().all(|key| Rc::strong_count(key) == 2) |
5403 | /// && keys_two.iter().all(|key| Rc::strong_count(key) == 1) |
5404 | /// ); |
5405 | /// |
5406 | /// reclaim_memory(&mut map, &keys_two); |
5407 | /// |
5408 | /// assert!( |
5409 | /// keys_one.iter().all(|key| Rc::strong_count(key) == 1) |
5410 | /// && keys_two.iter().all(|key| Rc::strong_count(key) == 2) |
5411 | /// ); |
5412 | /// |
5413 | /// fn reclaim_memory(map: &mut HashMap<Rc<String>, usize>, keys: &[Rc<String>]) { |
5414 | /// for key in keys { |
5415 | /// if let Entry::Occupied(entry) = map.entry(key.clone()) { |
5416 | /// // Replaces the entry's key with our version of it in `keys`. |
5417 | /// entry.replace_key(); |
5418 | /// } |
5419 | /// } |
5420 | /// } |
5421 | /// ``` |
5422 | #[cfg_attr (feature = "inline-more" , inline)] |
5423 | pub fn replace_key(self) -> K { |
5424 | let entry = unsafe { self.elem.as_mut() }; |
5425 | mem::replace(&mut entry.0, self.key.unwrap()) |
5426 | } |
5427 | |
5428 | /// Provides shared access to the key and owned access to the value of |
5429 | /// the entry and allows to replace or remove it based on the |
5430 | /// value of the returned option. |
5431 | /// |
5432 | /// # Examples |
5433 | /// |
5434 | /// ``` |
5435 | /// use hashbrown::HashMap; |
5436 | /// use hashbrown::hash_map::Entry; |
5437 | /// |
5438 | /// let mut map: HashMap<&str, u32> = HashMap::new(); |
5439 | /// map.insert("poneyland" , 42); |
5440 | /// |
5441 | /// let entry = match map.entry("poneyland" ) { |
5442 | /// Entry::Occupied(e) => { |
5443 | /// e.replace_entry_with(|k, v| { |
5444 | /// assert_eq!(k, &"poneyland" ); |
5445 | /// assert_eq!(v, 42); |
5446 | /// Some(v + 1) |
5447 | /// }) |
5448 | /// } |
5449 | /// Entry::Vacant(_) => panic!(), |
5450 | /// }; |
5451 | /// |
5452 | /// match entry { |
5453 | /// Entry::Occupied(e) => { |
5454 | /// assert_eq!(e.key(), &"poneyland" ); |
5455 | /// assert_eq!(e.get(), &43); |
5456 | /// } |
5457 | /// Entry::Vacant(_) => panic!(), |
5458 | /// } |
5459 | /// |
5460 | /// assert_eq!(map["poneyland" ], 43); |
5461 | /// |
5462 | /// let entry = match map.entry("poneyland" ) { |
5463 | /// Entry::Occupied(e) => e.replace_entry_with(|_k, _v| None), |
5464 | /// Entry::Vacant(_) => panic!(), |
5465 | /// }; |
5466 | /// |
5467 | /// match entry { |
5468 | /// Entry::Vacant(e) => { |
5469 | /// assert_eq!(e.key(), &"poneyland" ); |
5470 | /// } |
5471 | /// Entry::Occupied(_) => panic!(), |
5472 | /// } |
5473 | /// |
5474 | /// assert!(!map.contains_key("poneyland" )); |
5475 | /// ``` |
5476 | #[cfg_attr (feature = "inline-more" , inline)] |
5477 | pub fn replace_entry_with<F>(self, f: F) -> Entry<'a, K, V, S, A> |
5478 | where |
5479 | F: FnOnce(&K, V) -> Option<V>, |
5480 | { |
5481 | unsafe { |
5482 | let mut spare_key = None; |
5483 | |
5484 | self.table |
5485 | .table |
5486 | .replace_bucket_with(self.elem.clone(), |(key, value)| { |
5487 | if let Some(new_value) = f(&key, value) { |
5488 | Some((key, new_value)) |
5489 | } else { |
5490 | spare_key = Some(key); |
5491 | None |
5492 | } |
5493 | }); |
5494 | |
5495 | if let Some(key) = spare_key { |
5496 | Entry::Vacant(VacantEntry { |
5497 | hash: self.hash, |
5498 | key, |
5499 | table: self.table, |
5500 | }) |
5501 | } else { |
5502 | Entry::Occupied(self) |
5503 | } |
5504 | } |
5505 | } |
5506 | } |
5507 | |
5508 | impl<'a, K, V, S, A: Allocator + Clone> VacantEntry<'a, K, V, S, A> { |
5509 | /// Gets a reference to the key that would be used when inserting a value |
5510 | /// through the `VacantEntry`. |
5511 | /// |
5512 | /// # Examples |
5513 | /// |
5514 | /// ``` |
5515 | /// use hashbrown::HashMap; |
5516 | /// |
5517 | /// let mut map: HashMap<&str, u32> = HashMap::new(); |
5518 | /// assert_eq!(map.entry("poneyland" ).key(), &"poneyland" ); |
5519 | /// ``` |
5520 | #[cfg_attr (feature = "inline-more" , inline)] |
5521 | pub fn key(&self) -> &K { |
5522 | &self.key |
5523 | } |
5524 | |
5525 | /// Take ownership of the key. |
5526 | /// |
5527 | /// # Examples |
5528 | /// |
5529 | /// ``` |
5530 | /// use hashbrown::hash_map::{Entry, HashMap}; |
5531 | /// |
5532 | /// let mut map: HashMap<&str, u32> = HashMap::new(); |
5533 | /// |
5534 | /// match map.entry("poneyland" ) { |
5535 | /// Entry::Occupied(_) => panic!(), |
5536 | /// Entry::Vacant(v) => assert_eq!(v.into_key(), "poneyland" ), |
5537 | /// } |
5538 | /// ``` |
5539 | #[cfg_attr (feature = "inline-more" , inline)] |
5540 | pub fn into_key(self) -> K { |
5541 | self.key |
5542 | } |
5543 | |
5544 | /// Sets the value of the entry with the VacantEntry's key, |
5545 | /// and returns a mutable reference to it. |
5546 | /// |
5547 | /// # Examples |
5548 | /// |
5549 | /// ``` |
5550 | /// use hashbrown::HashMap; |
5551 | /// use hashbrown::hash_map::Entry; |
5552 | /// |
5553 | /// let mut map: HashMap<&str, u32> = HashMap::new(); |
5554 | /// |
5555 | /// if let Entry::Vacant(o) = map.entry("poneyland" ) { |
5556 | /// o.insert(37); |
5557 | /// } |
5558 | /// assert_eq!(map["poneyland" ], 37); |
5559 | /// ``` |
5560 | #[cfg_attr (feature = "inline-more" , inline)] |
5561 | pub fn insert(self, value: V) -> &'a mut V |
5562 | where |
5563 | K: Hash, |
5564 | S: BuildHasher, |
5565 | { |
5566 | let table = &mut self.table.table; |
5567 | let entry = table.insert_entry( |
5568 | self.hash, |
5569 | (self.key, value), |
5570 | make_hasher::<K, _, V, S>(&self.table.hash_builder), |
5571 | ); |
5572 | &mut entry.1 |
5573 | } |
5574 | |
5575 | #[cfg_attr (feature = "inline-more" , inline)] |
5576 | pub(crate) fn insert_entry(self, value: V) -> OccupiedEntry<'a, K, V, S, A> |
5577 | where |
5578 | K: Hash, |
5579 | S: BuildHasher, |
5580 | { |
5581 | let elem = self.table.table.insert( |
5582 | self.hash, |
5583 | (self.key, value), |
5584 | make_hasher::<K, _, V, S>(&self.table.hash_builder), |
5585 | ); |
5586 | OccupiedEntry { |
5587 | hash: self.hash, |
5588 | key: None, |
5589 | elem, |
5590 | table: self.table, |
5591 | } |
5592 | } |
5593 | } |
5594 | |
5595 | impl<'a, 'b, K, Q: ?Sized, V, S, A: Allocator + Clone> EntryRef<'a, 'b, K, Q, V, S, A> { |
5596 | /// Sets the value of the entry, and returns an OccupiedEntryRef. |
5597 | /// |
5598 | /// # Examples |
5599 | /// |
5600 | /// ``` |
5601 | /// use hashbrown::HashMap; |
5602 | /// |
5603 | /// let mut map: HashMap<String, u32> = HashMap::new(); |
5604 | /// let entry = map.entry_ref("horseyland" ).insert(37); |
5605 | /// |
5606 | /// assert_eq!(entry.key(), "horseyland" ); |
5607 | /// ``` |
5608 | #[cfg_attr (feature = "inline-more" , inline)] |
5609 | pub fn insert(self, value: V) -> OccupiedEntryRef<'a, 'b, K, Q, V, S, A> |
5610 | where |
5611 | K: Hash + From<&'b Q>, |
5612 | S: BuildHasher, |
5613 | { |
5614 | match self { |
5615 | EntryRef::Occupied(mut entry) => { |
5616 | entry.insert(value); |
5617 | entry |
5618 | } |
5619 | EntryRef::Vacant(entry) => entry.insert_entry(value), |
5620 | } |
5621 | } |
5622 | |
5623 | /// Ensures a value is in the entry by inserting the default if empty, and returns |
5624 | /// a mutable reference to the value in the entry. |
5625 | /// |
5626 | /// # Examples |
5627 | /// |
5628 | /// ``` |
5629 | /// use hashbrown::HashMap; |
5630 | /// |
5631 | /// let mut map: HashMap<String, u32> = HashMap::new(); |
5632 | /// |
5633 | /// // nonexistent key |
5634 | /// map.entry_ref("poneyland" ).or_insert(3); |
5635 | /// assert_eq!(map["poneyland" ], 3); |
5636 | /// |
5637 | /// // existing key |
5638 | /// *map.entry_ref("poneyland" ).or_insert(10) *= 2; |
5639 | /// assert_eq!(map["poneyland" ], 6); |
5640 | /// ``` |
5641 | #[cfg_attr (feature = "inline-more" , inline)] |
5642 | pub fn or_insert(self, default: V) -> &'a mut V |
5643 | where |
5644 | K: Hash + From<&'b Q>, |
5645 | S: BuildHasher, |
5646 | { |
5647 | match self { |
5648 | EntryRef::Occupied(entry) => entry.into_mut(), |
5649 | EntryRef::Vacant(entry) => entry.insert(default), |
5650 | } |
5651 | } |
5652 | |
5653 | /// Ensures a value is in the entry by inserting the result of the default function if empty, |
5654 | /// and returns a mutable reference to the value in the entry. |
5655 | /// |
5656 | /// # Examples |
5657 | /// |
5658 | /// ``` |
5659 | /// use hashbrown::HashMap; |
5660 | /// |
5661 | /// let mut map: HashMap<String, u32> = HashMap::new(); |
5662 | /// |
5663 | /// // nonexistent key |
5664 | /// map.entry_ref("poneyland" ).or_insert_with(|| 3); |
5665 | /// assert_eq!(map["poneyland" ], 3); |
5666 | /// |
5667 | /// // existing key |
5668 | /// *map.entry_ref("poneyland" ).or_insert_with(|| 10) *= 2; |
5669 | /// assert_eq!(map["poneyland" ], 6); |
5670 | /// ``` |
5671 | #[cfg_attr (feature = "inline-more" , inline)] |
5672 | pub fn or_insert_with<F: FnOnce() -> V>(self, default: F) -> &'a mut V |
5673 | where |
5674 | K: Hash + From<&'b Q>, |
5675 | S: BuildHasher, |
5676 | { |
5677 | match self { |
5678 | EntryRef::Occupied(entry) => entry.into_mut(), |
5679 | EntryRef::Vacant(entry) => entry.insert(default()), |
5680 | } |
5681 | } |
5682 | |
5683 | /// Ensures a value is in the entry by inserting, if empty, the result of the default function. |
5684 | /// This method allows for generating key-derived values for insertion by providing the default |
5685 | /// function a reference to the key that was moved during the `.entry_ref(key)` method call. |
5686 | /// |
5687 | /// The reference to the moved key is provided so that cloning or copying the key is |
5688 | /// unnecessary, unlike with `.or_insert_with(|| ... )`. |
5689 | /// |
5690 | /// # Examples |
5691 | /// |
5692 | /// ``` |
5693 | /// use hashbrown::HashMap; |
5694 | /// |
5695 | /// let mut map: HashMap<String, usize> = HashMap::new(); |
5696 | /// |
5697 | /// // nonexistent key |
5698 | /// map.entry_ref("poneyland" ).or_insert_with_key(|key| key.chars().count()); |
5699 | /// assert_eq!(map["poneyland" ], 9); |
5700 | /// |
5701 | /// // existing key |
5702 | /// *map.entry_ref("poneyland" ).or_insert_with_key(|key| key.chars().count() * 10) *= 2; |
5703 | /// assert_eq!(map["poneyland" ], 18); |
5704 | /// ``` |
5705 | #[cfg_attr (feature = "inline-more" , inline)] |
5706 | pub fn or_insert_with_key<F: FnOnce(&Q) -> V>(self, default: F) -> &'a mut V |
5707 | where |
5708 | K: Hash + Borrow<Q> + From<&'b Q>, |
5709 | S: BuildHasher, |
5710 | { |
5711 | match self { |
5712 | EntryRef::Occupied(entry) => entry.into_mut(), |
5713 | EntryRef::Vacant(entry) => { |
5714 | let value = default(entry.key.as_ref()); |
5715 | entry.insert(value) |
5716 | } |
5717 | } |
5718 | } |
5719 | |
5720 | /// Returns a reference to this entry's key. |
5721 | /// |
5722 | /// # Examples |
5723 | /// |
5724 | /// ``` |
5725 | /// use hashbrown::HashMap; |
5726 | /// |
5727 | /// let mut map: HashMap<String, u32> = HashMap::new(); |
5728 | /// map.entry_ref("poneyland" ).or_insert(3); |
5729 | /// // existing key |
5730 | /// assert_eq!(map.entry_ref("poneyland" ).key(), "poneyland" ); |
5731 | /// // nonexistent key |
5732 | /// assert_eq!(map.entry_ref("horseland" ).key(), "horseland" ); |
5733 | /// ``` |
5734 | #[cfg_attr (feature = "inline-more" , inline)] |
5735 | pub fn key(&self) -> &Q |
5736 | where |
5737 | K: Borrow<Q>, |
5738 | { |
5739 | match *self { |
5740 | EntryRef::Occupied(ref entry) => entry.key(), |
5741 | EntryRef::Vacant(ref entry) => entry.key(), |
5742 | } |
5743 | } |
5744 | |
5745 | /// Provides in-place mutable access to an occupied entry before any |
5746 | /// potential inserts into the map. |
5747 | /// |
5748 | /// # Examples |
5749 | /// |
5750 | /// ``` |
5751 | /// use hashbrown::HashMap; |
5752 | /// |
5753 | /// let mut map: HashMap<String, u32> = HashMap::new(); |
5754 | /// |
5755 | /// map.entry_ref("poneyland" ) |
5756 | /// .and_modify(|e| { *e += 1 }) |
5757 | /// .or_insert(42); |
5758 | /// assert_eq!(map["poneyland" ], 42); |
5759 | /// |
5760 | /// map.entry_ref("poneyland" ) |
5761 | /// .and_modify(|e| { *e += 1 }) |
5762 | /// .or_insert(42); |
5763 | /// assert_eq!(map["poneyland" ], 43); |
5764 | /// ``` |
5765 | #[cfg_attr (feature = "inline-more" , inline)] |
5766 | pub fn and_modify<F>(self, f: F) -> Self |
5767 | where |
5768 | F: FnOnce(&mut V), |
5769 | { |
5770 | match self { |
5771 | EntryRef::Occupied(mut entry) => { |
5772 | f(entry.get_mut()); |
5773 | EntryRef::Occupied(entry) |
5774 | } |
5775 | EntryRef::Vacant(entry) => EntryRef::Vacant(entry), |
5776 | } |
5777 | } |
5778 | |
5779 | /// Provides shared access to the key and owned access to the value of |
5780 | /// an occupied entry and allows to replace or remove it based on the |
5781 | /// value of the returned option. |
5782 | /// |
5783 | /// # Examples |
5784 | /// |
5785 | /// ``` |
5786 | /// use hashbrown::HashMap; |
5787 | /// use hashbrown::hash_map::EntryRef; |
5788 | /// |
5789 | /// let mut map: HashMap<String, u32> = HashMap::new(); |
5790 | /// |
5791 | /// let entry = map |
5792 | /// .entry_ref("poneyland" ) |
5793 | /// .and_replace_entry_with(|_k, _v| panic!()); |
5794 | /// |
5795 | /// match entry { |
5796 | /// EntryRef::Vacant(e) => { |
5797 | /// assert_eq!(e.key(), "poneyland" ); |
5798 | /// } |
5799 | /// EntryRef::Occupied(_) => panic!(), |
5800 | /// } |
5801 | /// |
5802 | /// map.insert("poneyland" .to_string(), 42); |
5803 | /// |
5804 | /// let entry = map |
5805 | /// .entry_ref("poneyland" ) |
5806 | /// .and_replace_entry_with(|k, v| { |
5807 | /// assert_eq!(k, "poneyland" ); |
5808 | /// assert_eq!(v, 42); |
5809 | /// Some(v + 1) |
5810 | /// }); |
5811 | /// |
5812 | /// match entry { |
5813 | /// EntryRef::Occupied(e) => { |
5814 | /// assert_eq!(e.key(), "poneyland" ); |
5815 | /// assert_eq!(e.get(), &43); |
5816 | /// } |
5817 | /// EntryRef::Vacant(_) => panic!(), |
5818 | /// } |
5819 | /// |
5820 | /// assert_eq!(map["poneyland" ], 43); |
5821 | /// |
5822 | /// let entry = map |
5823 | /// .entry_ref("poneyland" ) |
5824 | /// .and_replace_entry_with(|_k, _v| None); |
5825 | /// |
5826 | /// match entry { |
5827 | /// EntryRef::Vacant(e) => assert_eq!(e.key(), "poneyland" ), |
5828 | /// EntryRef::Occupied(_) => panic!(), |
5829 | /// } |
5830 | /// |
5831 | /// assert!(!map.contains_key("poneyland" )); |
5832 | /// ``` |
5833 | #[cfg_attr (feature = "inline-more" , inline)] |
5834 | pub fn and_replace_entry_with<F>(self, f: F) -> Self |
5835 | where |
5836 | F: FnOnce(&Q, V) -> Option<V>, |
5837 | K: Borrow<Q>, |
5838 | { |
5839 | match self { |
5840 | EntryRef::Occupied(entry) => entry.replace_entry_with(f), |
5841 | EntryRef::Vacant(_) => self, |
5842 | } |
5843 | } |
5844 | } |
5845 | |
5846 | impl<'a, 'b, K, Q: ?Sized, V: Default, S, A: Allocator + Clone> EntryRef<'a, 'b, K, Q, V, S, A> { |
5847 | /// Ensures a value is in the entry by inserting the default value if empty, |
5848 | /// and returns a mutable reference to the value in the entry. |
5849 | /// |
5850 | /// # Examples |
5851 | /// |
5852 | /// ``` |
5853 | /// use hashbrown::HashMap; |
5854 | /// |
5855 | /// let mut map: HashMap<String, Option<u32>> = HashMap::new(); |
5856 | /// |
5857 | /// // nonexistent key |
5858 | /// map.entry_ref("poneyland" ).or_default(); |
5859 | /// assert_eq!(map["poneyland" ], None); |
5860 | /// |
5861 | /// map.insert("horseland" .to_string(), Some(3)); |
5862 | /// |
5863 | /// // existing key |
5864 | /// assert_eq!(map.entry_ref("horseland" ).or_default(), &mut Some(3)); |
5865 | /// ``` |
5866 | #[cfg_attr (feature = "inline-more" , inline)] |
5867 | pub fn or_default(self) -> &'a mut V |
5868 | where |
5869 | K: Hash + From<&'b Q>, |
5870 | S: BuildHasher, |
5871 | { |
5872 | match self { |
5873 | EntryRef::Occupied(entry) => entry.into_mut(), |
5874 | EntryRef::Vacant(entry) => entry.insert(Default::default()), |
5875 | } |
5876 | } |
5877 | } |
5878 | |
5879 | impl<'a, 'b, K, Q: ?Sized, V, S, A: Allocator + Clone> OccupiedEntryRef<'a, 'b, K, Q, V, S, A> { |
5880 | /// Gets a reference to the key in the entry. |
5881 | /// |
5882 | /// # Examples |
5883 | /// |
5884 | /// ``` |
5885 | /// use hashbrown::hash_map::{EntryRef, HashMap}; |
5886 | /// |
5887 | /// let mut map: HashMap<String, u32> = HashMap::new(); |
5888 | /// map.entry_ref("poneyland" ).or_insert(12); |
5889 | /// |
5890 | /// match map.entry_ref("poneyland" ) { |
5891 | /// EntryRef::Vacant(_) => panic!(), |
5892 | /// EntryRef::Occupied(entry) => assert_eq!(entry.key(), "poneyland" ), |
5893 | /// } |
5894 | /// ``` |
5895 | #[cfg_attr (feature = "inline-more" , inline)] |
5896 | pub fn key(&self) -> &Q |
5897 | where |
5898 | K: Borrow<Q>, |
5899 | { |
5900 | unsafe { &self.elem.as_ref().0 }.borrow() |
5901 | } |
5902 | |
5903 | /// Take the ownership of the key and value from the map. |
5904 | /// Keeps the allocated memory for reuse. |
5905 | /// |
5906 | /// # Examples |
5907 | /// |
5908 | /// ``` |
5909 | /// use hashbrown::HashMap; |
5910 | /// use hashbrown::hash_map::EntryRef; |
5911 | /// |
5912 | /// let mut map: HashMap<String, u32> = HashMap::new(); |
5913 | /// // The map is empty |
5914 | /// assert!(map.is_empty() && map.capacity() == 0); |
5915 | /// |
5916 | /// map.entry_ref("poneyland" ).or_insert(12); |
5917 | /// let capacity_before_remove = map.capacity(); |
5918 | /// |
5919 | /// if let EntryRef::Occupied(o) = map.entry_ref("poneyland" ) { |
5920 | /// // We delete the entry from the map. |
5921 | /// assert_eq!(o.remove_entry(), ("poneyland" .to_owned(), 12)); |
5922 | /// } |
5923 | /// |
5924 | /// assert_eq!(map.contains_key("poneyland" ), false); |
5925 | /// // Now map hold none elements but capacity is equal to the old one |
5926 | /// assert!(map.len() == 0 && map.capacity() == capacity_before_remove); |
5927 | /// ``` |
5928 | #[cfg_attr (feature = "inline-more" , inline)] |
5929 | pub fn remove_entry(self) -> (K, V) { |
5930 | unsafe { self.table.table.remove(self.elem) } |
5931 | } |
5932 | |
5933 | /// Gets a reference to the value in the entry. |
5934 | /// |
5935 | /// # Examples |
5936 | /// |
5937 | /// ``` |
5938 | /// use hashbrown::HashMap; |
5939 | /// use hashbrown::hash_map::EntryRef; |
5940 | /// |
5941 | /// let mut map: HashMap<String, u32> = HashMap::new(); |
5942 | /// map.entry_ref("poneyland" ).or_insert(12); |
5943 | /// |
5944 | /// match map.entry_ref("poneyland" ) { |
5945 | /// EntryRef::Vacant(_) => panic!(), |
5946 | /// EntryRef::Occupied(entry) => assert_eq!(entry.get(), &12), |
5947 | /// } |
5948 | /// ``` |
5949 | #[cfg_attr (feature = "inline-more" , inline)] |
5950 | pub fn get(&self) -> &V { |
5951 | unsafe { &self.elem.as_ref().1 } |
5952 | } |
5953 | |
5954 | /// Gets a mutable reference to the value in the entry. |
5955 | /// |
5956 | /// If you need a reference to the `OccupiedEntryRef` which may outlive the |
5957 | /// destruction of the `EntryRef` value, see [`into_mut`]. |
5958 | /// |
5959 | /// [`into_mut`]: #method.into_mut |
5960 | /// |
5961 | /// # Examples |
5962 | /// |
5963 | /// ``` |
5964 | /// use hashbrown::HashMap; |
5965 | /// use hashbrown::hash_map::EntryRef; |
5966 | /// |
5967 | /// let mut map: HashMap<String, u32> = HashMap::new(); |
5968 | /// map.entry_ref("poneyland" ).or_insert(12); |
5969 | /// |
5970 | /// assert_eq!(map["poneyland" ], 12); |
5971 | /// if let EntryRef::Occupied(mut o) = map.entry_ref("poneyland" ) { |
5972 | /// *o.get_mut() += 10; |
5973 | /// assert_eq!(*o.get(), 22); |
5974 | /// |
5975 | /// // We can use the same Entry multiple times. |
5976 | /// *o.get_mut() += 2; |
5977 | /// } |
5978 | /// |
5979 | /// assert_eq!(map["poneyland" ], 24); |
5980 | /// ``` |
5981 | #[cfg_attr (feature = "inline-more" , inline)] |
5982 | pub fn get_mut(&mut self) -> &mut V { |
5983 | unsafe { &mut self.elem.as_mut().1 } |
5984 | } |
5985 | |
5986 | /// Converts the OccupiedEntryRef into a mutable reference to the value in the entry |
5987 | /// with a lifetime bound to the map itself. |
5988 | /// |
5989 | /// If you need multiple references to the `OccupiedEntryRef`, see [`get_mut`]. |
5990 | /// |
5991 | /// [`get_mut`]: #method.get_mut |
5992 | /// |
5993 | /// # Examples |
5994 | /// |
5995 | /// ``` |
5996 | /// use hashbrown::hash_map::{EntryRef, HashMap}; |
5997 | /// |
5998 | /// let mut map: HashMap<String, u32> = HashMap::new(); |
5999 | /// map.entry_ref("poneyland" ).or_insert(12); |
6000 | /// |
6001 | /// let value: &mut u32; |
6002 | /// match map.entry_ref("poneyland" ) { |
6003 | /// EntryRef::Occupied(entry) => value = entry.into_mut(), |
6004 | /// EntryRef::Vacant(_) => panic!(), |
6005 | /// } |
6006 | /// *value += 10; |
6007 | /// |
6008 | /// assert_eq!(map["poneyland" ], 22); |
6009 | /// ``` |
6010 | #[cfg_attr (feature = "inline-more" , inline)] |
6011 | pub fn into_mut(self) -> &'a mut V { |
6012 | unsafe { &mut self.elem.as_mut().1 } |
6013 | } |
6014 | |
6015 | /// Sets the value of the entry, and returns the entry's old value. |
6016 | /// |
6017 | /// # Examples |
6018 | /// |
6019 | /// ``` |
6020 | /// use hashbrown::HashMap; |
6021 | /// use hashbrown::hash_map::EntryRef; |
6022 | /// |
6023 | /// let mut map: HashMap<String, u32> = HashMap::new(); |
6024 | /// map.entry_ref("poneyland" ).or_insert(12); |
6025 | /// |
6026 | /// if let EntryRef::Occupied(mut o) = map.entry_ref("poneyland" ) { |
6027 | /// assert_eq!(o.insert(15), 12); |
6028 | /// } |
6029 | /// |
6030 | /// assert_eq!(map["poneyland" ], 15); |
6031 | /// ``` |
6032 | #[cfg_attr (feature = "inline-more" , inline)] |
6033 | pub fn insert(&mut self, value: V) -> V { |
6034 | mem::replace(self.get_mut(), value) |
6035 | } |
6036 | |
6037 | /// Takes the value out of the entry, and returns it. |
6038 | /// Keeps the allocated memory for reuse. |
6039 | /// |
6040 | /// # Examples |
6041 | /// |
6042 | /// ``` |
6043 | /// use hashbrown::HashMap; |
6044 | /// use hashbrown::hash_map::EntryRef; |
6045 | /// |
6046 | /// let mut map: HashMap<String, u32> = HashMap::new(); |
6047 | /// // The map is empty |
6048 | /// assert!(map.is_empty() && map.capacity() == 0); |
6049 | /// |
6050 | /// map.entry_ref("poneyland" ).or_insert(12); |
6051 | /// let capacity_before_remove = map.capacity(); |
6052 | /// |
6053 | /// if let EntryRef::Occupied(o) = map.entry_ref("poneyland" ) { |
6054 | /// assert_eq!(o.remove(), 12); |
6055 | /// } |
6056 | /// |
6057 | /// assert_eq!(map.contains_key("poneyland" ), false); |
6058 | /// // Now map hold none elements but capacity is equal to the old one |
6059 | /// assert!(map.len() == 0 && map.capacity() == capacity_before_remove); |
6060 | /// ``` |
6061 | #[cfg_attr (feature = "inline-more" , inline)] |
6062 | pub fn remove(self) -> V { |
6063 | self.remove_entry().1 |
6064 | } |
6065 | |
6066 | /// Replaces the entry, returning the old key and value. The new key in the hash map will be |
6067 | /// the key used to create this entry. |
6068 | /// |
6069 | /// # Panics |
6070 | /// |
6071 | /// Will panic if this OccupiedEntry was created through [`EntryRef::insert`]. |
6072 | /// |
6073 | /// # Examples |
6074 | /// |
6075 | /// ``` |
6076 | /// use hashbrown::hash_map::{EntryRef, HashMap}; |
6077 | /// use std::rc::Rc; |
6078 | /// |
6079 | /// let mut map: HashMap<Rc<str>, u32> = HashMap::new(); |
6080 | /// let key: Rc<str> = Rc::from("Stringthing" ); |
6081 | /// |
6082 | /// map.insert(key.clone(), 15); |
6083 | /// assert_eq!(Rc::strong_count(&key), 2); |
6084 | /// |
6085 | /// match map.entry_ref("Stringthing" ) { |
6086 | /// EntryRef::Occupied(entry) => { |
6087 | /// let (old_key, old_value): (Rc<str>, u32) = entry.replace_entry(16); |
6088 | /// assert!(Rc::ptr_eq(&key, &old_key) && old_value == 15); |
6089 | /// } |
6090 | /// EntryRef::Vacant(_) => panic!(), |
6091 | /// } |
6092 | /// |
6093 | /// assert_eq!(Rc::strong_count(&key), 1); |
6094 | /// assert_eq!(map["Stringthing" ], 16); |
6095 | /// ``` |
6096 | #[cfg_attr (feature = "inline-more" , inline)] |
6097 | pub fn replace_entry(self, value: V) -> (K, V) |
6098 | where |
6099 | K: From<&'b Q>, |
6100 | { |
6101 | let entry = unsafe { self.elem.as_mut() }; |
6102 | |
6103 | let old_key = mem::replace(&mut entry.0, self.key.unwrap().into_owned()); |
6104 | let old_value = mem::replace(&mut entry.1, value); |
6105 | |
6106 | (old_key, old_value) |
6107 | } |
6108 | |
6109 | /// Replaces the key in the hash map with the key used to create this entry. |
6110 | /// |
6111 | /// # Panics |
6112 | /// |
6113 | /// Will panic if this OccupiedEntry was created through [`Entry::insert`]. |
6114 | /// |
6115 | /// # Examples |
6116 | /// |
6117 | /// ``` |
6118 | /// use hashbrown::hash_map::{EntryRef, HashMap}; |
6119 | /// use std::rc::Rc; |
6120 | /// |
6121 | /// let mut map: HashMap<Rc<str>, usize> = HashMap::with_capacity(6); |
6122 | /// let mut keys: Vec<Rc<str>> = Vec::with_capacity(6); |
6123 | /// |
6124 | /// for (value, key) in ["a" , "b" , "c" , "d" , "e" , "f" ].into_iter().enumerate() { |
6125 | /// let rc_key: Rc<str> = Rc::from(key); |
6126 | /// keys.push(rc_key.clone()); |
6127 | /// map.insert(rc_key.clone(), value); |
6128 | /// } |
6129 | /// |
6130 | /// assert!(keys.iter().all(|key| Rc::strong_count(key) == 2)); |
6131 | /// |
6132 | /// // It doesn't matter that we kind of use a vector with the same keys, |
6133 | /// // because all keys will be newly created from the references |
6134 | /// reclaim_memory(&mut map, &keys); |
6135 | /// |
6136 | /// assert!(keys.iter().all(|key| Rc::strong_count(key) == 1)); |
6137 | /// |
6138 | /// fn reclaim_memory(map: &mut HashMap<Rc<str>, usize>, keys: &[Rc<str>]) { |
6139 | /// for key in keys { |
6140 | /// if let EntryRef::Occupied(entry) = map.entry_ref(key.as_ref()) { |
6141 | /// /// Replaces the entry's key with our version of it in `keys`. |
6142 | /// entry.replace_key(); |
6143 | /// } |
6144 | /// } |
6145 | /// } |
6146 | /// ``` |
6147 | #[cfg_attr (feature = "inline-more" , inline)] |
6148 | pub fn replace_key(self) -> K |
6149 | where |
6150 | K: From<&'b Q>, |
6151 | { |
6152 | let entry = unsafe { self.elem.as_mut() }; |
6153 | mem::replace(&mut entry.0, self.key.unwrap().into_owned()) |
6154 | } |
6155 | |
6156 | /// Provides shared access to the key and owned access to the value of |
6157 | /// the entry and allows to replace or remove it based on the |
6158 | /// value of the returned option. |
6159 | /// |
6160 | /// # Examples |
6161 | /// |
6162 | /// ``` |
6163 | /// use hashbrown::HashMap; |
6164 | /// use hashbrown::hash_map::EntryRef; |
6165 | /// |
6166 | /// let mut map: HashMap<String, u32> = HashMap::new(); |
6167 | /// map.insert("poneyland" .to_string(), 42); |
6168 | /// |
6169 | /// let entry = match map.entry_ref("poneyland" ) { |
6170 | /// EntryRef::Occupied(e) => { |
6171 | /// e.replace_entry_with(|k, v| { |
6172 | /// assert_eq!(k, "poneyland" ); |
6173 | /// assert_eq!(v, 42); |
6174 | /// Some(v + 1) |
6175 | /// }) |
6176 | /// } |
6177 | /// EntryRef::Vacant(_) => panic!(), |
6178 | /// }; |
6179 | /// |
6180 | /// match entry { |
6181 | /// EntryRef::Occupied(e) => { |
6182 | /// assert_eq!(e.key(), "poneyland" ); |
6183 | /// assert_eq!(e.get(), &43); |
6184 | /// } |
6185 | /// EntryRef::Vacant(_) => panic!(), |
6186 | /// } |
6187 | /// |
6188 | /// assert_eq!(map["poneyland" ], 43); |
6189 | /// |
6190 | /// let entry = match map.entry_ref("poneyland" ) { |
6191 | /// EntryRef::Occupied(e) => e.replace_entry_with(|_k, _v| None), |
6192 | /// EntryRef::Vacant(_) => panic!(), |
6193 | /// }; |
6194 | /// |
6195 | /// match entry { |
6196 | /// EntryRef::Vacant(e) => { |
6197 | /// assert_eq!(e.key(), "poneyland" ); |
6198 | /// } |
6199 | /// EntryRef::Occupied(_) => panic!(), |
6200 | /// } |
6201 | /// |
6202 | /// assert!(!map.contains_key("poneyland" )); |
6203 | /// ``` |
6204 | #[cfg_attr (feature = "inline-more" , inline)] |
6205 | pub fn replace_entry_with<F>(self, f: F) -> EntryRef<'a, 'b, K, Q, V, S, A> |
6206 | where |
6207 | F: FnOnce(&Q, V) -> Option<V>, |
6208 | K: Borrow<Q>, |
6209 | { |
6210 | unsafe { |
6211 | let mut spare_key = None; |
6212 | |
6213 | self.table |
6214 | .table |
6215 | .replace_bucket_with(self.elem.clone(), |(key, value)| { |
6216 | if let Some(new_value) = f(key.borrow(), value) { |
6217 | Some((key, new_value)) |
6218 | } else { |
6219 | spare_key = Some(KeyOrRef::Owned(key)); |
6220 | None |
6221 | } |
6222 | }); |
6223 | |
6224 | if let Some(key) = spare_key { |
6225 | EntryRef::Vacant(VacantEntryRef { |
6226 | hash: self.hash, |
6227 | key, |
6228 | table: self.table, |
6229 | }) |
6230 | } else { |
6231 | EntryRef::Occupied(self) |
6232 | } |
6233 | } |
6234 | } |
6235 | } |
6236 | |
6237 | impl<'a, 'b, K, Q: ?Sized, V, S, A: Allocator + Clone> VacantEntryRef<'a, 'b, K, Q, V, S, A> { |
6238 | /// Gets a reference to the key that would be used when inserting a value |
6239 | /// through the `VacantEntryRef`. |
6240 | /// |
6241 | /// # Examples |
6242 | /// |
6243 | /// ``` |
6244 | /// use hashbrown::HashMap; |
6245 | /// |
6246 | /// let mut map: HashMap<String, u32> = HashMap::new(); |
6247 | /// let key: &str = "poneyland" ; |
6248 | /// assert_eq!(map.entry_ref(key).key(), "poneyland" ); |
6249 | /// ``` |
6250 | #[cfg_attr (feature = "inline-more" , inline)] |
6251 | pub fn key(&self) -> &Q |
6252 | where |
6253 | K: Borrow<Q>, |
6254 | { |
6255 | self.key.as_ref() |
6256 | } |
6257 | |
6258 | /// Take ownership of the key. |
6259 | /// |
6260 | /// # Examples |
6261 | /// |
6262 | /// ``` |
6263 | /// use hashbrown::hash_map::{EntryRef, HashMap}; |
6264 | /// |
6265 | /// let mut map: HashMap<String, u32> = HashMap::new(); |
6266 | /// let key: &str = "poneyland" ; |
6267 | /// |
6268 | /// match map.entry_ref(key) { |
6269 | /// EntryRef::Occupied(_) => panic!(), |
6270 | /// EntryRef::Vacant(v) => assert_eq!(v.into_key(), "poneyland" .to_owned()), |
6271 | /// } |
6272 | /// ``` |
6273 | #[cfg_attr (feature = "inline-more" , inline)] |
6274 | pub fn into_key(self) -> K |
6275 | where |
6276 | K: From<&'b Q>, |
6277 | { |
6278 | self.key.into_owned() |
6279 | } |
6280 | |
6281 | /// Sets the value of the entry with the VacantEntryRef's key, |
6282 | /// and returns a mutable reference to it. |
6283 | /// |
6284 | /// # Examples |
6285 | /// |
6286 | /// ``` |
6287 | /// use hashbrown::HashMap; |
6288 | /// use hashbrown::hash_map::EntryRef; |
6289 | /// |
6290 | /// let mut map: HashMap<String, u32> = HashMap::new(); |
6291 | /// let key: &str = "poneyland" ; |
6292 | /// |
6293 | /// if let EntryRef::Vacant(o) = map.entry_ref(key) { |
6294 | /// o.insert(37); |
6295 | /// } |
6296 | /// assert_eq!(map["poneyland" ], 37); |
6297 | /// ``` |
6298 | #[cfg_attr (feature = "inline-more" , inline)] |
6299 | pub fn insert(self, value: V) -> &'a mut V |
6300 | where |
6301 | K: Hash + From<&'b Q>, |
6302 | S: BuildHasher, |
6303 | { |
6304 | let table = &mut self.table.table; |
6305 | let entry = table.insert_entry( |
6306 | self.hash, |
6307 | (self.key.into_owned(), value), |
6308 | make_hasher::<K, _, V, S>(&self.table.hash_builder), |
6309 | ); |
6310 | &mut entry.1 |
6311 | } |
6312 | |
6313 | #[cfg_attr (feature = "inline-more" , inline)] |
6314 | fn insert_entry(self, value: V) -> OccupiedEntryRef<'a, 'b, K, Q, V, S, A> |
6315 | where |
6316 | K: Hash + From<&'b Q>, |
6317 | S: BuildHasher, |
6318 | { |
6319 | let elem = self.table.table.insert( |
6320 | self.hash, |
6321 | (self.key.into_owned(), value), |
6322 | make_hasher::<K, _, V, S>(&self.table.hash_builder), |
6323 | ); |
6324 | OccupiedEntryRef { |
6325 | hash: self.hash, |
6326 | key: None, |
6327 | elem, |
6328 | table: self.table, |
6329 | } |
6330 | } |
6331 | } |
6332 | |
6333 | impl<K, V, S, A> FromIterator<(K, V)> for HashMap<K, V, S, A> |
6334 | where |
6335 | K: Eq + Hash, |
6336 | S: BuildHasher + Default, |
6337 | A: Default + Allocator + Clone, |
6338 | { |
6339 | #[cfg_attr (feature = "inline-more" , inline)] |
6340 | fn from_iter<T: IntoIterator<Item = (K, V)>>(iter: T) -> Self { |
6341 | let iter: ::IntoIter = iter.into_iter(); |
6342 | let mut map: HashMap = |
6343 | Self::with_capacity_and_hasher_in(capacity:iter.size_hint().0, S::default(), A::default()); |
6344 | iter.for_each(|(k: K, v: V)| { |
6345 | map.insert(k, v); |
6346 | }); |
6347 | map |
6348 | } |
6349 | } |
6350 | |
6351 | /// Inserts all new key-values from the iterator and replaces values with existing |
6352 | /// keys with new values returned from the iterator. |
6353 | impl<K, V, S, A> Extend<(K, V)> for HashMap<K, V, S, A> |
6354 | where |
6355 | K: Eq + Hash, |
6356 | S: BuildHasher, |
6357 | A: Allocator + Clone, |
6358 | { |
6359 | /// Inserts all new key-values from the iterator to existing `HashMap<K, V, S, A>`. |
6360 | /// Replace values with existing keys with new values returned from the iterator. |
6361 | /// |
6362 | /// # Examples |
6363 | /// |
6364 | /// ``` |
6365 | /// use hashbrown::hash_map::HashMap; |
6366 | /// |
6367 | /// let mut map = HashMap::new(); |
6368 | /// map.insert(1, 100); |
6369 | /// |
6370 | /// let some_iter = [(1, 1), (2, 2)].into_iter(); |
6371 | /// map.extend(some_iter); |
6372 | /// // Replace values with existing keys with new values returned from the iterator. |
6373 | /// // So that the map.get(&1) doesn't return Some(&100). |
6374 | /// assert_eq!(map.get(&1), Some(&1)); |
6375 | /// |
6376 | /// let some_vec: Vec<_> = vec![(3, 3), (4, 4)]; |
6377 | /// map.extend(some_vec); |
6378 | /// |
6379 | /// let some_arr = [(5, 5), (6, 6)]; |
6380 | /// map.extend(some_arr); |
6381 | /// let old_map_len = map.len(); |
6382 | /// |
6383 | /// // You can also extend from another HashMap |
6384 | /// let mut new_map = HashMap::new(); |
6385 | /// new_map.extend(map); |
6386 | /// assert_eq!(new_map.len(), old_map_len); |
6387 | /// |
6388 | /// let mut vec: Vec<_> = new_map.into_iter().collect(); |
6389 | /// // The `IntoIter` iterator produces items in arbitrary order, so the |
6390 | /// // items must be sorted to test them against a sorted array. |
6391 | /// vec.sort_unstable(); |
6392 | /// assert_eq!(vec, [(1, 1), (2, 2), (3, 3), (4, 4), (5, 5), (6, 6)]); |
6393 | /// ``` |
6394 | #[cfg_attr (feature = "inline-more" , inline)] |
6395 | fn extend<T: IntoIterator<Item = (K, V)>>(&mut self, iter: T) { |
6396 | // Keys may be already present or show multiple times in the iterator. |
6397 | // Reserve the entire hint lower bound if the map is empty. |
6398 | // Otherwise reserve half the hint (rounded up), so the map |
6399 | // will only resize twice in the worst case. |
6400 | let iter = iter.into_iter(); |
6401 | let reserve = if self.is_empty() { |
6402 | iter.size_hint().0 |
6403 | } else { |
6404 | (iter.size_hint().0 + 1) / 2 |
6405 | }; |
6406 | self.reserve(reserve); |
6407 | iter.for_each(move |(k, v)| { |
6408 | self.insert(k, v); |
6409 | }); |
6410 | } |
6411 | |
6412 | #[inline ] |
6413 | #[cfg (feature = "nightly" )] |
6414 | fn extend_one(&mut self, (k, v): (K, V)) { |
6415 | self.insert(k, v); |
6416 | } |
6417 | |
6418 | #[inline ] |
6419 | #[cfg (feature = "nightly" )] |
6420 | fn extend_reserve(&mut self, additional: usize) { |
6421 | // Keys may be already present or show multiple times in the iterator. |
6422 | // Reserve the entire hint lower bound if the map is empty. |
6423 | // Otherwise reserve half the hint (rounded up), so the map |
6424 | // will only resize twice in the worst case. |
6425 | let reserve = if self.is_empty() { |
6426 | additional |
6427 | } else { |
6428 | (additional + 1) / 2 |
6429 | }; |
6430 | self.reserve(reserve); |
6431 | } |
6432 | } |
6433 | |
6434 | /// Inserts all new key-values from the iterator and replaces values with existing |
6435 | /// keys with new values returned from the iterator. |
6436 | impl<'a, K, V, S, A> Extend<(&'a K, &'a V)> for HashMap<K, V, S, A> |
6437 | where |
6438 | K: Eq + Hash + Copy, |
6439 | V: Copy, |
6440 | S: BuildHasher, |
6441 | A: Allocator + Clone, |
6442 | { |
6443 | /// Inserts all new key-values from the iterator to existing `HashMap<K, V, S, A>`. |
6444 | /// Replace values with existing keys with new values returned from the iterator. |
6445 | /// The keys and values must implement [`Copy`] trait. |
6446 | /// |
6447 | /// [`Copy`]: https://doc.rust-lang.org/core/marker/trait.Copy.html |
6448 | /// |
6449 | /// # Examples |
6450 | /// |
6451 | /// ``` |
6452 | /// use hashbrown::hash_map::HashMap; |
6453 | /// |
6454 | /// let mut map = HashMap::new(); |
6455 | /// map.insert(1, 100); |
6456 | /// |
6457 | /// let arr = [(1, 1), (2, 2)]; |
6458 | /// let some_iter = arr.iter().map(|&(k, v)| (k, v)); |
6459 | /// map.extend(some_iter); |
6460 | /// // Replace values with existing keys with new values returned from the iterator. |
6461 | /// // So that the map.get(&1) doesn't return Some(&100). |
6462 | /// assert_eq!(map.get(&1), Some(&1)); |
6463 | /// |
6464 | /// let some_vec: Vec<_> = vec![(3, 3), (4, 4)]; |
6465 | /// map.extend(some_vec.iter().map(|&(k, v)| (k, v))); |
6466 | /// |
6467 | /// let some_arr = [(5, 5), (6, 6)]; |
6468 | /// map.extend(some_arr.iter().map(|&(k, v)| (k, v))); |
6469 | /// |
6470 | /// // You can also extend from another HashMap |
6471 | /// let mut new_map = HashMap::new(); |
6472 | /// new_map.extend(&map); |
6473 | /// assert_eq!(new_map, map); |
6474 | /// |
6475 | /// let mut vec: Vec<_> = new_map.into_iter().collect(); |
6476 | /// // The `IntoIter` iterator produces items in arbitrary order, so the |
6477 | /// // items must be sorted to test them against a sorted array. |
6478 | /// vec.sort_unstable(); |
6479 | /// assert_eq!(vec, [(1, 1), (2, 2), (3, 3), (4, 4), (5, 5), (6, 6)]); |
6480 | /// ``` |
6481 | #[cfg_attr (feature = "inline-more" , inline)] |
6482 | fn extend<T: IntoIterator<Item = (&'a K, &'a V)>>(&mut self, iter: T) { |
6483 | self.extend(iter.into_iter().map(|(&key, &value)| (key, value))); |
6484 | } |
6485 | |
6486 | #[inline ] |
6487 | #[cfg (feature = "nightly" )] |
6488 | fn extend_one(&mut self, (k, v): (&'a K, &'a V)) { |
6489 | self.insert(*k, *v); |
6490 | } |
6491 | |
6492 | #[inline ] |
6493 | #[cfg (feature = "nightly" )] |
6494 | fn extend_reserve(&mut self, additional: usize) { |
6495 | Extend::<(K, V)>::extend_reserve(self, additional); |
6496 | } |
6497 | } |
6498 | |
6499 | /// Inserts all new key-values from the iterator and replaces values with existing |
6500 | /// keys with new values returned from the iterator. |
6501 | impl<'a, K, V, S, A> Extend<&'a (K, V)> for HashMap<K, V, S, A> |
6502 | where |
6503 | K: Eq + Hash + Copy, |
6504 | V: Copy, |
6505 | S: BuildHasher, |
6506 | A: Allocator + Clone, |
6507 | { |
6508 | /// Inserts all new key-values from the iterator to existing `HashMap<K, V, S, A>`. |
6509 | /// Replace values with existing keys with new values returned from the iterator. |
6510 | /// The keys and values must implement [`Copy`] trait. |
6511 | /// |
6512 | /// [`Copy`]: https://doc.rust-lang.org/core/marker/trait.Copy.html |
6513 | /// |
6514 | /// # Examples |
6515 | /// |
6516 | /// ``` |
6517 | /// use hashbrown::hash_map::HashMap; |
6518 | /// |
6519 | /// let mut map = HashMap::new(); |
6520 | /// map.insert(1, 100); |
6521 | /// |
6522 | /// let arr = [(1, 1), (2, 2)]; |
6523 | /// let some_iter = arr.iter(); |
6524 | /// map.extend(some_iter); |
6525 | /// // Replace values with existing keys with new values returned from the iterator. |
6526 | /// // So that the map.get(&1) doesn't return Some(&100). |
6527 | /// assert_eq!(map.get(&1), Some(&1)); |
6528 | /// |
6529 | /// let some_vec: Vec<_> = vec![(3, 3), (4, 4)]; |
6530 | /// map.extend(&some_vec); |
6531 | /// |
6532 | /// let some_arr = [(5, 5), (6, 6)]; |
6533 | /// map.extend(&some_arr); |
6534 | /// |
6535 | /// let mut vec: Vec<_> = map.into_iter().collect(); |
6536 | /// // The `IntoIter` iterator produces items in arbitrary order, so the |
6537 | /// // items must be sorted to test them against a sorted array. |
6538 | /// vec.sort_unstable(); |
6539 | /// assert_eq!(vec, [(1, 1), (2, 2), (3, 3), (4, 4), (5, 5), (6, 6)]); |
6540 | /// ``` |
6541 | #[cfg_attr (feature = "inline-more" , inline)] |
6542 | fn extend<T: IntoIterator<Item = &'a (K, V)>>(&mut self, iter: T) { |
6543 | self.extend(iter.into_iter().map(|&(key, value)| (key, value))); |
6544 | } |
6545 | |
6546 | #[inline ] |
6547 | #[cfg (feature = "nightly" )] |
6548 | fn extend_one(&mut self, &(k, v): &'a (K, V)) { |
6549 | self.insert(k, v); |
6550 | } |
6551 | |
6552 | #[inline ] |
6553 | #[cfg (feature = "nightly" )] |
6554 | fn extend_reserve(&mut self, additional: usize) { |
6555 | Extend::<(K, V)>::extend_reserve(self, additional); |
6556 | } |
6557 | } |
6558 | |
6559 | #[allow (dead_code)] |
6560 | fn assert_covariance() { |
6561 | fn map_key<'new>(v: HashMap<&'static str, u8>) -> HashMap<&'new str, u8> { |
6562 | v |
6563 | } |
6564 | fn map_val<'new>(v: HashMap<u8, &'static str>) -> HashMap<u8, &'new str> { |
6565 | v |
6566 | } |
6567 | fn iter_key<'a, 'new>(v: Iter<'a, &'static str, u8>) -> Iter<'a, &'new str, u8> { |
6568 | v |
6569 | } |
6570 | fn iter_val<'a, 'new>(v: Iter<'a, u8, &'static str>) -> Iter<'a, u8, &'new str> { |
6571 | v |
6572 | } |
6573 | fn into_iter_key<'new, A: Allocator + Clone>( |
6574 | v: IntoIter<&'static str, u8, A>, |
6575 | ) -> IntoIter<&'new str, u8, A> { |
6576 | v |
6577 | } |
6578 | fn into_iter_val<'new, A: Allocator + Clone>( |
6579 | v: IntoIter<u8, &'static str, A>, |
6580 | ) -> IntoIter<u8, &'new str, A> { |
6581 | v |
6582 | } |
6583 | fn keys_key<'a, 'new>(v: Keys<'a, &'static str, u8>) -> Keys<'a, &'new str, u8> { |
6584 | v |
6585 | } |
6586 | fn keys_val<'a, 'new>(v: Keys<'a, u8, &'static str>) -> Keys<'a, u8, &'new str> { |
6587 | v |
6588 | } |
6589 | fn values_key<'a, 'new>(v: Values<'a, &'static str, u8>) -> Values<'a, &'new str, u8> { |
6590 | v |
6591 | } |
6592 | fn values_val<'a, 'new>(v: Values<'a, u8, &'static str>) -> Values<'a, u8, &'new str> { |
6593 | v |
6594 | } |
6595 | fn drain<'new>( |
6596 | d: Drain<'static, &'static str, &'static str>, |
6597 | ) -> Drain<'new, &'new str, &'new str> { |
6598 | d |
6599 | } |
6600 | } |
6601 | |
6602 | #[cfg (test)] |
6603 | mod test_map { |
6604 | use super::DefaultHashBuilder; |
6605 | use super::Entry::{Occupied, Vacant}; |
6606 | use super::EntryRef; |
6607 | use super::{HashMap, RawEntryMut}; |
6608 | use rand::{rngs::SmallRng, Rng, SeedableRng}; |
6609 | use std::borrow::ToOwned; |
6610 | use std::cell::RefCell; |
6611 | use std::usize; |
6612 | use std::vec::Vec; |
6613 | |
6614 | #[test ] |
6615 | fn test_zero_capacities() { |
6616 | type HM = HashMap<i32, i32>; |
6617 | |
6618 | let m = HM::new(); |
6619 | assert_eq!(m.capacity(), 0); |
6620 | |
6621 | let m = HM::default(); |
6622 | assert_eq!(m.capacity(), 0); |
6623 | |
6624 | let m = HM::with_hasher(DefaultHashBuilder::default()); |
6625 | assert_eq!(m.capacity(), 0); |
6626 | |
6627 | let m = HM::with_capacity(0); |
6628 | assert_eq!(m.capacity(), 0); |
6629 | |
6630 | let m = HM::with_capacity_and_hasher(0, DefaultHashBuilder::default()); |
6631 | assert_eq!(m.capacity(), 0); |
6632 | |
6633 | let mut m = HM::new(); |
6634 | m.insert(1, 1); |
6635 | m.insert(2, 2); |
6636 | m.remove(&1); |
6637 | m.remove(&2); |
6638 | m.shrink_to_fit(); |
6639 | assert_eq!(m.capacity(), 0); |
6640 | |
6641 | let mut m = HM::new(); |
6642 | m.reserve(0); |
6643 | assert_eq!(m.capacity(), 0); |
6644 | } |
6645 | |
6646 | #[test ] |
6647 | fn test_create_capacity_zero() { |
6648 | let mut m = HashMap::with_capacity(0); |
6649 | |
6650 | assert!(m.insert(1, 1).is_none()); |
6651 | |
6652 | assert!(m.contains_key(&1)); |
6653 | assert!(!m.contains_key(&0)); |
6654 | } |
6655 | |
6656 | #[test ] |
6657 | fn test_insert() { |
6658 | let mut m = HashMap::new(); |
6659 | assert_eq!(m.len(), 0); |
6660 | assert!(m.insert(1, 2).is_none()); |
6661 | assert_eq!(m.len(), 1); |
6662 | assert!(m.insert(2, 4).is_none()); |
6663 | assert_eq!(m.len(), 2); |
6664 | assert_eq!(*m.get(&1).unwrap(), 2); |
6665 | assert_eq!(*m.get(&2).unwrap(), 4); |
6666 | } |
6667 | |
6668 | #[test ] |
6669 | fn test_clone() { |
6670 | let mut m = HashMap::new(); |
6671 | assert_eq!(m.len(), 0); |
6672 | assert!(m.insert(1, 2).is_none()); |
6673 | assert_eq!(m.len(), 1); |
6674 | assert!(m.insert(2, 4).is_none()); |
6675 | assert_eq!(m.len(), 2); |
6676 | #[allow (clippy::redundant_clone)] |
6677 | let m2 = m.clone(); |
6678 | assert_eq!(*m2.get(&1).unwrap(), 2); |
6679 | assert_eq!(*m2.get(&2).unwrap(), 4); |
6680 | assert_eq!(m2.len(), 2); |
6681 | } |
6682 | |
6683 | #[test ] |
6684 | fn test_clone_from() { |
6685 | let mut m = HashMap::new(); |
6686 | let mut m2 = HashMap::new(); |
6687 | assert_eq!(m.len(), 0); |
6688 | assert!(m.insert(1, 2).is_none()); |
6689 | assert_eq!(m.len(), 1); |
6690 | assert!(m.insert(2, 4).is_none()); |
6691 | assert_eq!(m.len(), 2); |
6692 | m2.clone_from(&m); |
6693 | assert_eq!(*m2.get(&1).unwrap(), 2); |
6694 | assert_eq!(*m2.get(&2).unwrap(), 4); |
6695 | assert_eq!(m2.len(), 2); |
6696 | } |
6697 | |
6698 | thread_local! { static DROP_VECTOR: RefCell<Vec<i32>> = RefCell::new(Vec::new()) } |
6699 | |
6700 | #[derive (Hash, PartialEq, Eq)] |
6701 | struct Droppable { |
6702 | k: usize, |
6703 | } |
6704 | |
6705 | impl Droppable { |
6706 | fn new(k: usize) -> Droppable { |
6707 | DROP_VECTOR.with(|slot| { |
6708 | slot.borrow_mut()[k] += 1; |
6709 | }); |
6710 | |
6711 | Droppable { k } |
6712 | } |
6713 | } |
6714 | |
6715 | impl Drop for Droppable { |
6716 | fn drop(&mut self) { |
6717 | DROP_VECTOR.with(|slot| { |
6718 | slot.borrow_mut()[self.k] -= 1; |
6719 | }); |
6720 | } |
6721 | } |
6722 | |
6723 | impl Clone for Droppable { |
6724 | fn clone(&self) -> Self { |
6725 | Droppable::new(self.k) |
6726 | } |
6727 | } |
6728 | |
6729 | #[test ] |
6730 | fn test_drops() { |
6731 | DROP_VECTOR.with(|slot| { |
6732 | *slot.borrow_mut() = vec![0; 200]; |
6733 | }); |
6734 | |
6735 | { |
6736 | let mut m = HashMap::new(); |
6737 | |
6738 | DROP_VECTOR.with(|v| { |
6739 | for i in 0..200 { |
6740 | assert_eq!(v.borrow()[i], 0); |
6741 | } |
6742 | }); |
6743 | |
6744 | for i in 0..100 { |
6745 | let d1 = Droppable::new(i); |
6746 | let d2 = Droppable::new(i + 100); |
6747 | m.insert(d1, d2); |
6748 | } |
6749 | |
6750 | DROP_VECTOR.with(|v| { |
6751 | for i in 0..200 { |
6752 | assert_eq!(v.borrow()[i], 1); |
6753 | } |
6754 | }); |
6755 | |
6756 | for i in 0..50 { |
6757 | let k = Droppable::new(i); |
6758 | let v = m.remove(&k); |
6759 | |
6760 | assert!(v.is_some()); |
6761 | |
6762 | DROP_VECTOR.with(|v| { |
6763 | assert_eq!(v.borrow()[i], 1); |
6764 | assert_eq!(v.borrow()[i + 100], 1); |
6765 | }); |
6766 | } |
6767 | |
6768 | DROP_VECTOR.with(|v| { |
6769 | for i in 0..50 { |
6770 | assert_eq!(v.borrow()[i], 0); |
6771 | assert_eq!(v.borrow()[i + 100], 0); |
6772 | } |
6773 | |
6774 | for i in 50..100 { |
6775 | assert_eq!(v.borrow()[i], 1); |
6776 | assert_eq!(v.borrow()[i + 100], 1); |
6777 | } |
6778 | }); |
6779 | } |
6780 | |
6781 | DROP_VECTOR.with(|v| { |
6782 | for i in 0..200 { |
6783 | assert_eq!(v.borrow()[i], 0); |
6784 | } |
6785 | }); |
6786 | } |
6787 | |
6788 | #[test ] |
6789 | fn test_into_iter_drops() { |
6790 | DROP_VECTOR.with(|v| { |
6791 | *v.borrow_mut() = vec![0; 200]; |
6792 | }); |
6793 | |
6794 | let hm = { |
6795 | let mut hm = HashMap::new(); |
6796 | |
6797 | DROP_VECTOR.with(|v| { |
6798 | for i in 0..200 { |
6799 | assert_eq!(v.borrow()[i], 0); |
6800 | } |
6801 | }); |
6802 | |
6803 | for i in 0..100 { |
6804 | let d1 = Droppable::new(i); |
6805 | let d2 = Droppable::new(i + 100); |
6806 | hm.insert(d1, d2); |
6807 | } |
6808 | |
6809 | DROP_VECTOR.with(|v| { |
6810 | for i in 0..200 { |
6811 | assert_eq!(v.borrow()[i], 1); |
6812 | } |
6813 | }); |
6814 | |
6815 | hm |
6816 | }; |
6817 | |
6818 | // By the way, ensure that cloning doesn't screw up the dropping. |
6819 | drop(hm.clone()); |
6820 | |
6821 | { |
6822 | let mut half = hm.into_iter().take(50); |
6823 | |
6824 | DROP_VECTOR.with(|v| { |
6825 | for i in 0..200 { |
6826 | assert_eq!(v.borrow()[i], 1); |
6827 | } |
6828 | }); |
6829 | |
6830 | #[allow (clippy::let_underscore_drop)] // kind-of a false positive |
6831 | for _ in half.by_ref() {} |
6832 | |
6833 | DROP_VECTOR.with(|v| { |
6834 | let nk = (0..100).filter(|&i| v.borrow()[i] == 1).count(); |
6835 | |
6836 | let nv = (0..100).filter(|&i| v.borrow()[i + 100] == 1).count(); |
6837 | |
6838 | assert_eq!(nk, 50); |
6839 | assert_eq!(nv, 50); |
6840 | }); |
6841 | }; |
6842 | |
6843 | DROP_VECTOR.with(|v| { |
6844 | for i in 0..200 { |
6845 | assert_eq!(v.borrow()[i], 0); |
6846 | } |
6847 | }); |
6848 | } |
6849 | |
6850 | #[test ] |
6851 | fn test_empty_remove() { |
6852 | let mut m: HashMap<i32, bool> = HashMap::new(); |
6853 | assert_eq!(m.remove(&0), None); |
6854 | } |
6855 | |
6856 | #[test ] |
6857 | fn test_empty_entry() { |
6858 | let mut m: HashMap<i32, bool> = HashMap::new(); |
6859 | match m.entry(0) { |
6860 | Occupied(_) => panic!(), |
6861 | Vacant(_) => {} |
6862 | } |
6863 | assert!(*m.entry(0).or_insert(true)); |
6864 | assert_eq!(m.len(), 1); |
6865 | } |
6866 | |
6867 | #[test ] |
6868 | fn test_empty_entry_ref() { |
6869 | let mut m: HashMap<std::string::String, bool> = HashMap::new(); |
6870 | match m.entry_ref("poneyland" ) { |
6871 | EntryRef::Occupied(_) => panic!(), |
6872 | EntryRef::Vacant(_) => {} |
6873 | } |
6874 | assert!(*m.entry_ref("poneyland" ).or_insert(true)); |
6875 | assert_eq!(m.len(), 1); |
6876 | } |
6877 | |
6878 | #[test ] |
6879 | fn test_empty_iter() { |
6880 | let mut m: HashMap<i32, bool> = HashMap::new(); |
6881 | assert_eq!(m.drain().next(), None); |
6882 | assert_eq!(m.keys().next(), None); |
6883 | assert_eq!(m.values().next(), None); |
6884 | assert_eq!(m.values_mut().next(), None); |
6885 | assert_eq!(m.iter().next(), None); |
6886 | assert_eq!(m.iter_mut().next(), None); |
6887 | assert_eq!(m.len(), 0); |
6888 | assert!(m.is_empty()); |
6889 | assert_eq!(m.into_iter().next(), None); |
6890 | } |
6891 | |
6892 | #[test ] |
6893 | #[cfg_attr (miri, ignore)] // FIXME: takes too long |
6894 | fn test_lots_of_insertions() { |
6895 | let mut m = HashMap::new(); |
6896 | |
6897 | // Try this a few times to make sure we never screw up the hashmap's |
6898 | // internal state. |
6899 | for _ in 0..10 { |
6900 | assert!(m.is_empty()); |
6901 | |
6902 | for i in 1..1001 { |
6903 | assert!(m.insert(i, i).is_none()); |
6904 | |
6905 | for j in 1..=i { |
6906 | let r = m.get(&j); |
6907 | assert_eq!(r, Some(&j)); |
6908 | } |
6909 | |
6910 | for j in i + 1..1001 { |
6911 | let r = m.get(&j); |
6912 | assert_eq!(r, None); |
6913 | } |
6914 | } |
6915 | |
6916 | for i in 1001..2001 { |
6917 | assert!(!m.contains_key(&i)); |
6918 | } |
6919 | |
6920 | // remove forwards |
6921 | for i in 1..1001 { |
6922 | assert!(m.remove(&i).is_some()); |
6923 | |
6924 | for j in 1..=i { |
6925 | assert!(!m.contains_key(&j)); |
6926 | } |
6927 | |
6928 | for j in i + 1..1001 { |
6929 | assert!(m.contains_key(&j)); |
6930 | } |
6931 | } |
6932 | |
6933 | for i in 1..1001 { |
6934 | assert!(!m.contains_key(&i)); |
6935 | } |
6936 | |
6937 | for i in 1..1001 { |
6938 | assert!(m.insert(i, i).is_none()); |
6939 | } |
6940 | |
6941 | // remove backwards |
6942 | for i in (1..1001).rev() { |
6943 | assert!(m.remove(&i).is_some()); |
6944 | |
6945 | for j in i..1001 { |
6946 | assert!(!m.contains_key(&j)); |
6947 | } |
6948 | |
6949 | for j in 1..i { |
6950 | assert!(m.contains_key(&j)); |
6951 | } |
6952 | } |
6953 | } |
6954 | } |
6955 | |
6956 | #[test ] |
6957 | fn test_find_mut() { |
6958 | let mut m = HashMap::new(); |
6959 | assert!(m.insert(1, 12).is_none()); |
6960 | assert!(m.insert(2, 8).is_none()); |
6961 | assert!(m.insert(5, 14).is_none()); |
6962 | let new = 100; |
6963 | match m.get_mut(&5) { |
6964 | None => panic!(), |
6965 | Some(x) => *x = new, |
6966 | } |
6967 | assert_eq!(m.get(&5), Some(&new)); |
6968 | } |
6969 | |
6970 | #[test ] |
6971 | fn test_insert_overwrite() { |
6972 | let mut m = HashMap::new(); |
6973 | assert!(m.insert(1, 2).is_none()); |
6974 | assert_eq!(*m.get(&1).unwrap(), 2); |
6975 | assert!(m.insert(1, 3).is_some()); |
6976 | assert_eq!(*m.get(&1).unwrap(), 3); |
6977 | } |
6978 | |
6979 | #[test ] |
6980 | fn test_insert_conflicts() { |
6981 | let mut m = HashMap::with_capacity(4); |
6982 | assert!(m.insert(1, 2).is_none()); |
6983 | assert!(m.insert(5, 3).is_none()); |
6984 | assert!(m.insert(9, 4).is_none()); |
6985 | assert_eq!(*m.get(&9).unwrap(), 4); |
6986 | assert_eq!(*m.get(&5).unwrap(), 3); |
6987 | assert_eq!(*m.get(&1).unwrap(), 2); |
6988 | } |
6989 | |
6990 | #[test ] |
6991 | fn test_conflict_remove() { |
6992 | let mut m = HashMap::with_capacity(4); |
6993 | assert!(m.insert(1, 2).is_none()); |
6994 | assert_eq!(*m.get(&1).unwrap(), 2); |
6995 | assert!(m.insert(5, 3).is_none()); |
6996 | assert_eq!(*m.get(&1).unwrap(), 2); |
6997 | assert_eq!(*m.get(&5).unwrap(), 3); |
6998 | assert!(m.insert(9, 4).is_none()); |
6999 | assert_eq!(*m.get(&1).unwrap(), 2); |
7000 | assert_eq!(*m.get(&5).unwrap(), 3); |
7001 | assert_eq!(*m.get(&9).unwrap(), 4); |
7002 | assert!(m.remove(&1).is_some()); |
7003 | assert_eq!(*m.get(&9).unwrap(), 4); |
7004 | assert_eq!(*m.get(&5).unwrap(), 3); |
7005 | } |
7006 | |
7007 | #[test ] |
7008 | fn test_insert_unique_unchecked() { |
7009 | let mut map = HashMap::new(); |
7010 | let (k1, v1) = map.insert_unique_unchecked(10, 11); |
7011 | assert_eq!((&10, &mut 11), (k1, v1)); |
7012 | let (k2, v2) = map.insert_unique_unchecked(20, 21); |
7013 | assert_eq!((&20, &mut 21), (k2, v2)); |
7014 | assert_eq!(Some(&11), map.get(&10)); |
7015 | assert_eq!(Some(&21), map.get(&20)); |
7016 | assert_eq!(None, map.get(&30)); |
7017 | } |
7018 | |
7019 | #[test ] |
7020 | fn test_is_empty() { |
7021 | let mut m = HashMap::with_capacity(4); |
7022 | assert!(m.insert(1, 2).is_none()); |
7023 | assert!(!m.is_empty()); |
7024 | assert!(m.remove(&1).is_some()); |
7025 | assert!(m.is_empty()); |
7026 | } |
7027 | |
7028 | #[test ] |
7029 | fn test_remove() { |
7030 | let mut m = HashMap::new(); |
7031 | m.insert(1, 2); |
7032 | assert_eq!(m.remove(&1), Some(2)); |
7033 | assert_eq!(m.remove(&1), None); |
7034 | } |
7035 | |
7036 | #[test ] |
7037 | fn test_remove_entry() { |
7038 | let mut m = HashMap::new(); |
7039 | m.insert(1, 2); |
7040 | assert_eq!(m.remove_entry(&1), Some((1, 2))); |
7041 | assert_eq!(m.remove(&1), None); |
7042 | } |
7043 | |
7044 | #[test ] |
7045 | fn test_iterate() { |
7046 | let mut m = HashMap::with_capacity(4); |
7047 | for i in 0..32 { |
7048 | assert!(m.insert(i, i * 2).is_none()); |
7049 | } |
7050 | assert_eq!(m.len(), 32); |
7051 | |
7052 | let mut observed: u32 = 0; |
7053 | |
7054 | for (k, v) in &m { |
7055 | assert_eq!(*v, *k * 2); |
7056 | observed |= 1 << *k; |
7057 | } |
7058 | assert_eq!(observed, 0xFFFF_FFFF); |
7059 | } |
7060 | |
7061 | #[test ] |
7062 | fn test_keys() { |
7063 | let vec = vec![(1, 'a' ), (2, 'b' ), (3, 'c' )]; |
7064 | let map: HashMap<_, _> = vec.into_iter().collect(); |
7065 | let keys: Vec<_> = map.keys().copied().collect(); |
7066 | assert_eq!(keys.len(), 3); |
7067 | assert!(keys.contains(&1)); |
7068 | assert!(keys.contains(&2)); |
7069 | assert!(keys.contains(&3)); |
7070 | } |
7071 | |
7072 | #[test ] |
7073 | fn test_values() { |
7074 | let vec = vec![(1, 'a' ), (2, 'b' ), (3, 'c' )]; |
7075 | let map: HashMap<_, _> = vec.into_iter().collect(); |
7076 | let values: Vec<_> = map.values().copied().collect(); |
7077 | assert_eq!(values.len(), 3); |
7078 | assert!(values.contains(&'a' )); |
7079 | assert!(values.contains(&'b' )); |
7080 | assert!(values.contains(&'c' )); |
7081 | } |
7082 | |
7083 | #[test ] |
7084 | fn test_values_mut() { |
7085 | let vec = vec![(1, 1), (2, 2), (3, 3)]; |
7086 | let mut map: HashMap<_, _> = vec.into_iter().collect(); |
7087 | for value in map.values_mut() { |
7088 | *value *= 2; |
7089 | } |
7090 | let values: Vec<_> = map.values().copied().collect(); |
7091 | assert_eq!(values.len(), 3); |
7092 | assert!(values.contains(&2)); |
7093 | assert!(values.contains(&4)); |
7094 | assert!(values.contains(&6)); |
7095 | } |
7096 | |
7097 | #[test ] |
7098 | fn test_into_keys() { |
7099 | let vec = vec![(1, 'a' ), (2, 'b' ), (3, 'c' )]; |
7100 | let map: HashMap<_, _> = vec.into_iter().collect(); |
7101 | let keys: Vec<_> = map.into_keys().collect(); |
7102 | |
7103 | assert_eq!(keys.len(), 3); |
7104 | assert!(keys.contains(&1)); |
7105 | assert!(keys.contains(&2)); |
7106 | assert!(keys.contains(&3)); |
7107 | } |
7108 | |
7109 | #[test ] |
7110 | fn test_into_values() { |
7111 | let vec = vec![(1, 'a' ), (2, 'b' ), (3, 'c' )]; |
7112 | let map: HashMap<_, _> = vec.into_iter().collect(); |
7113 | let values: Vec<_> = map.into_values().collect(); |
7114 | |
7115 | assert_eq!(values.len(), 3); |
7116 | assert!(values.contains(&'a' )); |
7117 | assert!(values.contains(&'b' )); |
7118 | assert!(values.contains(&'c' )); |
7119 | } |
7120 | |
7121 | #[test ] |
7122 | fn test_find() { |
7123 | let mut m = HashMap::new(); |
7124 | assert!(m.get(&1).is_none()); |
7125 | m.insert(1, 2); |
7126 | match m.get(&1) { |
7127 | None => panic!(), |
7128 | Some(v) => assert_eq!(*v, 2), |
7129 | } |
7130 | } |
7131 | |
7132 | #[test ] |
7133 | fn test_eq() { |
7134 | let mut m1 = HashMap::new(); |
7135 | m1.insert(1, 2); |
7136 | m1.insert(2, 3); |
7137 | m1.insert(3, 4); |
7138 | |
7139 | let mut m2 = HashMap::new(); |
7140 | m2.insert(1, 2); |
7141 | m2.insert(2, 3); |
7142 | |
7143 | assert!(m1 != m2); |
7144 | |
7145 | m2.insert(3, 4); |
7146 | |
7147 | assert_eq!(m1, m2); |
7148 | } |
7149 | |
7150 | #[test ] |
7151 | fn test_show() { |
7152 | let mut map = HashMap::new(); |
7153 | let empty: HashMap<i32, i32> = HashMap::new(); |
7154 | |
7155 | map.insert(1, 2); |
7156 | map.insert(3, 4); |
7157 | |
7158 | let map_str = format!("{:?}" , map); |
7159 | |
7160 | assert!(map_str == "{1: 2, 3: 4}" || map_str == "{3: 4, 1: 2}" ); |
7161 | assert_eq!(format!("{:?}" , empty), "{}" ); |
7162 | } |
7163 | |
7164 | #[test ] |
7165 | fn test_expand() { |
7166 | let mut m = HashMap::new(); |
7167 | |
7168 | assert_eq!(m.len(), 0); |
7169 | assert!(m.is_empty()); |
7170 | |
7171 | let mut i = 0; |
7172 | let old_raw_cap = m.raw_capacity(); |
7173 | while old_raw_cap == m.raw_capacity() { |
7174 | m.insert(i, i); |
7175 | i += 1; |
7176 | } |
7177 | |
7178 | assert_eq!(m.len(), i); |
7179 | assert!(!m.is_empty()); |
7180 | } |
7181 | |
7182 | #[test ] |
7183 | fn test_behavior_resize_policy() { |
7184 | let mut m = HashMap::new(); |
7185 | |
7186 | assert_eq!(m.len(), 0); |
7187 | assert_eq!(m.raw_capacity(), 1); |
7188 | assert!(m.is_empty()); |
7189 | |
7190 | m.insert(0, 0); |
7191 | m.remove(&0); |
7192 | assert!(m.is_empty()); |
7193 | let initial_raw_cap = m.raw_capacity(); |
7194 | m.reserve(initial_raw_cap); |
7195 | let raw_cap = m.raw_capacity(); |
7196 | |
7197 | assert_eq!(raw_cap, initial_raw_cap * 2); |
7198 | |
7199 | let mut i = 0; |
7200 | for _ in 0..raw_cap * 3 / 4 { |
7201 | m.insert(i, i); |
7202 | i += 1; |
7203 | } |
7204 | // three quarters full |
7205 | |
7206 | assert_eq!(m.len(), i); |
7207 | assert_eq!(m.raw_capacity(), raw_cap); |
7208 | |
7209 | for _ in 0..raw_cap / 4 { |
7210 | m.insert(i, i); |
7211 | i += 1; |
7212 | } |
7213 | // half full |
7214 | |
7215 | let new_raw_cap = m.raw_capacity(); |
7216 | assert_eq!(new_raw_cap, raw_cap * 2); |
7217 | |
7218 | for _ in 0..raw_cap / 2 - 1 { |
7219 | i -= 1; |
7220 | m.remove(&i); |
7221 | assert_eq!(m.raw_capacity(), new_raw_cap); |
7222 | } |
7223 | // A little more than one quarter full. |
7224 | m.shrink_to_fit(); |
7225 | assert_eq!(m.raw_capacity(), raw_cap); |
7226 | // again, a little more than half full |
7227 | for _ in 0..raw_cap / 2 { |
7228 | i -= 1; |
7229 | m.remove(&i); |
7230 | } |
7231 | m.shrink_to_fit(); |
7232 | |
7233 | assert_eq!(m.len(), i); |
7234 | assert!(!m.is_empty()); |
7235 | assert_eq!(m.raw_capacity(), initial_raw_cap); |
7236 | } |
7237 | |
7238 | #[test ] |
7239 | fn test_reserve_shrink_to_fit() { |
7240 | let mut m = HashMap::new(); |
7241 | m.insert(0, 0); |
7242 | m.remove(&0); |
7243 | assert!(m.capacity() >= m.len()); |
7244 | for i in 0..128 { |
7245 | m.insert(i, i); |
7246 | } |
7247 | m.reserve(256); |
7248 | |
7249 | let usable_cap = m.capacity(); |
7250 | for i in 128..(128 + 256) { |
7251 | m.insert(i, i); |
7252 | assert_eq!(m.capacity(), usable_cap); |
7253 | } |
7254 | |
7255 | for i in 100..(128 + 256) { |
7256 | assert_eq!(m.remove(&i), Some(i)); |
7257 | } |
7258 | m.shrink_to_fit(); |
7259 | |
7260 | assert_eq!(m.len(), 100); |
7261 | assert!(!m.is_empty()); |
7262 | assert!(m.capacity() >= m.len()); |
7263 | |
7264 | for i in 0..100 { |
7265 | assert_eq!(m.remove(&i), Some(i)); |
7266 | } |
7267 | m.shrink_to_fit(); |
7268 | m.insert(0, 0); |
7269 | |
7270 | assert_eq!(m.len(), 1); |
7271 | assert!(m.capacity() >= m.len()); |
7272 | assert_eq!(m.remove(&0), Some(0)); |
7273 | } |
7274 | |
7275 | #[test ] |
7276 | fn test_from_iter() { |
7277 | let xs = [(1, 1), (2, 2), (2, 2), (3, 3), (4, 4), (5, 5), (6, 6)]; |
7278 | |
7279 | let map: HashMap<_, _> = xs.iter().copied().collect(); |
7280 | |
7281 | for &(k, v) in &xs { |
7282 | assert_eq!(map.get(&k), Some(&v)); |
7283 | } |
7284 | |
7285 | assert_eq!(map.iter().len(), xs.len() - 1); |
7286 | } |
7287 | |
7288 | #[test ] |
7289 | fn test_size_hint() { |
7290 | let xs = [(1, 1), (2, 2), (3, 3), (4, 4), (5, 5), (6, 6)]; |
7291 | |
7292 | let map: HashMap<_, _> = xs.iter().copied().collect(); |
7293 | |
7294 | let mut iter = map.iter(); |
7295 | |
7296 | for _ in iter.by_ref().take(3) {} |
7297 | |
7298 | assert_eq!(iter.size_hint(), (3, Some(3))); |
7299 | } |
7300 | |
7301 | #[test ] |
7302 | fn test_iter_len() { |
7303 | let xs = [(1, 1), (2, 2), (3, 3), (4, 4), (5, 5), (6, 6)]; |
7304 | |
7305 | let map: HashMap<_, _> = xs.iter().copied().collect(); |
7306 | |
7307 | let mut iter = map.iter(); |
7308 | |
7309 | for _ in iter.by_ref().take(3) {} |
7310 | |
7311 | assert_eq!(iter.len(), 3); |
7312 | } |
7313 | |
7314 | #[test ] |
7315 | fn test_mut_size_hint() { |
7316 | let xs = [(1, 1), (2, 2), (3, 3), (4, 4), (5, 5), (6, 6)]; |
7317 | |
7318 | let mut map: HashMap<_, _> = xs.iter().copied().collect(); |
7319 | |
7320 | let mut iter = map.iter_mut(); |
7321 | |
7322 | for _ in iter.by_ref().take(3) {} |
7323 | |
7324 | assert_eq!(iter.size_hint(), (3, Some(3))); |
7325 | } |
7326 | |
7327 | #[test ] |
7328 | fn test_iter_mut_len() { |
7329 | let xs = [(1, 1), (2, 2), (3, 3), (4, 4), (5, 5), (6, 6)]; |
7330 | |
7331 | let mut map: HashMap<_, _> = xs.iter().copied().collect(); |
7332 | |
7333 | let mut iter = map.iter_mut(); |
7334 | |
7335 | for _ in iter.by_ref().take(3) {} |
7336 | |
7337 | assert_eq!(iter.len(), 3); |
7338 | } |
7339 | |
7340 | #[test ] |
7341 | fn test_index() { |
7342 | let mut map = HashMap::new(); |
7343 | |
7344 | map.insert(1, 2); |
7345 | map.insert(2, 1); |
7346 | map.insert(3, 4); |
7347 | |
7348 | assert_eq!(map[&2], 1); |
7349 | } |
7350 | |
7351 | #[test ] |
7352 | #[should_panic ] |
7353 | fn test_index_nonexistent() { |
7354 | let mut map = HashMap::new(); |
7355 | |
7356 | map.insert(1, 2); |
7357 | map.insert(2, 1); |
7358 | map.insert(3, 4); |
7359 | |
7360 | #[allow (clippy::no_effect)] // false positive lint |
7361 | map[&4]; |
7362 | } |
7363 | |
7364 | #[test ] |
7365 | fn test_entry() { |
7366 | let xs = [(1, 10), (2, 20), (3, 30), (4, 40), (5, 50), (6, 60)]; |
7367 | |
7368 | let mut map: HashMap<_, _> = xs.iter().copied().collect(); |
7369 | |
7370 | // Existing key (insert) |
7371 | match map.entry(1) { |
7372 | Vacant(_) => unreachable!(), |
7373 | Occupied(mut view) => { |
7374 | assert_eq!(view.get(), &10); |
7375 | assert_eq!(view.insert(100), 10); |
7376 | } |
7377 | } |
7378 | assert_eq!(map.get(&1).unwrap(), &100); |
7379 | assert_eq!(map.len(), 6); |
7380 | |
7381 | // Existing key (update) |
7382 | match map.entry(2) { |
7383 | Vacant(_) => unreachable!(), |
7384 | Occupied(mut view) => { |
7385 | let v = view.get_mut(); |
7386 | let new_v = (*v) * 10; |
7387 | *v = new_v; |
7388 | } |
7389 | } |
7390 | assert_eq!(map.get(&2).unwrap(), &200); |
7391 | assert_eq!(map.len(), 6); |
7392 | |
7393 | // Existing key (take) |
7394 | match map.entry(3) { |
7395 | Vacant(_) => unreachable!(), |
7396 | Occupied(view) => { |
7397 | assert_eq!(view.remove(), 30); |
7398 | } |
7399 | } |
7400 | assert_eq!(map.get(&3), None); |
7401 | assert_eq!(map.len(), 5); |
7402 | |
7403 | // Inexistent key (insert) |
7404 | match map.entry(10) { |
7405 | Occupied(_) => unreachable!(), |
7406 | Vacant(view) => { |
7407 | assert_eq!(*view.insert(1000), 1000); |
7408 | } |
7409 | } |
7410 | assert_eq!(map.get(&10).unwrap(), &1000); |
7411 | assert_eq!(map.len(), 6); |
7412 | } |
7413 | |
7414 | #[test ] |
7415 | fn test_entry_ref() { |
7416 | let xs = [ |
7417 | ("One" .to_owned(), 10), |
7418 | ("Two" .to_owned(), 20), |
7419 | ("Three" .to_owned(), 30), |
7420 | ("Four" .to_owned(), 40), |
7421 | ("Five" .to_owned(), 50), |
7422 | ("Six" .to_owned(), 60), |
7423 | ]; |
7424 | |
7425 | let mut map: HashMap<_, _> = xs.iter().cloned().collect(); |
7426 | |
7427 | // Existing key (insert) |
7428 | match map.entry_ref("One" ) { |
7429 | EntryRef::Vacant(_) => unreachable!(), |
7430 | EntryRef::Occupied(mut view) => { |
7431 | assert_eq!(view.get(), &10); |
7432 | assert_eq!(view.insert(100), 10); |
7433 | } |
7434 | } |
7435 | assert_eq!(map.get("One" ).unwrap(), &100); |
7436 | assert_eq!(map.len(), 6); |
7437 | |
7438 | // Existing key (update) |
7439 | match map.entry_ref("Two" ) { |
7440 | EntryRef::Vacant(_) => unreachable!(), |
7441 | EntryRef::Occupied(mut view) => { |
7442 | let v = view.get_mut(); |
7443 | let new_v = (*v) * 10; |
7444 | *v = new_v; |
7445 | } |
7446 | } |
7447 | assert_eq!(map.get("Two" ).unwrap(), &200); |
7448 | assert_eq!(map.len(), 6); |
7449 | |
7450 | // Existing key (take) |
7451 | match map.entry_ref("Three" ) { |
7452 | EntryRef::Vacant(_) => unreachable!(), |
7453 | EntryRef::Occupied(view) => { |
7454 | assert_eq!(view.remove(), 30); |
7455 | } |
7456 | } |
7457 | assert_eq!(map.get("Three" ), None); |
7458 | assert_eq!(map.len(), 5); |
7459 | |
7460 | // Inexistent key (insert) |
7461 | match map.entry_ref("Ten" ) { |
7462 | EntryRef::Occupied(_) => unreachable!(), |
7463 | EntryRef::Vacant(view) => { |
7464 | assert_eq!(*view.insert(1000), 1000); |
7465 | } |
7466 | } |
7467 | assert_eq!(map.get("Ten" ).unwrap(), &1000); |
7468 | assert_eq!(map.len(), 6); |
7469 | } |
7470 | |
7471 | #[test ] |
7472 | fn test_entry_take_doesnt_corrupt() { |
7473 | #![allow (deprecated)] //rand |
7474 | // Test for #19292 |
7475 | fn check(m: &HashMap<i32, ()>) { |
7476 | for k in m.keys() { |
7477 | assert!(m.contains_key(k), " {} is in keys() but not in the map?" , k); |
7478 | } |
7479 | } |
7480 | |
7481 | let mut m = HashMap::new(); |
7482 | |
7483 | let mut rng = { |
7484 | let seed = u64::from_le_bytes(*b"testseed" ); |
7485 | SmallRng::seed_from_u64(seed) |
7486 | }; |
7487 | |
7488 | // Populate the map with some items. |
7489 | for _ in 0..50 { |
7490 | let x = rng.gen_range(-10..10); |
7491 | m.insert(x, ()); |
7492 | } |
7493 | |
7494 | for _ in 0..1000 { |
7495 | let x = rng.gen_range(-10..10); |
7496 | match m.entry(x) { |
7497 | Vacant(_) => {} |
7498 | Occupied(e) => { |
7499 | e.remove(); |
7500 | } |
7501 | } |
7502 | |
7503 | check(&m); |
7504 | } |
7505 | } |
7506 | |
7507 | #[test ] |
7508 | fn test_entry_ref_take_doesnt_corrupt() { |
7509 | #![allow (deprecated)] //rand |
7510 | // Test for #19292 |
7511 | fn check(m: &HashMap<std::string::String, ()>) { |
7512 | for k in m.keys() { |
7513 | assert!(m.contains_key(k), " {} is in keys() but not in the map?" , k); |
7514 | } |
7515 | } |
7516 | |
7517 | let mut m = HashMap::new(); |
7518 | |
7519 | let mut rng = { |
7520 | let seed = u64::from_le_bytes(*b"testseed" ); |
7521 | SmallRng::seed_from_u64(seed) |
7522 | }; |
7523 | |
7524 | // Populate the map with some items. |
7525 | for _ in 0..50 { |
7526 | let mut x = std::string::String::with_capacity(1); |
7527 | x.push(rng.gen_range('a' ..='z' )); |
7528 | m.insert(x, ()); |
7529 | } |
7530 | |
7531 | for _ in 0..1000 { |
7532 | let mut x = std::string::String::with_capacity(1); |
7533 | x.push(rng.gen_range('a' ..='z' )); |
7534 | match m.entry_ref(x.as_str()) { |
7535 | EntryRef::Vacant(_) => {} |
7536 | EntryRef::Occupied(e) => { |
7537 | e.remove(); |
7538 | } |
7539 | } |
7540 | |
7541 | check(&m); |
7542 | } |
7543 | } |
7544 | |
7545 | #[test ] |
7546 | fn test_extend_ref_k_ref_v() { |
7547 | let mut a = HashMap::new(); |
7548 | a.insert(1, "one" ); |
7549 | let mut b = HashMap::new(); |
7550 | b.insert(2, "two" ); |
7551 | b.insert(3, "three" ); |
7552 | |
7553 | a.extend(&b); |
7554 | |
7555 | assert_eq!(a.len(), 3); |
7556 | assert_eq!(a[&1], "one" ); |
7557 | assert_eq!(a[&2], "two" ); |
7558 | assert_eq!(a[&3], "three" ); |
7559 | } |
7560 | |
7561 | #[test ] |
7562 | fn test_extend_ref_kv_tuple() { |
7563 | use std::ops::AddAssign; |
7564 | let mut a = HashMap::new(); |
7565 | a.insert(0, 0); |
7566 | |
7567 | fn create_arr<T: AddAssign<T> + Copy, const N: usize>(start: T, step: T) -> [(T, T); N] { |
7568 | let mut outs: [(T, T); N] = [(start, start); N]; |
7569 | let mut element = step; |
7570 | outs.iter_mut().skip(1).for_each(|(k, v)| { |
7571 | *k += element; |
7572 | *v += element; |
7573 | element += step; |
7574 | }); |
7575 | outs |
7576 | } |
7577 | |
7578 | let for_iter: Vec<_> = (0..100).map(|i| (i, i)).collect(); |
7579 | let iter = for_iter.iter(); |
7580 | let vec: Vec<_> = (100..200).map(|i| (i, i)).collect(); |
7581 | a.extend(iter); |
7582 | a.extend(&vec); |
7583 | a.extend(&create_arr::<i32, 100>(200, 1)); |
7584 | |
7585 | assert_eq!(a.len(), 300); |
7586 | |
7587 | for item in 0..300 { |
7588 | assert_eq!(a[&item], item); |
7589 | } |
7590 | } |
7591 | |
7592 | #[test ] |
7593 | fn test_capacity_not_less_than_len() { |
7594 | let mut a = HashMap::new(); |
7595 | let mut item = 0; |
7596 | |
7597 | for _ in 0..116 { |
7598 | a.insert(item, 0); |
7599 | item += 1; |
7600 | } |
7601 | |
7602 | assert!(a.capacity() > a.len()); |
7603 | |
7604 | let free = a.capacity() - a.len(); |
7605 | for _ in 0..free { |
7606 | a.insert(item, 0); |
7607 | item += 1; |
7608 | } |
7609 | |
7610 | assert_eq!(a.len(), a.capacity()); |
7611 | |
7612 | // Insert at capacity should cause allocation. |
7613 | a.insert(item, 0); |
7614 | assert!(a.capacity() > a.len()); |
7615 | } |
7616 | |
7617 | #[test ] |
7618 | fn test_occupied_entry_key() { |
7619 | let mut a = HashMap::new(); |
7620 | let key = "hello there" ; |
7621 | let value = "value goes here" ; |
7622 | assert!(a.is_empty()); |
7623 | a.insert(key, value); |
7624 | assert_eq!(a.len(), 1); |
7625 | assert_eq!(a[key], value); |
7626 | |
7627 | match a.entry(key) { |
7628 | Vacant(_) => panic!(), |
7629 | Occupied(e) => assert_eq!(key, *e.key()), |
7630 | } |
7631 | assert_eq!(a.len(), 1); |
7632 | assert_eq!(a[key], value); |
7633 | } |
7634 | |
7635 | #[test ] |
7636 | fn test_occupied_entry_ref_key() { |
7637 | let mut a = HashMap::new(); |
7638 | let key = "hello there" ; |
7639 | let value = "value goes here" ; |
7640 | assert!(a.is_empty()); |
7641 | a.insert(key.to_owned(), value); |
7642 | assert_eq!(a.len(), 1); |
7643 | assert_eq!(a[key], value); |
7644 | |
7645 | match a.entry_ref(key) { |
7646 | EntryRef::Vacant(_) => panic!(), |
7647 | EntryRef::Occupied(e) => assert_eq!(key, e.key()), |
7648 | } |
7649 | assert_eq!(a.len(), 1); |
7650 | assert_eq!(a[key], value); |
7651 | } |
7652 | |
7653 | #[test ] |
7654 | fn test_vacant_entry_key() { |
7655 | let mut a = HashMap::new(); |
7656 | let key = "hello there" ; |
7657 | let value = "value goes here" ; |
7658 | |
7659 | assert!(a.is_empty()); |
7660 | match a.entry(key) { |
7661 | Occupied(_) => panic!(), |
7662 | Vacant(e) => { |
7663 | assert_eq!(key, *e.key()); |
7664 | e.insert(value); |
7665 | } |
7666 | } |
7667 | assert_eq!(a.len(), 1); |
7668 | assert_eq!(a[key], value); |
7669 | } |
7670 | |
7671 | #[test ] |
7672 | fn test_vacant_entry_ref_key() { |
7673 | let mut a: HashMap<std::string::String, &str> = HashMap::new(); |
7674 | let key = "hello there" ; |
7675 | let value = "value goes here" ; |
7676 | |
7677 | assert!(a.is_empty()); |
7678 | match a.entry_ref(key) { |
7679 | EntryRef::Occupied(_) => panic!(), |
7680 | EntryRef::Vacant(e) => { |
7681 | assert_eq!(key, e.key()); |
7682 | e.insert(value); |
7683 | } |
7684 | } |
7685 | assert_eq!(a.len(), 1); |
7686 | assert_eq!(a[key], value); |
7687 | } |
7688 | |
7689 | #[test ] |
7690 | fn test_occupied_entry_replace_entry_with() { |
7691 | let mut a = HashMap::new(); |
7692 | |
7693 | let key = "a key" ; |
7694 | let value = "an initial value" ; |
7695 | let new_value = "a new value" ; |
7696 | |
7697 | let entry = a.entry(key).insert(value).replace_entry_with(|k, v| { |
7698 | assert_eq!(k, &key); |
7699 | assert_eq!(v, value); |
7700 | Some(new_value) |
7701 | }); |
7702 | |
7703 | match entry { |
7704 | Occupied(e) => { |
7705 | assert_eq!(e.key(), &key); |
7706 | assert_eq!(e.get(), &new_value); |
7707 | } |
7708 | Vacant(_) => panic!(), |
7709 | } |
7710 | |
7711 | assert_eq!(a[key], new_value); |
7712 | assert_eq!(a.len(), 1); |
7713 | |
7714 | let entry = match a.entry(key) { |
7715 | Occupied(e) => e.replace_entry_with(|k, v| { |
7716 | assert_eq!(k, &key); |
7717 | assert_eq!(v, new_value); |
7718 | None |
7719 | }), |
7720 | Vacant(_) => panic!(), |
7721 | }; |
7722 | |
7723 | match entry { |
7724 | Vacant(e) => assert_eq!(e.key(), &key), |
7725 | Occupied(_) => panic!(), |
7726 | } |
7727 | |
7728 | assert!(!a.contains_key(key)); |
7729 | assert_eq!(a.len(), 0); |
7730 | } |
7731 | |
7732 | #[test ] |
7733 | fn test_occupied_entry_ref_replace_entry_with() { |
7734 | let mut a: HashMap<std::string::String, &str> = HashMap::new(); |
7735 | |
7736 | let key = "a key" ; |
7737 | let value = "an initial value" ; |
7738 | let new_value = "a new value" ; |
7739 | |
7740 | let entry = a.entry_ref(key).insert(value).replace_entry_with(|k, v| { |
7741 | assert_eq!(k, key); |
7742 | assert_eq!(v, value); |
7743 | Some(new_value) |
7744 | }); |
7745 | |
7746 | match entry { |
7747 | EntryRef::Occupied(e) => { |
7748 | assert_eq!(e.key(), key); |
7749 | assert_eq!(e.get(), &new_value); |
7750 | } |
7751 | EntryRef::Vacant(_) => panic!(), |
7752 | } |
7753 | |
7754 | assert_eq!(a[key], new_value); |
7755 | assert_eq!(a.len(), 1); |
7756 | |
7757 | let entry = match a.entry_ref(key) { |
7758 | EntryRef::Occupied(e) => e.replace_entry_with(|k, v| { |
7759 | assert_eq!(k, key); |
7760 | assert_eq!(v, new_value); |
7761 | None |
7762 | }), |
7763 | EntryRef::Vacant(_) => panic!(), |
7764 | }; |
7765 | |
7766 | match entry { |
7767 | EntryRef::Vacant(e) => assert_eq!(e.key(), key), |
7768 | EntryRef::Occupied(_) => panic!(), |
7769 | } |
7770 | |
7771 | assert!(!a.contains_key(key)); |
7772 | assert_eq!(a.len(), 0); |
7773 | } |
7774 | |
7775 | #[test ] |
7776 | fn test_entry_and_replace_entry_with() { |
7777 | let mut a = HashMap::new(); |
7778 | |
7779 | let key = "a key" ; |
7780 | let value = "an initial value" ; |
7781 | let new_value = "a new value" ; |
7782 | |
7783 | let entry = a.entry(key).and_replace_entry_with(|_, _| panic!()); |
7784 | |
7785 | match entry { |
7786 | Vacant(e) => assert_eq!(e.key(), &key), |
7787 | Occupied(_) => panic!(), |
7788 | } |
7789 | |
7790 | a.insert(key, value); |
7791 | |
7792 | let entry = a.entry(key).and_replace_entry_with(|k, v| { |
7793 | assert_eq!(k, &key); |
7794 | assert_eq!(v, value); |
7795 | Some(new_value) |
7796 | }); |
7797 | |
7798 | match entry { |
7799 | Occupied(e) => { |
7800 | assert_eq!(e.key(), &key); |
7801 | assert_eq!(e.get(), &new_value); |
7802 | } |
7803 | Vacant(_) => panic!(), |
7804 | } |
7805 | |
7806 | assert_eq!(a[key], new_value); |
7807 | assert_eq!(a.len(), 1); |
7808 | |
7809 | let entry = a.entry(key).and_replace_entry_with(|k, v| { |
7810 | assert_eq!(k, &key); |
7811 | assert_eq!(v, new_value); |
7812 | None |
7813 | }); |
7814 | |
7815 | match entry { |
7816 | Vacant(e) => assert_eq!(e.key(), &key), |
7817 | Occupied(_) => panic!(), |
7818 | } |
7819 | |
7820 | assert!(!a.contains_key(key)); |
7821 | assert_eq!(a.len(), 0); |
7822 | } |
7823 | |
7824 | #[test ] |
7825 | fn test_entry_ref_and_replace_entry_with() { |
7826 | let mut a = HashMap::new(); |
7827 | |
7828 | let key = "a key" ; |
7829 | let value = "an initial value" ; |
7830 | let new_value = "a new value" ; |
7831 | |
7832 | let entry = a.entry_ref(key).and_replace_entry_with(|_, _| panic!()); |
7833 | |
7834 | match entry { |
7835 | EntryRef::Vacant(e) => assert_eq!(e.key(), key), |
7836 | EntryRef::Occupied(_) => panic!(), |
7837 | } |
7838 | |
7839 | a.insert(key.to_owned(), value); |
7840 | |
7841 | let entry = a.entry_ref(key).and_replace_entry_with(|k, v| { |
7842 | assert_eq!(k, key); |
7843 | assert_eq!(v, value); |
7844 | Some(new_value) |
7845 | }); |
7846 | |
7847 | match entry { |
7848 | EntryRef::Occupied(e) => { |
7849 | assert_eq!(e.key(), key); |
7850 | assert_eq!(e.get(), &new_value); |
7851 | } |
7852 | EntryRef::Vacant(_) => panic!(), |
7853 | } |
7854 | |
7855 | assert_eq!(a[key], new_value); |
7856 | assert_eq!(a.len(), 1); |
7857 | |
7858 | let entry = a.entry_ref(key).and_replace_entry_with(|k, v| { |
7859 | assert_eq!(k, key); |
7860 | assert_eq!(v, new_value); |
7861 | None |
7862 | }); |
7863 | |
7864 | match entry { |
7865 | EntryRef::Vacant(e) => assert_eq!(e.key(), key), |
7866 | EntryRef::Occupied(_) => panic!(), |
7867 | } |
7868 | |
7869 | assert!(!a.contains_key(key)); |
7870 | assert_eq!(a.len(), 0); |
7871 | } |
7872 | |
7873 | #[test ] |
7874 | fn test_raw_occupied_entry_replace_entry_with() { |
7875 | let mut a = HashMap::new(); |
7876 | |
7877 | let key = "a key" ; |
7878 | let value = "an initial value" ; |
7879 | let new_value = "a new value" ; |
7880 | |
7881 | let entry = a |
7882 | .raw_entry_mut() |
7883 | .from_key(&key) |
7884 | .insert(key, value) |
7885 | .replace_entry_with(|k, v| { |
7886 | assert_eq!(k, &key); |
7887 | assert_eq!(v, value); |
7888 | Some(new_value) |
7889 | }); |
7890 | |
7891 | match entry { |
7892 | RawEntryMut::Occupied(e) => { |
7893 | assert_eq!(e.key(), &key); |
7894 | assert_eq!(e.get(), &new_value); |
7895 | } |
7896 | RawEntryMut::Vacant(_) => panic!(), |
7897 | } |
7898 | |
7899 | assert_eq!(a[key], new_value); |
7900 | assert_eq!(a.len(), 1); |
7901 | |
7902 | let entry = match a.raw_entry_mut().from_key(&key) { |
7903 | RawEntryMut::Occupied(e) => e.replace_entry_with(|k, v| { |
7904 | assert_eq!(k, &key); |
7905 | assert_eq!(v, new_value); |
7906 | None |
7907 | }), |
7908 | RawEntryMut::Vacant(_) => panic!(), |
7909 | }; |
7910 | |
7911 | match entry { |
7912 | RawEntryMut::Vacant(_) => {} |
7913 | RawEntryMut::Occupied(_) => panic!(), |
7914 | } |
7915 | |
7916 | assert!(!a.contains_key(key)); |
7917 | assert_eq!(a.len(), 0); |
7918 | } |
7919 | |
7920 | #[test ] |
7921 | fn test_raw_entry_and_replace_entry_with() { |
7922 | let mut a = HashMap::new(); |
7923 | |
7924 | let key = "a key" ; |
7925 | let value = "an initial value" ; |
7926 | let new_value = "a new value" ; |
7927 | |
7928 | let entry = a |
7929 | .raw_entry_mut() |
7930 | .from_key(&key) |
7931 | .and_replace_entry_with(|_, _| panic!()); |
7932 | |
7933 | match entry { |
7934 | RawEntryMut::Vacant(_) => {} |
7935 | RawEntryMut::Occupied(_) => panic!(), |
7936 | } |
7937 | |
7938 | a.insert(key, value); |
7939 | |
7940 | let entry = a |
7941 | .raw_entry_mut() |
7942 | .from_key(&key) |
7943 | .and_replace_entry_with(|k, v| { |
7944 | assert_eq!(k, &key); |
7945 | assert_eq!(v, value); |
7946 | Some(new_value) |
7947 | }); |
7948 | |
7949 | match entry { |
7950 | RawEntryMut::Occupied(e) => { |
7951 | assert_eq!(e.key(), &key); |
7952 | assert_eq!(e.get(), &new_value); |
7953 | } |
7954 | RawEntryMut::Vacant(_) => panic!(), |
7955 | } |
7956 | |
7957 | assert_eq!(a[key], new_value); |
7958 | assert_eq!(a.len(), 1); |
7959 | |
7960 | let entry = a |
7961 | .raw_entry_mut() |
7962 | .from_key(&key) |
7963 | .and_replace_entry_with(|k, v| { |
7964 | assert_eq!(k, &key); |
7965 | assert_eq!(v, new_value); |
7966 | None |
7967 | }); |
7968 | |
7969 | match entry { |
7970 | RawEntryMut::Vacant(_) => {} |
7971 | RawEntryMut::Occupied(_) => panic!(), |
7972 | } |
7973 | |
7974 | assert!(!a.contains_key(key)); |
7975 | assert_eq!(a.len(), 0); |
7976 | } |
7977 | |
7978 | #[test ] |
7979 | fn test_replace_entry_with_doesnt_corrupt() { |
7980 | #![allow (deprecated)] //rand |
7981 | // Test for #19292 |
7982 | fn check(m: &HashMap<i32, ()>) { |
7983 | for k in m.keys() { |
7984 | assert!(m.contains_key(k), " {} is in keys() but not in the map?" , k); |
7985 | } |
7986 | } |
7987 | |
7988 | let mut m = HashMap::new(); |
7989 | |
7990 | let mut rng = { |
7991 | let seed = u64::from_le_bytes(*b"testseed" ); |
7992 | SmallRng::seed_from_u64(seed) |
7993 | }; |
7994 | |
7995 | // Populate the map with some items. |
7996 | for _ in 0..50 { |
7997 | let x = rng.gen_range(-10..10); |
7998 | m.insert(x, ()); |
7999 | } |
8000 | |
8001 | for _ in 0..1000 { |
8002 | let x = rng.gen_range(-10..10); |
8003 | m.entry(x).and_replace_entry_with(|_, _| None); |
8004 | check(&m); |
8005 | } |
8006 | } |
8007 | |
8008 | #[test ] |
8009 | fn test_replace_entry_ref_with_doesnt_corrupt() { |
8010 | #![allow (deprecated)] //rand |
8011 | // Test for #19292 |
8012 | fn check(m: &HashMap<std::string::String, ()>) { |
8013 | for k in m.keys() { |
8014 | assert!(m.contains_key(k), " {} is in keys() but not in the map?" , k); |
8015 | } |
8016 | } |
8017 | |
8018 | let mut m = HashMap::new(); |
8019 | |
8020 | let mut rng = { |
8021 | let seed = u64::from_le_bytes(*b"testseed" ); |
8022 | SmallRng::seed_from_u64(seed) |
8023 | }; |
8024 | |
8025 | // Populate the map with some items. |
8026 | for _ in 0..50 { |
8027 | let mut x = std::string::String::with_capacity(1); |
8028 | x.push(rng.gen_range('a' ..='z' )); |
8029 | m.insert(x, ()); |
8030 | } |
8031 | |
8032 | for _ in 0..1000 { |
8033 | let mut x = std::string::String::with_capacity(1); |
8034 | x.push(rng.gen_range('a' ..='z' )); |
8035 | m.entry_ref(x.as_str()).and_replace_entry_with(|_, _| None); |
8036 | check(&m); |
8037 | } |
8038 | } |
8039 | |
8040 | #[test ] |
8041 | fn test_retain() { |
8042 | let mut map: HashMap<i32, i32> = (0..100).map(|x| (x, x * 10)).collect(); |
8043 | |
8044 | map.retain(|&k, _| k % 2 == 0); |
8045 | assert_eq!(map.len(), 50); |
8046 | assert_eq!(map[&2], 20); |
8047 | assert_eq!(map[&4], 40); |
8048 | assert_eq!(map[&6], 60); |
8049 | } |
8050 | |
8051 | #[test ] |
8052 | fn test_drain_filter() { |
8053 | { |
8054 | let mut map: HashMap<i32, i32> = (0..8).map(|x| (x, x * 10)).collect(); |
8055 | let drained = map.drain_filter(|&k, _| k % 2 == 0); |
8056 | let mut out = drained.collect::<Vec<_>>(); |
8057 | out.sort_unstable(); |
8058 | assert_eq!(vec![(0, 0), (2, 20), (4, 40), (6, 60)], out); |
8059 | assert_eq!(map.len(), 4); |
8060 | } |
8061 | { |
8062 | let mut map: HashMap<i32, i32> = (0..8).map(|x| (x, x * 10)).collect(); |
8063 | drop(map.drain_filter(|&k, _| k % 2 == 0)); |
8064 | assert_eq!(map.len(), 4); |
8065 | } |
8066 | } |
8067 | |
8068 | #[test ] |
8069 | #[cfg_attr (miri, ignore)] // FIXME: no OOM signalling (https://github.com/rust-lang/miri/issues/613) |
8070 | fn test_try_reserve() { |
8071 | use crate::TryReserveError::{AllocError, CapacityOverflow}; |
8072 | |
8073 | const MAX_USIZE: usize = usize::MAX; |
8074 | |
8075 | let mut empty_bytes: HashMap<u8, u8> = HashMap::new(); |
8076 | |
8077 | if let Err(CapacityOverflow) = empty_bytes.try_reserve(MAX_USIZE) { |
8078 | } else { |
8079 | panic!("usize::MAX should trigger an overflow!" ); |
8080 | } |
8081 | |
8082 | if let Err(AllocError { .. }) = empty_bytes.try_reserve(MAX_USIZE / 16) { |
8083 | } else { |
8084 | // This may succeed if there is enough free memory. Attempt to |
8085 | // allocate a few more hashmaps to ensure the allocation will fail. |
8086 | let mut empty_bytes2: HashMap<u8, u8> = HashMap::new(); |
8087 | let _ = empty_bytes2.try_reserve(MAX_USIZE / 16); |
8088 | let mut empty_bytes3: HashMap<u8, u8> = HashMap::new(); |
8089 | let _ = empty_bytes3.try_reserve(MAX_USIZE / 16); |
8090 | let mut empty_bytes4: HashMap<u8, u8> = HashMap::new(); |
8091 | if let Err(AllocError { .. }) = empty_bytes4.try_reserve(MAX_USIZE / 16) { |
8092 | } else { |
8093 | panic!("usize::MAX / 8 should trigger an OOM!" ); |
8094 | } |
8095 | } |
8096 | } |
8097 | |
8098 | #[test ] |
8099 | fn test_raw_entry() { |
8100 | use super::RawEntryMut::{Occupied, Vacant}; |
8101 | |
8102 | let xs = [(1_i32, 10_i32), (2, 20), (3, 30), (4, 40), (5, 50), (6, 60)]; |
8103 | |
8104 | let mut map: HashMap<_, _> = xs.iter().copied().collect(); |
8105 | |
8106 | let compute_hash = |map: &HashMap<i32, i32>, k: i32| -> u64 { |
8107 | super::make_insert_hash::<i32, _>(map.hasher(), &k) |
8108 | }; |
8109 | |
8110 | // Existing key (insert) |
8111 | match map.raw_entry_mut().from_key(&1) { |
8112 | Vacant(_) => unreachable!(), |
8113 | Occupied(mut view) => { |
8114 | assert_eq!(view.get(), &10); |
8115 | assert_eq!(view.insert(100), 10); |
8116 | } |
8117 | } |
8118 | let hash1 = compute_hash(&map, 1); |
8119 | assert_eq!(map.raw_entry().from_key(&1).unwrap(), (&1, &100)); |
8120 | assert_eq!( |
8121 | map.raw_entry().from_hash(hash1, |k| *k == 1).unwrap(), |
8122 | (&1, &100) |
8123 | ); |
8124 | assert_eq!( |
8125 | map.raw_entry().from_key_hashed_nocheck(hash1, &1).unwrap(), |
8126 | (&1, &100) |
8127 | ); |
8128 | assert_eq!(map.len(), 6); |
8129 | |
8130 | // Existing key (update) |
8131 | match map.raw_entry_mut().from_key(&2) { |
8132 | Vacant(_) => unreachable!(), |
8133 | Occupied(mut view) => { |
8134 | let v = view.get_mut(); |
8135 | let new_v = (*v) * 10; |
8136 | *v = new_v; |
8137 | } |
8138 | } |
8139 | let hash2 = compute_hash(&map, 2); |
8140 | assert_eq!(map.raw_entry().from_key(&2).unwrap(), (&2, &200)); |
8141 | assert_eq!( |
8142 | map.raw_entry().from_hash(hash2, |k| *k == 2).unwrap(), |
8143 | (&2, &200) |
8144 | ); |
8145 | assert_eq!( |
8146 | map.raw_entry().from_key_hashed_nocheck(hash2, &2).unwrap(), |
8147 | (&2, &200) |
8148 | ); |
8149 | assert_eq!(map.len(), 6); |
8150 | |
8151 | // Existing key (take) |
8152 | let hash3 = compute_hash(&map, 3); |
8153 | match map.raw_entry_mut().from_key_hashed_nocheck(hash3, &3) { |
8154 | Vacant(_) => unreachable!(), |
8155 | Occupied(view) => { |
8156 | assert_eq!(view.remove_entry(), (3, 30)); |
8157 | } |
8158 | } |
8159 | assert_eq!(map.raw_entry().from_key(&3), None); |
8160 | assert_eq!(map.raw_entry().from_hash(hash3, |k| *k == 3), None); |
8161 | assert_eq!(map.raw_entry().from_key_hashed_nocheck(hash3, &3), None); |
8162 | assert_eq!(map.len(), 5); |
8163 | |
8164 | // Nonexistent key (insert) |
8165 | match map.raw_entry_mut().from_key(&10) { |
8166 | Occupied(_) => unreachable!(), |
8167 | Vacant(view) => { |
8168 | assert_eq!(view.insert(10, 1000), (&mut 10, &mut 1000)); |
8169 | } |
8170 | } |
8171 | assert_eq!(map.raw_entry().from_key(&10).unwrap(), (&10, &1000)); |
8172 | assert_eq!(map.len(), 6); |
8173 | |
8174 | // Ensure all lookup methods produce equivalent results. |
8175 | for k in 0..12 { |
8176 | let hash = compute_hash(&map, k); |
8177 | let v = map.get(&k).copied(); |
8178 | let kv = v.as_ref().map(|v| (&k, v)); |
8179 | |
8180 | assert_eq!(map.raw_entry().from_key(&k), kv); |
8181 | assert_eq!(map.raw_entry().from_hash(hash, |q| *q == k), kv); |
8182 | assert_eq!(map.raw_entry().from_key_hashed_nocheck(hash, &k), kv); |
8183 | |
8184 | match map.raw_entry_mut().from_key(&k) { |
8185 | Occupied(o) => assert_eq!(Some(o.get_key_value()), kv), |
8186 | Vacant(_) => assert_eq!(v, None), |
8187 | } |
8188 | match map.raw_entry_mut().from_key_hashed_nocheck(hash, &k) { |
8189 | Occupied(o) => assert_eq!(Some(o.get_key_value()), kv), |
8190 | Vacant(_) => assert_eq!(v, None), |
8191 | } |
8192 | match map.raw_entry_mut().from_hash(hash, |q| *q == k) { |
8193 | Occupied(o) => assert_eq!(Some(o.get_key_value()), kv), |
8194 | Vacant(_) => assert_eq!(v, None), |
8195 | } |
8196 | } |
8197 | } |
8198 | |
8199 | #[test ] |
8200 | fn test_key_without_hash_impl() { |
8201 | #[derive (Debug)] |
8202 | struct IntWrapper(u64); |
8203 | |
8204 | let mut m: HashMap<IntWrapper, (), ()> = HashMap::default(); |
8205 | { |
8206 | assert!(m.raw_entry().from_hash(0, |k| k.0 == 0).is_none()); |
8207 | } |
8208 | { |
8209 | let vacant_entry = match m.raw_entry_mut().from_hash(0, |k| k.0 == 0) { |
8210 | RawEntryMut::Occupied(..) => panic!("Found entry for key 0" ), |
8211 | RawEntryMut::Vacant(e) => e, |
8212 | }; |
8213 | vacant_entry.insert_with_hasher(0, IntWrapper(0), (), |k| k.0); |
8214 | } |
8215 | { |
8216 | assert!(m.raw_entry().from_hash(0, |k| k.0 == 0).is_some()); |
8217 | assert!(m.raw_entry().from_hash(1, |k| k.0 == 1).is_none()); |
8218 | assert!(m.raw_entry().from_hash(2, |k| k.0 == 2).is_none()); |
8219 | } |
8220 | { |
8221 | let vacant_entry = match m.raw_entry_mut().from_hash(1, |k| k.0 == 1) { |
8222 | RawEntryMut::Occupied(..) => panic!("Found entry for key 1" ), |
8223 | RawEntryMut::Vacant(e) => e, |
8224 | }; |
8225 | vacant_entry.insert_with_hasher(1, IntWrapper(1), (), |k| k.0); |
8226 | } |
8227 | { |
8228 | assert!(m.raw_entry().from_hash(0, |k| k.0 == 0).is_some()); |
8229 | assert!(m.raw_entry().from_hash(1, |k| k.0 == 1).is_some()); |
8230 | assert!(m.raw_entry().from_hash(2, |k| k.0 == 2).is_none()); |
8231 | } |
8232 | { |
8233 | let occupied_entry = match m.raw_entry_mut().from_hash(0, |k| k.0 == 0) { |
8234 | RawEntryMut::Occupied(e) => e, |
8235 | RawEntryMut::Vacant(..) => panic!("Couldn't find entry for key 0" ), |
8236 | }; |
8237 | occupied_entry.remove(); |
8238 | } |
8239 | assert!(m.raw_entry().from_hash(0, |k| k.0 == 0).is_none()); |
8240 | assert!(m.raw_entry().from_hash(1, |k| k.0 == 1).is_some()); |
8241 | assert!(m.raw_entry().from_hash(2, |k| k.0 == 2).is_none()); |
8242 | } |
8243 | |
8244 | #[test ] |
8245 | #[cfg (feature = "raw" )] |
8246 | fn test_into_iter_refresh() { |
8247 | #[cfg (miri)] |
8248 | const N: usize = 32; |
8249 | #[cfg (not(miri))] |
8250 | const N: usize = 128; |
8251 | |
8252 | let mut rng = rand::thread_rng(); |
8253 | for n in 0..N { |
8254 | let mut map = HashMap::new(); |
8255 | for i in 0..n { |
8256 | assert!(map.insert(i, 2 * i).is_none()); |
8257 | } |
8258 | let hash_builder = map.hasher().clone(); |
8259 | |
8260 | let mut it = unsafe { map.table.iter() }; |
8261 | assert_eq!(it.len(), n); |
8262 | |
8263 | let mut i = 0; |
8264 | let mut left = n; |
8265 | let mut removed = Vec::new(); |
8266 | loop { |
8267 | // occasionally remove some elements |
8268 | if i < n && rng.gen_bool(0.1) { |
8269 | let hash_value = super::make_insert_hash(&hash_builder, &i); |
8270 | |
8271 | unsafe { |
8272 | let e = map.table.find(hash_value, |q| q.0.eq(&i)); |
8273 | if let Some(e) = e { |
8274 | it.reflect_remove(&e); |
8275 | let t = map.table.remove(e); |
8276 | removed.push(t); |
8277 | left -= 1; |
8278 | } else { |
8279 | assert!(removed.contains(&(i, 2 * i)), " {} not in {:?}" , i, removed); |
8280 | let e = map.table.insert( |
8281 | hash_value, |
8282 | (i, 2 * i), |
8283 | super::make_hasher::<usize, _, usize, _>(&hash_builder), |
8284 | ); |
8285 | it.reflect_insert(&e); |
8286 | if let Some(p) = removed.iter().position(|e| e == &(i, 2 * i)) { |
8287 | removed.swap_remove(p); |
8288 | } |
8289 | left += 1; |
8290 | } |
8291 | } |
8292 | } |
8293 | |
8294 | let e = it.next(); |
8295 | if e.is_none() { |
8296 | break; |
8297 | } |
8298 | assert!(i < n); |
8299 | let t = unsafe { e.unwrap().as_ref() }; |
8300 | assert!(!removed.contains(t)); |
8301 | let (key, value) = t; |
8302 | assert_eq!(*value, 2 * key); |
8303 | i += 1; |
8304 | } |
8305 | assert!(i <= n); |
8306 | |
8307 | // just for safety: |
8308 | assert_eq!(map.table.len(), left); |
8309 | } |
8310 | } |
8311 | |
8312 | #[test ] |
8313 | fn test_const_with_hasher() { |
8314 | use core::hash::BuildHasher; |
8315 | use std::collections::hash_map::DefaultHasher; |
8316 | |
8317 | #[derive (Clone)] |
8318 | struct MyHasher; |
8319 | impl BuildHasher for MyHasher { |
8320 | type Hasher = DefaultHasher; |
8321 | |
8322 | fn build_hasher(&self) -> DefaultHasher { |
8323 | DefaultHasher::new() |
8324 | } |
8325 | } |
8326 | |
8327 | const EMPTY_MAP: HashMap<u32, std::string::String, MyHasher> = |
8328 | HashMap::with_hasher(MyHasher); |
8329 | |
8330 | let mut map = EMPTY_MAP; |
8331 | map.insert(17, "seventeen" .to_owned()); |
8332 | assert_eq!("seventeen" , map[&17]); |
8333 | } |
8334 | |
8335 | #[test ] |
8336 | fn test_get_each_mut() { |
8337 | let mut map = HashMap::new(); |
8338 | map.insert("foo" .to_owned(), 0); |
8339 | map.insert("bar" .to_owned(), 10); |
8340 | map.insert("baz" .to_owned(), 20); |
8341 | map.insert("qux" .to_owned(), 30); |
8342 | |
8343 | let xs = map.get_many_mut(["foo" , "qux" ]); |
8344 | assert_eq!(xs, Some([&mut 0, &mut 30])); |
8345 | |
8346 | let xs = map.get_many_mut(["foo" , "dud" ]); |
8347 | assert_eq!(xs, None); |
8348 | |
8349 | let xs = map.get_many_mut(["foo" , "foo" ]); |
8350 | assert_eq!(xs, None); |
8351 | |
8352 | let ys = map.get_many_key_value_mut(["bar" , "baz" ]); |
8353 | assert_eq!( |
8354 | ys, |
8355 | Some([(&"bar" .to_owned(), &mut 10), (&"baz" .to_owned(), &mut 20),]), |
8356 | ); |
8357 | |
8358 | let ys = map.get_many_key_value_mut(["bar" , "dip" ]); |
8359 | assert_eq!(ys, None); |
8360 | |
8361 | let ys = map.get_many_key_value_mut(["baz" , "baz" ]); |
8362 | assert_eq!(ys, None); |
8363 | } |
8364 | |
8365 | #[test ] |
8366 | #[should_panic = "panic in drop" ] |
8367 | fn test_clone_from_double_drop() { |
8368 | #[derive (Clone)] |
8369 | struct CheckedDrop { |
8370 | panic_in_drop: bool, |
8371 | dropped: bool, |
8372 | } |
8373 | impl Drop for CheckedDrop { |
8374 | fn drop(&mut self) { |
8375 | if self.panic_in_drop { |
8376 | self.dropped = true; |
8377 | panic!("panic in drop" ); |
8378 | } |
8379 | if self.dropped { |
8380 | panic!("double drop" ); |
8381 | } |
8382 | self.dropped = true; |
8383 | } |
8384 | } |
8385 | const DISARMED: CheckedDrop = CheckedDrop { |
8386 | panic_in_drop: false, |
8387 | dropped: false, |
8388 | }; |
8389 | const ARMED: CheckedDrop = CheckedDrop { |
8390 | panic_in_drop: true, |
8391 | dropped: false, |
8392 | }; |
8393 | |
8394 | let mut map1 = HashMap::new(); |
8395 | map1.insert(1, DISARMED); |
8396 | map1.insert(2, DISARMED); |
8397 | map1.insert(3, DISARMED); |
8398 | map1.insert(4, DISARMED); |
8399 | |
8400 | let mut map2 = HashMap::new(); |
8401 | map2.insert(1, DISARMED); |
8402 | map2.insert(2, ARMED); |
8403 | map2.insert(3, DISARMED); |
8404 | map2.insert(4, DISARMED); |
8405 | |
8406 | map2.clone_from(&map1); |
8407 | } |
8408 | } |
8409 | |