rune_alloc/hashbrown/map.rs
1use core::borrow::Borrow;
2use core::convert::Infallible;
3use core::fmt::{self, Debug};
4use core::hash::{BuildHasher, Hash};
5use core::iter::FusedIterator;
6use core::marker::PhantomData;
7use core::mem;
8use core::ops::Index;
9
10use crate::alloc::{into_ok, into_ok_try};
11use crate::alloc::{Allocator, Global};
12use crate::clone::TryClone;
13use crate::error::{CustomError, Error};
14use crate::iter::{TryExtend, TryFromIteratorIn};
15#[cfg(test)]
16use crate::testing::*;
17
18use super::raw::{Bucket, RawDrain, RawIntoIter, RawIter, RawTable};
19use super::{Equivalent, ErrorOrInsertSlot, HasherFn};
20
21/// Default hasher for `HashMap`.
22pub type DefaultHashBuilder = core::hash::BuildHasherDefault<ahash::AHasher>;
23
24/// Default source of random state.
25pub type RandomState = ahash::RandomState;
26
27/// Default hasher.
28pub type Hasher = ahash::AHasher;
29
30/// A hash map implemented with quadratic probing and SIMD lookup.
31///
32/// The default hashing algorithm is currently [`AHash`], though this is
33/// subject to change at any point in the future. This hash function is very
34/// fast for all types of keys, but this algorithm will typically *not* protect
35/// against attacks such as HashDoS.
36///
37/// The hashing algorithm can be replaced on a per-`HashMap` basis using the
38/// [`default`], [`with_hasher`], and [`with_capacity_and_hasher`] methods. Many
39/// alternative algorithms are available on crates.io, such as the [`fnv`] crate.
40///
41/// It is required that the keys implement the [`Eq`] and [`Hash`] traits, although
42/// this can frequently be achieved by using `#[derive(PartialEq, Eq, Hash)]`.
43/// If you implement these yourself, it is important that the following
44/// property holds:
45///
46/// ```text
47/// k1 == k2 -> hash(k1) == hash(k2)
48/// ```
49///
50/// In other words, if two keys are equal, their hashes must be equal.
51///
52/// It is a logic error for a key to be modified in such a way that the key's
53/// hash, as determined by the [`Hash`] trait, or its equality, as determined by
54/// the [`Eq`] trait, changes while it is in the map. This is normally only
55/// possible through [`Cell`], [`RefCell`], global state, I/O, or unsafe code.
56///
57/// It is also a logic error for the [`Hash`] implementation of a key to panic.
58/// This is generally only possible if the trait is implemented manually. If a
59/// panic does occur then the contents of the `HashMap` may become corrupted and
60/// some items may be dropped from the table.
61///
62/// # Examples
63///
64/// ```
65/// use rune::alloc::HashMap;
66///
67/// // Type inference lets us omit an explicit type signature (which
68/// // would be `HashMap<String, String>` in this example).
69/// let mut book_reviews = HashMap::new();
70///
71/// // Review some books.
72/// book_reviews.try_insert(
73/// "Adventures of Huckleberry Finn".to_string(),
74/// "My favorite book.".to_string(),
75/// )?;
76/// book_reviews.try_insert(
77/// "Grimms' Fairy Tales".to_string(),
78/// "Masterpiece.".to_string(),
79/// )?;
80/// book_reviews.try_insert(
81/// "Pride and Prejudice".to_string(),
82/// "Very enjoyable.".to_string(),
83/// )?;
84/// book_reviews.try_insert(
85/// "The Adventures of Sherlock Holmes".to_string(),
86/// "Eye lyked it alot.".to_string(),
87/// )?;
88///
89/// // Check for a specific one.
90/// // When collections store owned values (String), they can still be
91/// // queried using references (&str).
92/// if !book_reviews.contains_key("Les Misérables") {
93/// println!("We've got {} reviews, but Les Misérables ain't one.",
94/// book_reviews.len());
95/// }
96///
97/// // oops, this review has a lot of spelling mistakes, let's delete it.
98/// book_reviews.remove("The Adventures of Sherlock Holmes");
99///
100/// // Look up the values associated with some keys.
101/// let to_find = ["Pride and Prejudice", "Alice's Adventure in Wonderland"];
102/// for &book in &to_find {
103/// match book_reviews.get(book) {
104/// Some(review) => println!("{}: {}", book, review),
105/// None => println!("{} is unreviewed.", book)
106/// }
107/// }
108///
109/// // Look up the value for a key (will panic if the key is not found).
110/// println!("Review for Jane: {}", book_reviews["Pride and Prejudice"]);
111///
112/// // Iterate over everything.
113/// for (book, review) in &book_reviews {
114/// println!("{}: \"{}\"", book, review);
115/// }
116/// # Ok::<_, rune::alloc::Error>(())
117/// ```
118///
119/// `HashMap` also implements an [`Entry API`](#method.entry), which allows
120/// for more complex methods of getting, setting, updating and removing keys and
121/// their values:
122///
123/// ```
124/// use rune::alloc::HashMap;
125///
126/// // type inference lets us omit an explicit type signature (which
127/// // would be `HashMap<&str, u8>` in this example).
128/// let mut player_stats = HashMap::new();
129///
130/// fn random_stat_buff() -> u8 {
131/// // could actually return some random value here - let's just return
132/// // some fixed value for now
133/// 42
134/// }
135///
136/// // insert a key only if it doesn't already exist
137/// player_stats.entry("health").or_try_insert(100)?;
138///
139/// // insert a key using a function that provides a new value only if it
140/// // doesn't already exist
141/// player_stats.entry("defence").or_try_insert_with(random_stat_buff)?;
142///
143/// // update a key, guarding against the key possibly not being set
144/// let stat = player_stats.entry("attack").or_try_insert(100)?;
145/// *stat += random_stat_buff();
146/// # Ok::<_, rune::alloc::Error>(())
147/// ```
148///
149/// The easiest way to use `HashMap` with a custom key type is to derive [`Eq`] and [`Hash`].
150/// We must also derive [`PartialEq`].
151///
152/// [`Eq`]: https://doc.rust-lang.org/std/cmp/trait.Eq.html
153/// [`Hash`]: https://doc.rust-lang.org/std/hash/trait.Hash.html
154/// [`PartialEq`]: https://doc.rust-lang.org/std/cmp/trait.PartialEq.html
155/// [`RefCell`]: https://doc.rust-lang.org/std/cell/struct.RefCell.html
156/// [`Cell`]: https://doc.rust-lang.org/std/cell/struct.Cell.html
157/// [`default`]: #method.default
158/// [`with_hasher`]: #method.with_hasher
159/// [`with_capacity_and_hasher`]: #method.with_capacity_and_hasher
160/// [`fnv`]: https://crates.io/crates/fnv
161/// [`AHash`]: https://crates.io/crates/ahash
162///
163/// ```
164/// use rune::alloc::HashMap;
165///
166/// #[derive(Hash, Eq, PartialEq, Debug)]
167/// struct Viking {
168/// name: String,
169/// country: String,
170/// }
171///
172/// impl Viking {
173/// /// Creates a new Viking.
174/// fn new(name: &str, country: &str) -> Viking {
175/// Viking { name: name.to_string(), country: country.to_string() }
176/// }
177/// }
178///
179/// // Use a HashMap to store the vikings' health points.
180/// let mut vikings = HashMap::new();
181///
182/// vikings.try_insert(Viking::new("Einar", "Norway"), 25)?;
183/// vikings.try_insert(Viking::new("Olaf", "Denmark"), 24)?;
184/// vikings.try_insert(Viking::new("Harald", "Iceland"), 12)?;
185///
186/// // Use derived implementation to print the status of the vikings.
187/// for (viking, health) in &vikings {
188/// println!("{:?} has {} hp", viking, health);
189/// }
190/// # Ok::<_, rune::alloc::Error>(())
191/// ```
192///
193/// A `HashMap` with fixed list of elements can be initialized from an array:
194///
195/// ```
196/// use rune::alloc::HashMap;
197/// use rune::alloc::prelude::*;
198///
199/// let timber_resources: HashMap<&str, i32> = [("Norway", 100), ("Denmark", 50), ("Iceland", 10)]
200/// .iter().cloned().try_collect()?;
201/// // use the values stored in map
202/// # Ok::<_, rune::alloc::Error>(())
203/// ```
204pub struct HashMap<K, V, S = DefaultHashBuilder, A: Allocator = Global> {
205 pub(crate) hash_builder: S,
206 pub(crate) table: RawTable<(K, V), A>,
207}
208
209impl<K, V, S: Clone, A: Allocator + Clone> TryClone for HashMap<K, V, S, A>
210where
211 K: TryClone,
212 V: TryClone,
213{
214 fn try_clone(&self) -> Result<Self, Error> {
215 Ok(HashMap {
216 hash_builder: self.hash_builder.clone(),
217 table: self.table.try_clone()?,
218 })
219 }
220
221 fn try_clone_from(&mut self, source: &Self) -> Result<(), Error> {
222 self.table.try_clone_from(&source.table)?;
223
224 // Update hash_builder only if we successfully cloned all elements.
225 self.hash_builder.clone_from(&source.hash_builder);
226 Ok(())
227 }
228}
229
230#[cfg(test)]
231impl<K, V, S: Clone, A: Allocator + Clone> Clone for HashMap<K, V, S, A>
232where
233 K: TryClone,
234 V: TryClone,
235{
236 fn clone(&self) -> Self {
237 self.try_clone().abort()
238 }
239
240 fn clone_from(&mut self, source: &Self) {
241 self.try_clone_from(source).abort()
242 }
243}
244
245/// Ensures that a single closure type across uses of this which, in turn prevents multiple
246/// instances of any functions like RawTable::reserve from being generated
247#[cfg_attr(feature = "inline-more", inline)]
248pub(crate) fn make_hasher<T: ?Sized, S>(hash_builder: &S) -> impl HasherFn<(), T, Infallible> + '_
249where
250 T: Hash,
251 S: BuildHasher,
252{
253 move |_: &mut (), value: &T| Ok(make_hash::<T, S>(hash_builder, value))
254}
255
256/// Ensures that a single closure type across uses of this which, in turn prevents multiple
257/// instances of any functions like RawTable::reserve from being generated
258#[cfg_attr(feature = "inline-more", inline)]
259fn equivalent_key<C, Q, K, V>(k: &Q) -> impl Fn(&mut C, &(K, V)) -> Result<bool, Infallible> + '_
260where
261 Q: ?Sized + Equivalent<K>,
262{
263 move |_, x| Ok(k.equivalent(&x.0))
264}
265
266/// Ensures that a single closure type across uses of this which, in turn prevents multiple
267/// instances of any functions like RawTable::reserve from being generated
268#[cfg_attr(feature = "inline-more", inline)]
269fn equivalent<Q, K>(k: &Q) -> impl Fn(&K) -> bool + '_
270where
271 Q: ?Sized + Equivalent<K>,
272{
273 move |x| k.equivalent(x)
274}
275
276#[cfg(not(rune_nightly))]
277#[cfg_attr(feature = "inline-more", inline)]
278pub(crate) fn make_hash<Q: ?Sized, S>(hash_builder: &S, val: &Q) -> u64
279where
280 Q: Hash,
281 S: BuildHasher,
282{
283 hash_builder.hash_one(val)
284}
285
286#[cfg(rune_nightly)]
287#[cfg_attr(feature = "inline-more", inline)]
288pub(crate) fn make_hash<Q, S>(hash_builder: &S, val: &Q) -> u64
289where
290 Q: Hash + ?Sized,
291 S: BuildHasher,
292{
293 hash_builder.hash_one(val)
294}
295
296impl<K, V> HashMap<K, V, DefaultHashBuilder> {
297 /// Creates an empty `HashMap`.
298 ///
299 /// The hash map is initially created with a capacity of 0, so it will not allocate until it
300 /// is first inserted into.
301 ///
302 /// # HashDoS resistance
303 ///
304 /// The `hash_builder` normally use a fixed key by default and that does not
305 /// allow the `HashMap` to be protected against attacks such as [`HashDoS`].
306 /// Users who require HashDoS resistance should explicitly use
307 /// [`ahash::RandomState`] or [`std::collections::hash_map::RandomState`] as
308 /// the hasher when creating a [`HashMap`], for example with
309 /// [`with_hasher`](HashMap::with_hasher) method.
310 ///
311 /// [`HashDoS`]: https://en.wikipedia.org/wiki/Collision_attack
312 /// [`std::collections::hash_map::RandomState`]: https://doc.rust-lang.org/std/collections/hash_map/struct.RandomState.html
313 ///
314 /// # Examples
315 ///
316 /// ```
317 /// use rune::alloc::HashMap;
318 /// let mut map: HashMap<&str, i32> = HashMap::new();
319 /// assert_eq!(map.len(), 0);
320 /// assert_eq!(map.capacity(), 0);
321 /// # Ok::<_, rune::alloc::Error>(())
322 /// ```
323 #[cfg_attr(feature = "inline-more", inline)]
324 pub fn new() -> Self {
325 Self::default()
326 }
327
328 /// Creates an empty `HashMap` with the specified capacity.
329 ///
330 /// The hash map will be able to hold at least `capacity` elements without
331 /// reallocating. If `capacity` is 0, the hash map will not allocate.
332 ///
333 /// # HashDoS resistance
334 ///
335 /// The `hash_builder` normally use a fixed key by default and that does not
336 /// allow the `HashMap` to be protected against attacks such as [`HashDoS`].
337 /// Users who require HashDoS resistance should explicitly use
338 /// [`ahash::RandomState`] or [`std::collections::hash_map::RandomState`] as
339 /// the hasher when creating a [`HashMap`], for example with
340 /// [`try_with_capacity_and_hasher`] method.
341 ///
342 /// [`try_with_capacity_and_hasher`]: HashMap::try_with_capacity_and_hasher
343 /// [`HashDoS`]: https://en.wikipedia.org/wiki/Collision_attack
344 /// [`std::collections::hash_map::RandomState`]: https://doc.rust-lang.org/std/collections/hash_map/struct.RandomState.html
345 ///
346 /// # Examples
347 ///
348 /// ```
349 /// use rune::alloc::HashMap;
350 /// let mut map: HashMap<&str, i32> = HashMap::try_with_capacity(10)?;
351 /// assert_eq!(map.len(), 0);
352 /// assert!(map.capacity() >= 10);
353 /// # Ok::<_, rune::alloc::Error>(())
354 /// ```
355 #[cfg_attr(feature = "inline-more", inline)]
356 pub fn try_with_capacity(capacity: usize) -> Result<Self, Error> {
357 Self::try_with_capacity_and_hasher(capacity, DefaultHashBuilder::default())
358 }
359
360 #[cfg(test)]
361 pub(crate) fn with_capacity(capacity: usize) -> Self {
362 Self::try_with_capacity(capacity).abort()
363 }
364}
365
366impl<K, V, A: Allocator> HashMap<K, V, DefaultHashBuilder, A> {
367 /// Creates an empty `HashMap` using the given allocator.
368 ///
369 /// The hash map is initially created with a capacity of 0, so it will not allocate until it
370 /// is first inserted into.
371 ///
372 /// # HashDoS resistance
373 ///
374 /// The `hash_builder` normally use a fixed key by default and that does
375 /// not allow the `HashMap` to be protected against attacks such as [`HashDoS`].
376 /// Users who require HashDoS resistance should explicitly use
377 /// [`ahash::RandomState`] or [`std::collections::hash_map::RandomState`]
378 /// as the hasher when creating a [`HashMap`], for example with
379 /// [`with_hasher_in`](HashMap::with_hasher_in) method.
380 ///
381 /// [`HashDoS`]: https://en.wikipedia.org/wiki/Collision_attack
382 /// [`std::collections::hash_map::RandomState`]: https://doc.rust-lang.org/std/collections/hash_map/struct.RandomState.html
383 ///
384 /// # Examples
385 ///
386 /// ```
387 /// use rune::alloc::HashMap;
388 /// use rune::alloc::alloc::Global;
389 ///
390 /// let mut map = HashMap::new_in(Global);
391 ///
392 /// // The created HashMap holds none elements
393 /// assert_eq!(map.len(), 0);
394 ///
395 /// // The created HashMap also doesn't allocate memory
396 /// assert_eq!(map.capacity(), 0);
397 ///
398 /// // Now we insert element inside created HashMap
399 /// map.try_insert("One", 1)?;
400 /// // We can see that the HashMap holds 1 element
401 /// assert_eq!(map.len(), 1);
402 /// // And it also allocates some capacity
403 /// assert!(map.capacity() > 1);
404 /// # Ok::<_, rune::alloc::Error>(())
405 /// ```
406 #[cfg_attr(feature = "inline-more", inline)]
407 pub fn new_in(alloc: A) -> Self {
408 Self::with_hasher_in(DefaultHashBuilder::default(), alloc)
409 }
410
411 /// Creates an empty `HashMap` with the specified capacity using the given allocator.
412 ///
413 /// The hash map will be able to hold at least `capacity` elements without
414 /// reallocating. If `capacity` is 0, the hash map will not allocate.
415 ///
416 /// # HashDoS resistance
417 ///
418 /// The `hash_builder` normally use a fixed key by default and that does not
419 /// allow the `HashMap` to be protected against attacks such as [`HashDoS`].
420 /// Users who require HashDoS resistance should explicitly use
421 /// [`ahash::RandomState`] or [`std::collections::hash_map::RandomState`] as
422 /// the hasher when creating a [`HashMap`], for example with
423 /// [`try_with_capacity_and_hasher_in`] method.
424 ///
425 /// [`try_with_capacity_and_hasher_in`]:
426 /// HashMap::try_with_capacity_and_hasher_in
427 /// [`HashDoS`]: https://en.wikipedia.org/wiki/Collision_attack
428 /// [`std::collections::hash_map::RandomState`]: https://doc.rust-lang.org/std/collections/hash_map/struct.RandomState.html
429 ///
430 /// # Examples
431 ///
432 /// ```
433 /// use rune::alloc::HashMap;
434 /// use rune::alloc::alloc::Global;
435 ///
436 /// let mut map = HashMap::try_with_capacity_in(5, Global)?;
437 ///
438 /// // The created HashMap holds none elements
439 /// assert_eq!(map.len(), 0);
440 /// // But it can hold at least 5 elements without reallocating
441 /// let empty_map_capacity = map.capacity();
442 /// assert!(empty_map_capacity >= 5);
443 ///
444 /// // Now we insert some 5 elements inside created HashMap
445 /// map.try_insert("One", 1)?;
446 /// map.try_insert("Two", 2)?;
447 /// map.try_insert("Three", 3)?;
448 /// map.try_insert("Four", 4)?;
449 /// map.try_insert("Five", 5)?;
450 ///
451 /// // We can see that the HashMap holds 5 elements
452 /// assert_eq!(map.len(), 5);
453 /// // But its capacity isn't changed
454 /// assert_eq!(map.capacity(), empty_map_capacity);
455 /// # Ok::<_, rune::alloc::Error>(())
456 /// ```
457 #[cfg_attr(feature = "inline-more", inline)]
458 pub fn try_with_capacity_in(capacity: usize, alloc: A) -> Result<Self, Error> {
459 Self::try_with_capacity_and_hasher_in(capacity, DefaultHashBuilder::default(), alloc)
460 }
461}
462
463impl<K, V, S> HashMap<K, V, S> {
464 /// Creates an empty `HashMap` which will use the given hash builder to hash
465 /// keys.
466 ///
467 /// The hash map is initially created with a capacity of 0, so it will not
468 /// allocate until it is first inserted into.
469 ///
470 /// # HashDoS resistance
471 ///
472 /// The `hash_builder` normally use a fixed key by default and that does
473 /// not allow the `HashMap` to be protected against attacks such as [`HashDoS`].
474 /// Users who require HashDoS resistance should explicitly use
475 /// [`ahash::RandomState`] or [`std::collections::hash_map::RandomState`]
476 /// as the hasher when creating a [`HashMap`].
477 ///
478 /// The `hash_builder` passed should implement the [`BuildHasher`] trait for
479 /// the HashMap to be useful, see its documentation for details.
480 ///
481 /// [`HashDoS`]: https://en.wikipedia.org/wiki/Collision_attack
482 /// [`std::collections::hash_map::RandomState`]: https://doc.rust-lang.org/std/collections/hash_map/struct.RandomState.html
483 /// [`BuildHasher`]: https://doc.rust-lang.org/std/hash/trait.BuildHasher.html
484 ///
485 /// # Examples
486 ///
487 /// ```
488 /// use rune::alloc::HashMap;
489 /// use rune::alloc::hash_map::DefaultHashBuilder;
490 ///
491 /// let s = DefaultHashBuilder::default();
492 /// let mut map = HashMap::with_hasher(s);
493 /// assert_eq!(map.len(), 0);
494 /// assert_eq!(map.capacity(), 0);
495 ///
496 /// map.try_insert(1, 2)?;
497 /// # Ok::<_, rune::alloc::Error>(())
498 /// ```
499 #[cfg_attr(feature = "inline-more", inline)]
500 pub const fn with_hasher(hash_builder: S) -> Self {
501 Self {
502 hash_builder,
503 table: RawTable::new_in(Global),
504 }
505 }
506
507 /// Creates an empty `HashMap` with the specified capacity, using `hash_builder`
508 /// to hash the keys.
509 ///
510 /// The hash map will be able to hold at least `capacity` elements without
511 /// reallocating. If `capacity` is 0, the hash map will not allocate.
512 ///
513 /// # HashDoS resistance
514 ///
515 /// The `hash_builder` normally use a fixed key by default and that does
516 /// not allow the `HashMap` to be protected against attacks such as [`HashDoS`].
517 /// Users who require HashDoS resistance should explicitly use
518 /// [`ahash::RandomState`] or [`std::collections::hash_map::RandomState`]
519 /// as the hasher when creating a [`HashMap`].
520 ///
521 /// The `hash_builder` passed should implement the [`BuildHasher`] trait for
522 /// the HashMap to be useful, see its documentation for details.
523 ///
524 /// [`HashDoS`]: https://en.wikipedia.org/wiki/Collision_attack
525 /// [`std::collections::hash_map::RandomState`]: https://doc.rust-lang.org/std/collections/hash_map/struct.RandomState.html
526 /// [`BuildHasher`]: https://doc.rust-lang.org/std/hash/trait.BuildHasher.html
527 ///
528 /// # Examples
529 ///
530 /// ```
531 /// use rune::alloc::HashMap;
532 /// use rune::alloc::hash_map::DefaultHashBuilder;
533 ///
534 /// let s = DefaultHashBuilder::default();
535 /// let mut map = HashMap::try_with_capacity_and_hasher(10, s)?;
536 /// assert_eq!(map.len(), 0);
537 /// assert!(map.capacity() >= 10);
538 ///
539 /// map.try_insert(1, 2)?;
540 /// # Ok::<_, rune::alloc::Error>(())
541 /// ```
542 #[cfg_attr(feature = "inline-more", inline)]
543 pub fn try_with_capacity_and_hasher(capacity: usize, hash_builder: S) -> Result<Self, Error> {
544 Ok(Self {
545 hash_builder,
546 table: RawTable::try_with_capacity_in(capacity, Global)?,
547 })
548 }
549
550 #[cfg(test)]
551 pub(crate) fn with_capacity_and_hasher(capacity: usize, hash_builder: S) -> Self {
552 Self::try_with_capacity_and_hasher(capacity, hash_builder).abort()
553 }
554}
555
556impl<K, V, S, A: Allocator> HashMap<K, V, S, A> {
557 /// Returns a reference to the underlying allocator.
558 #[inline]
559 pub fn allocator(&self) -> &A {
560 self.table.allocator()
561 }
562
563 /// Creates an empty `HashMap` which will use the given hash builder to hash
564 /// keys. It will be allocated with the given allocator.
565 ///
566 /// The hash map is initially created with a capacity of 0, so it will not allocate until it
567 /// is first inserted into.
568 ///
569 /// # HashDoS resistance
570 ///
571 /// The `hash_builder` normally use a fixed key by default and that does
572 /// not allow the `HashMap` to be protected against attacks such as [`HashDoS`].
573 /// Users who require HashDoS resistance should explicitly use
574 /// [`ahash::RandomState`] or [`std::collections::hash_map::RandomState`]
575 /// as the hasher when creating a [`HashMap`].
576 ///
577 /// [`HashDoS`]: https://en.wikipedia.org/wiki/Collision_attack
578 /// [`std::collections::hash_map::RandomState`]: https://doc.rust-lang.org/std/collections/hash_map/struct.RandomState.html
579 ///
580 /// # Examples
581 ///
582 /// ```
583 /// use rune::alloc::HashMap;
584 /// use rune::alloc::hash_map::DefaultHashBuilder;
585 ///
586 /// let s = DefaultHashBuilder::default();
587 /// let mut map = HashMap::with_hasher(s);
588 /// map.try_insert(1, 2)?;
589 /// # Ok::<_, rune::alloc::Error>(())
590 /// ```
591 #[cfg_attr(feature = "inline-more", inline)]
592 pub const fn with_hasher_in(hash_builder: S, alloc: A) -> Self {
593 Self {
594 hash_builder,
595 table: RawTable::new_in(alloc),
596 }
597 }
598
599 /// Creates an empty `HashMap` with the specified capacity, using `hash_builder`
600 /// to hash the keys. It will be allocated with the given allocator.
601 ///
602 /// The hash map will be able to hold at least `capacity` elements without
603 /// reallocating. If `capacity` is 0, the hash map will not allocate.
604 ///
605 /// # HashDoS resistance
606 ///
607 /// The `hash_builder` normally use a fixed key by default and that does
608 /// not allow the `HashMap` to be protected against attacks such as [`HashDoS`].
609 /// Users who require HashDoS resistance should explicitly use
610 /// [`ahash::RandomState`] or [`std::collections::hash_map::RandomState`]
611 /// as the hasher when creating a [`HashMap`].
612 ///
613 /// [`HashDoS`]: https://en.wikipedia.org/wiki/Collision_attack
614 /// [`std::collections::hash_map::RandomState`]: https://doc.rust-lang.org/std/collections/hash_map/struct.RandomState.html
615 ///
616 /// # Examples
617 ///
618 /// ```
619 /// use rune::alloc::HashMap;
620 /// use rune::alloc::alloc::Global;
621 /// use rune::alloc::hash_map::DefaultHashBuilder;
622 ///
623 /// let s = DefaultHashBuilder::default();
624 /// let mut map = HashMap::try_with_capacity_and_hasher_in(10, s, Global)?;
625 /// map.try_insert(1, 2)?;
626 /// # Ok::<_, rune::alloc::Error>(())
627 /// ```
628 #[cfg_attr(feature = "inline-more", inline)]
629 pub fn try_with_capacity_and_hasher_in(
630 capacity: usize,
631 hash_builder: S,
632 alloc: A,
633 ) -> Result<Self, Error> {
634 Ok(Self {
635 hash_builder,
636 table: RawTable::try_with_capacity_in(capacity, alloc)?,
637 })
638 }
639
640 /// Returns a reference to the map's [`BuildHasher`].
641 ///
642 /// [`BuildHasher`]: https://doc.rust-lang.org/std/hash/trait.BuildHasher.html
643 ///
644 /// # Examples
645 ///
646 /// ```
647 /// use rune::alloc::HashMap;
648 /// use rune::alloc::hash_map::DefaultHashBuilder;
649 ///
650 /// let hasher = DefaultHashBuilder::default();
651 /// let map: HashMap<i32, i32> = HashMap::with_hasher(hasher);
652 /// let hasher: &DefaultHashBuilder = map.hasher();
653 /// # Ok::<_, rune::alloc::Error>(())
654 /// ```
655 #[cfg_attr(feature = "inline-more", inline)]
656 pub fn hasher(&self) -> &S {
657 &self.hash_builder
658 }
659
660 /// Returns the number of elements the map can hold without reallocating.
661 ///
662 /// This number is a lower bound; the `HashMap<K, V>` might be able to hold
663 /// more, but is guaranteed to be able to hold at least this many.
664 ///
665 /// # Examples
666 ///
667 /// ```
668 /// use rune::alloc::HashMap;
669 /// let map: HashMap<i32, i32> = HashMap::try_with_capacity(100)?;
670 /// assert_eq!(map.len(), 0);
671 /// assert!(map.capacity() >= 100);
672 /// # Ok::<_, rune::alloc::Error>(())
673 /// ```
674 #[cfg_attr(feature = "inline-more", inline)]
675 pub fn capacity(&self) -> usize {
676 self.table.capacity()
677 }
678
679 /// An iterator visiting all keys in arbitrary order.
680 /// The iterator element type is `&'a K`.
681 ///
682 /// # Examples
683 ///
684 /// ```
685 /// use rune::alloc::HashMap;
686 ///
687 /// let mut map = HashMap::new();
688 /// map.try_insert("a", 1)?;
689 /// map.try_insert("b", 2)?;
690 /// map.try_insert("c", 3)?;
691 /// assert_eq!(map.len(), 3);
692 /// let mut vec: Vec<&str> = Vec::new();
693 ///
694 /// for key in map.keys() {
695 /// println!("{}", key);
696 /// vec.push(*key);
697 /// }
698 ///
699 /// // The `Keys` iterator produces keys in arbitrary order, so the
700 /// // keys must be sorted to test them against a sorted array.
701 /// vec.sort_unstable();
702 /// assert_eq!(vec, ["a", "b", "c"]);
703 ///
704 /// assert_eq!(map.len(), 3);
705 /// # Ok::<_, rune::alloc::Error>(())
706 /// ```
707 #[cfg_attr(feature = "inline-more", inline)]
708 pub fn keys(&self) -> Keys<'_, K, V> {
709 Keys { inner: self.iter() }
710 }
711
712 /// An iterator visiting all values in arbitrary order.
713 /// The iterator element type is `&'a V`.
714 ///
715 /// # Examples
716 ///
717 /// ```
718 /// use rune::alloc::HashMap;
719 ///
720 /// let mut map = HashMap::new();
721 /// map.try_insert("a", 1)?;
722 /// map.try_insert("b", 2)?;
723 /// map.try_insert("c", 3)?;
724 /// assert_eq!(map.len(), 3);
725 /// let mut vec: Vec<i32> = Vec::new();
726 ///
727 /// for val in map.values() {
728 /// println!("{}", val);
729 /// vec.push(*val);
730 /// }
731 ///
732 /// // The `Values` iterator produces values in arbitrary order, so the
733 /// // values must be sorted to test them against a sorted array.
734 /// vec.sort_unstable();
735 /// assert_eq!(vec, [1, 2, 3]);
736 ///
737 /// assert_eq!(map.len(), 3);
738 /// # Ok::<_, rune::alloc::Error>(())
739 /// ```
740 #[cfg_attr(feature = "inline-more", inline)]
741 pub fn values(&self) -> Values<'_, K, V> {
742 Values { inner: self.iter() }
743 }
744
745 /// An iterator visiting all values mutably in arbitrary order.
746 /// The iterator element type is `&'a mut V`.
747 ///
748 /// # Examples
749 ///
750 /// ```
751 /// use rune::alloc::HashMap;
752 ///
753 /// let mut map = HashMap::new();
754 ///
755 /// map.try_insert("a", 1)?;
756 /// map.try_insert("b", 2)?;
757 /// map.try_insert("c", 3)?;
758 ///
759 /// for val in map.values_mut() {
760 /// *val = *val + 10;
761 /// }
762 ///
763 /// assert_eq!(map.len(), 3);
764 /// let mut vec: Vec<i32> = Vec::new();
765 ///
766 /// for val in map.values() {
767 /// println!("{}", val);
768 /// vec.push(*val);
769 /// }
770 ///
771 /// // The `Values` iterator produces values in arbitrary order, so the
772 /// // values must be sorted to test them against a sorted array.
773 /// vec.sort_unstable();
774 /// assert_eq!(vec, [11, 12, 13]);
775 ///
776 /// assert_eq!(map.len(), 3);
777 /// # Ok::<_, rune::alloc::Error>(())
778 /// ```
779 #[cfg_attr(feature = "inline-more", inline)]
780 pub fn values_mut(&mut self) -> ValuesMut<'_, K, V> {
781 ValuesMut {
782 inner: self.iter_mut(),
783 }
784 }
785
786 /// An iterator visiting all key-value pairs in arbitrary order.
787 /// The iterator element type is `(&'a K, &'a V)`.
788 ///
789 /// # Examples
790 ///
791 /// ```
792 /// use rune::alloc::HashMap;
793 ///
794 /// let mut map = HashMap::new();
795 /// map.try_insert("a", 1)?;
796 /// map.try_insert("b", 2)?;
797 /// map.try_insert("c", 3)?;
798 /// assert_eq!(map.len(), 3);
799 /// let mut vec: Vec<(&str, i32)> = Vec::new();
800 ///
801 /// for (key, val) in map.iter() {
802 /// println!("key: {} val: {}", key, val);
803 /// vec.push((*key, *val));
804 /// }
805 ///
806 /// // The `Iter` iterator produces items in arbitrary order, so the
807 /// // items must be sorted to test them against a sorted array.
808 /// vec.sort_unstable();
809 /// assert_eq!(vec, [("a", 1), ("b", 2), ("c", 3)]);
810 ///
811 /// assert_eq!(map.len(), 3);
812 /// # Ok::<_, rune::alloc::Error>(())
813 /// ```
814 #[cfg_attr(feature = "inline-more", inline)]
815 pub fn iter(&self) -> Iter<'_, K, V> {
816 // Here we tie the lifetime of self to the iter.
817 unsafe {
818 Iter {
819 inner: self.table.iter(),
820 marker: PhantomData,
821 }
822 }
823 }
824
825 /// An iterator visiting all key-value pairs in arbitrary order,
826 /// with mutable references to the values.
827 /// The iterator element type is `(&'a K, &'a mut V)`.
828 ///
829 /// # Examples
830 ///
831 /// ```
832 /// use rune::alloc::HashMap;
833 ///
834 /// let mut map = HashMap::new();
835 /// map.try_insert("a", 1)?;
836 /// map.try_insert("b", 2)?;
837 /// map.try_insert("c", 3)?;
838 ///
839 /// // Update all values
840 /// for (_, val) in map.iter_mut() {
841 /// *val *= 2;
842 /// }
843 ///
844 /// assert_eq!(map.len(), 3);
845 /// let mut vec: Vec<(&str, i32)> = Vec::new();
846 ///
847 /// for (key, val) in &map {
848 /// println!("key: {} val: {}", key, val);
849 /// vec.push((*key, *val));
850 /// }
851 ///
852 /// // The `Iter` iterator produces items in arbitrary order, so the
853 /// // items must be sorted to test them against a sorted array.
854 /// vec.sort_unstable();
855 /// assert_eq!(vec, [("a", 2), ("b", 4), ("c", 6)]);
856 ///
857 /// assert_eq!(map.len(), 3);
858 /// # Ok::<_, rune::alloc::Error>(())
859 /// ```
860 #[cfg_attr(feature = "inline-more", inline)]
861 pub fn iter_mut(&mut self) -> IterMut<'_, K, V> {
862 // Here we tie the lifetime of self to the iter.
863 unsafe {
864 IterMut {
865 inner: self.table.iter(),
866 marker: PhantomData,
867 }
868 }
869 }
870
871 #[cfg(test)]
872 #[cfg_attr(feature = "inline-more", inline)]
873 fn raw_capacity(&self) -> usize {
874 self.table.buckets()
875 }
876
877 /// Returns the number of elements in the map.
878 ///
879 /// # Examples
880 ///
881 /// ```
882 /// use rune::alloc::HashMap;
883 ///
884 /// let mut a = HashMap::new();
885 /// assert_eq!(a.len(), 0);
886 /// a.try_insert(1, "a")?;
887 /// assert_eq!(a.len(), 1);
888 /// # Ok::<_, rune::alloc::Error>(())
889 /// ```
890 #[cfg_attr(feature = "inline-more", inline)]
891 pub fn len(&self) -> usize {
892 self.table.len()
893 }
894
895 /// Returns `true` if the map contains no elements.
896 ///
897 /// # Examples
898 ///
899 /// ```
900 /// use rune::alloc::HashMap;
901 ///
902 /// let mut a = HashMap::new();
903 /// assert!(a.is_empty());
904 /// a.try_insert(1, "a")?;
905 /// assert!(!a.is_empty());
906 /// # Ok::<_, rune::alloc::Error>(())
907 /// ```
908 #[cfg_attr(feature = "inline-more", inline)]
909 pub fn is_empty(&self) -> bool {
910 self.len() == 0
911 }
912
913 /// Clears the map, returning all key-value pairs as an iterator. Keeps the
914 /// allocated memory for reuse.
915 ///
916 /// If the returned iterator is dropped before being fully consumed, it
917 /// drops the remaining key-value pairs. The returned iterator keeps a
918 /// mutable borrow on the vector to optimize its implementation.
919 ///
920 /// # Examples
921 ///
922 /// ```
923 /// use rune::alloc::HashMap;
924 ///
925 /// let mut a = HashMap::new();
926 /// a.try_insert(1, "a")?;
927 /// a.try_insert(2, "b")?;
928 /// let capacity_before_drain = a.capacity();
929 ///
930 /// for (k, v) in a.drain().take(1) {
931 /// assert!(k == 1 || k == 2);
932 /// assert!(v == "a" || v == "b");
933 /// }
934 ///
935 /// // As we can see, the map is empty and contains no element.
936 /// assert!(a.is_empty() && a.len() == 0);
937 /// // But map capacity is equal to old one.
938 /// assert_eq!(a.capacity(), capacity_before_drain);
939 ///
940 /// let mut a = HashMap::new();
941 /// a.try_insert(1, "a")?;
942 /// a.try_insert(2, "b")?;
943 ///
944 /// { // Iterator is dropped without being consumed.
945 /// let d = a.drain();
946 /// }
947 ///
948 /// // But the map is empty even if we do not use Drain iterator.
949 /// assert!(a.is_empty());
950 /// # Ok::<_, rune::alloc::Error>(())
951 /// ```
952 #[cfg_attr(feature = "inline-more", inline)]
953 pub fn drain(&mut self) -> Drain<'_, K, V, A> {
954 Drain {
955 inner: self.table.drain(),
956 }
957 }
958
959 /// Retains only the elements specified by the predicate. Keeps the
960 /// allocated memory for reuse.
961 ///
962 /// In other words, remove all pairs `(k, v)` such that `f(&k, &mut v)` returns `false`.
963 /// The elements are visited in unsorted (and unspecified) order.
964 ///
965 /// # Examples
966 ///
967 /// ```
968 /// use rune::alloc::{HashMap, Vec};
969 /// use rune::alloc::prelude::*;
970 ///
971 /// let mut map: HashMap<i32, i32> = (0..8).map(|x|(x, x*10)).try_collect()?;
972 /// assert_eq!(map.len(), 8);
973 ///
974 /// map.retain(|&k, _| k % 2 == 0);
975 ///
976 /// // We can see, that the number of elements inside map is changed.
977 /// assert_eq!(map.len(), 4);
978 ///
979 /// let mut vec: Vec<(i32, i32)> = map.iter().map(|(&k, &v)| (k, v)).try_collect()?;
980 /// vec.sort_unstable();
981 /// assert_eq!(vec, [(0, 0), (2, 20), (4, 40), (6, 60)]);
982 /// # Ok::<_, rune::alloc::Error>(())
983 /// ```
984 pub fn retain<F>(&mut self, mut f: F)
985 where
986 F: FnMut(&K, &mut V) -> bool,
987 {
988 // Here we only use `iter` as a temporary, preventing use-after-free
989 unsafe {
990 for item in self.table.iter() {
991 let &mut (ref key, ref mut value) = item.as_mut();
992 if !f(key, value) {
993 self.table.erase(item);
994 }
995 }
996 }
997 }
998
999 /// Drains elements which are true under the given predicate,
1000 /// and returns an iterator over the removed items.
1001 ///
1002 /// In other words, move all pairs `(k, v)` such that `f(&k, &mut v)` returns `true` out
1003 /// into another iterator.
1004 ///
1005 /// Note that `extract_if` lets you mutate every value in the filter closure, regardless of
1006 /// whether you choose to keep or remove it.
1007 ///
1008 /// If the returned `ExtractIf` is not exhausted, e.g. because it is dropped without iterating
1009 /// or the iteration short-circuits, then the remaining elements will be retained.
1010 /// Use [`retain`] with a negated predicate if you do not need the returned iterator.
1011 ///
1012 /// Keeps the allocated memory for reuse.
1013 ///
1014 /// # Examples
1015 ///
1016 /// ```
1017 /// use rune::alloc::{try_vec, HashMap, Vec};
1018 /// use rune::alloc::prelude::*;
1019 ///
1020 /// let mut map: HashMap<i32, i32> = (0..8).map(|x| (x, x)).try_collect()?;
1021 ///
1022 /// let drained: HashMap<i32, i32> = map.extract_if(|k, _v| k % 2 == 0).try_collect()?;
1023 ///
1024 /// let mut evens = drained.keys().cloned().try_collect::<Vec<_>>()?;
1025 /// let mut odds = map.keys().cloned().try_collect::<Vec<_>>()?;
1026 /// evens.sort();
1027 /// odds.sort();
1028 ///
1029 /// assert_eq!(evens, try_vec![0, 2, 4, 6]);
1030 /// assert_eq!(odds, try_vec![1, 3, 5, 7]);
1031 ///
1032 /// let mut map: HashMap<i32, i32> = (0..8).map(|x| (x, x)).try_collect()?;
1033 ///
1034 /// { // Iterator is dropped without being consumed.
1035 /// let d = map.extract_if(|k, _v| k % 2 != 0);
1036 /// }
1037 ///
1038 /// // ExtractIf was not exhausted, therefore no elements were drained.
1039 /// assert_eq!(map.len(), 8);
1040 /// # Ok::<_, rune::alloc::Error>(())
1041 /// ```
1042 ///
1043 /// [`retain`]: HashMap::retain
1044 #[cfg_attr(feature = "inline-more", inline)]
1045 pub fn extract_if<F>(&mut self, f: F) -> ExtractIf<'_, K, V, F, A>
1046 where
1047 F: FnMut(&K, &mut V) -> bool,
1048 {
1049 ExtractIf {
1050 f,
1051 inner: ExtractIfInner {
1052 iter: unsafe { self.table.iter() },
1053 table: &mut self.table,
1054 },
1055 }
1056 }
1057
1058 /// Clears the map, removing all key-value pairs. Keeps the allocated memory
1059 /// for reuse.
1060 ///
1061 /// # Examples
1062 ///
1063 /// ```
1064 /// use rune::alloc::HashMap;
1065 ///
1066 /// let mut a = HashMap::new();
1067 /// a.try_insert(1, "a")?;
1068 /// let capacity_before_clear = a.capacity();
1069 ///
1070 /// a.clear();
1071 ///
1072 /// // Map is empty.
1073 /// assert!(a.is_empty());
1074 /// // But map capacity is equal to old one.
1075 /// assert_eq!(a.capacity(), capacity_before_clear);
1076 /// # Ok::<_, rune::alloc::Error>(())
1077 /// ```
1078 #[cfg_attr(feature = "inline-more", inline)]
1079 pub fn clear(&mut self) {
1080 self.table.clear();
1081 }
1082
1083 /// Creates a consuming iterator visiting all the keys in arbitrary order.
1084 /// The map cannot be used after calling this.
1085 /// The iterator element type is `K`.
1086 ///
1087 /// # Examples
1088 ///
1089 /// ```
1090 /// use rune::alloc::{HashMap, Vec};
1091 /// use rune::alloc::prelude::*;
1092 ///
1093 /// let mut map = HashMap::new();
1094 /// map.try_insert("a", 1)?;
1095 /// map.try_insert("b", 2)?;
1096 /// map.try_insert("c", 3)?;
1097 ///
1098 /// let mut vec: Vec<&str> = map.into_keys().try_collect()?;
1099 ///
1100 /// // The `IntoKeys` iterator produces keys in arbitrary order, so the
1101 /// // keys must be sorted to test them against a sorted array.
1102 /// vec.sort_unstable();
1103 /// assert_eq!(vec, ["a", "b", "c"]);
1104 /// # Ok::<_, rune::alloc::Error>(())
1105 /// ```
1106 #[inline]
1107 pub fn into_keys(self) -> IntoKeys<K, V, A> {
1108 IntoKeys {
1109 inner: self.into_iter(),
1110 }
1111 }
1112
1113 /// Creates a consuming iterator visiting all the values in arbitrary order.
1114 /// The map cannot be used after calling this.
1115 /// The iterator element type is `V`.
1116 ///
1117 /// # Examples
1118 ///
1119 /// ```
1120 /// use rune::alloc::{HashMap, Vec};
1121 /// use rune::alloc::prelude::*;
1122 ///
1123 /// let mut map = HashMap::new();
1124 /// map.try_insert("a", 1)?;
1125 /// map.try_insert("b", 2)?;
1126 /// map.try_insert("c", 3)?;
1127 ///
1128 /// let mut vec: Vec<i32> = map.into_values().try_collect()?;
1129 ///
1130 /// // The `IntoValues` iterator produces values in arbitrary order, so
1131 /// // the values must be sorted to test them against a sorted array.
1132 /// vec.sort_unstable();
1133 /// assert_eq!(vec, [1, 2, 3]);
1134 /// # Ok::<_, rune::alloc::Error>(())
1135 /// ```
1136 #[inline]
1137 pub fn into_values(self) -> IntoValues<K, V, A> {
1138 IntoValues {
1139 inner: self.into_iter(),
1140 }
1141 }
1142}
1143
1144impl<K, V, S, A> HashMap<K, V, S, A>
1145where
1146 K: Eq + Hash,
1147 S: BuildHasher,
1148 A: Allocator,
1149{
1150 /// Tries to reserve capacity for at least `additional` more elements to be inserted
1151 /// in the given `HashMap<K,V>`. The collection may reserve more space to avoid
1152 /// frequent reallocations.
1153 ///
1154 /// # Errors
1155 ///
1156 /// If the capacity overflows, or the allocator reports a failure, then an error
1157 /// is returned.
1158 ///
1159 /// # Examples
1160 ///
1161 /// ```
1162 /// use rune::alloc::HashMap;
1163 ///
1164 /// let mut map: HashMap<&str, isize> = HashMap::new();
1165 /// // Map is empty and doesn't allocate memory
1166 /// assert_eq!(map.capacity(), 0);
1167 ///
1168 /// map.try_reserve(10).expect("why is the test harness OOMing on 10 bytes?");
1169 ///
1170 /// // And now map can hold at least 10 elements
1171 /// assert!(map.capacity() >= 10);
1172 /// ```
1173 /// If the capacity overflows, or the allocator reports a failure, then an error
1174 /// is returned:
1175 /// ```
1176 /// # fn test() {
1177 /// use rune::alloc::{HashMap, Error};
1178 /// let mut map: HashMap<i32, i32> = HashMap::new();
1179 ///
1180 /// match map.try_reserve(usize::MAX) {
1181 /// Err(error) => match error {
1182 /// Error::CapacityOverflow => {}
1183 /// _ => panic!("Error::AllocError ?"),
1184 /// },
1185 /// _ => panic!(),
1186 /// }
1187 /// # }
1188 /// # fn main() {
1189 /// # #[cfg(not(miri))]
1190 /// # test()
1191 /// # }
1192 /// ```
1193 #[cfg_attr(feature = "inline-more", inline)]
1194 pub fn try_reserve(&mut self, additional: usize) -> Result<(), Error> {
1195 let hasher = make_hasher::<K, S>(&self.hash_builder);
1196 into_ok_try(
1197 self.table
1198 .try_reserve(&mut (), additional, hasher.into_tuple()),
1199 )
1200 }
1201
1202 #[cfg(test)]
1203 pub fn reserve(&mut self, additional: usize) {
1204 self.try_reserve(additional).abort()
1205 }
1206
1207 /// Shrinks the capacity of the map as much as possible. It will drop
1208 /// down as much as possible while maintaining the internal rules
1209 /// and possibly leaving some space in accordance with the resize policy.
1210 ///
1211 /// # Examples
1212 ///
1213 /// ```
1214 /// use rune::alloc::HashMap;
1215 ///
1216 /// let mut map: HashMap<i32, i32> = HashMap::try_with_capacity(100)?;
1217 /// map.try_insert(1, 2)?;
1218 /// map.try_insert(3, 4)?;
1219 /// assert!(map.capacity() >= 100);
1220 /// map.try_shrink_to_fit()?;
1221 /// assert!(map.capacity() >= 2);
1222 /// # Ok::<_, rune::alloc::Error>(())
1223 /// ```
1224 #[cfg_attr(feature = "inline-more", inline)]
1225 pub fn try_shrink_to_fit(&mut self) -> Result<(), Error> {
1226 into_ok_try(self.table.shrink_to(
1227 &mut (),
1228 0,
1229 make_hasher::<K, S>(&self.hash_builder).into_tuple(),
1230 ))
1231 }
1232
1233 #[cfg(test)]
1234 pub(crate) fn shrink_to_fit(&mut self) {
1235 self.try_shrink_to_fit().abort()
1236 }
1237
1238 /// Shrinks the capacity of the map with a lower limit. It will drop
1239 /// down no lower than the supplied limit while maintaining the internal rules
1240 /// and possibly leaving some space in accordance with the resize policy.
1241 ///
1242 /// This function does nothing if the current capacity is smaller than the
1243 /// supplied minimum capacity.
1244 ///
1245 /// # Examples
1246 ///
1247 /// ```
1248 /// use rune::alloc::HashMap;
1249 ///
1250 /// let mut map: HashMap<i32, i32> = HashMap::try_with_capacity(100)?;
1251 /// map.try_insert(1, 2)?;
1252 /// map.try_insert(3, 4)?;
1253 /// assert!(map.capacity() >= 100);
1254 /// map.try_shrink_to(10)?;
1255 /// assert!(map.capacity() >= 10);
1256 /// map.try_shrink_to(0)?;
1257 /// assert!(map.capacity() >= 2);
1258 /// map.try_shrink_to(10)?;
1259 /// assert!(map.capacity() >= 2);
1260 /// # Ok::<_, rune::alloc::Error>(())
1261 /// ```
1262 #[cfg_attr(feature = "inline-more", inline)]
1263 pub fn try_shrink_to(&mut self, min_capacity: usize) -> Result<(), Error> {
1264 into_ok_try(self.table.shrink_to(
1265 &mut (),
1266 min_capacity,
1267 make_hasher::<K, S>(&self.hash_builder).into_tuple(),
1268 ))
1269 }
1270
1271 /// Gets the given key's corresponding entry in the map for in-place manipulation.
1272 ///
1273 /// # Examples
1274 ///
1275 /// ```
1276 /// use rune::alloc::HashMap;
1277 ///
1278 /// let mut letters = HashMap::new();
1279 ///
1280 /// for ch in "a short treatise on fungi".chars() {
1281 /// let counter = letters.entry(ch).or_try_insert(0)?;
1282 /// *counter += 1;
1283 /// }
1284 ///
1285 /// assert_eq!(letters[&'s'], 2);
1286 /// assert_eq!(letters[&'t'], 3);
1287 /// assert_eq!(letters[&'u'], 1);
1288 /// assert_eq!(letters.get(&'y'), None);
1289 /// # Ok::<_, rune::alloc::Error>(())
1290 /// ```
1291 #[cfg_attr(feature = "inline-more", inline)]
1292 pub fn entry(&mut self, key: K) -> Entry<'_, K, V, S, A> {
1293 let hash = make_hash::<K, S>(&self.hash_builder, &key);
1294 if let Some(elem) = into_ok(self.table.find(&mut (), hash, equivalent_key(&key))) {
1295 Entry::Occupied(OccupiedEntry {
1296 hash,
1297 key: Some(key),
1298 elem,
1299 table: self,
1300 })
1301 } else {
1302 Entry::Vacant(VacantEntry {
1303 hash,
1304 key,
1305 table: self,
1306 })
1307 }
1308 }
1309
1310 /// Gets the given key's corresponding entry by reference in the map for in-place manipulation.
1311 ///
1312 /// # Examples
1313 ///
1314 /// ```
1315 /// use rune::alloc::HashMap;
1316 ///
1317 /// let mut words: HashMap<String, usize> = HashMap::new();
1318 /// let source = ["poneyland", "horseyland", "poneyland", "poneyland"];
1319 /// for (i, &s) in source.iter().enumerate() {
1320 /// let counter = words.entry_ref(s).or_try_insert(0)?;
1321 /// *counter += 1;
1322 /// }
1323 ///
1324 /// assert_eq!(words["poneyland"], 3);
1325 /// assert_eq!(words["horseyland"], 1);
1326 /// # Ok::<_, rune::alloc::Error>(())
1327 /// ```
1328 #[cfg_attr(feature = "inline-more", inline)]
1329 pub fn entry_ref<'a, 'b, Q: ?Sized>(&'a mut self, key: &'b Q) -> EntryRef<'a, 'b, K, Q, V, S, A>
1330 where
1331 Q: Hash + Equivalent<K>,
1332 {
1333 let hash = make_hash::<Q, S>(&self.hash_builder, key);
1334
1335 if let Some(elem) = into_ok(self.table.find(&mut (), hash, equivalent_key(key))) {
1336 EntryRef::Occupied(OccupiedEntryRef {
1337 hash,
1338 key: Some(KeyOrRef::Borrowed(key)),
1339 elem,
1340 table: self,
1341 })
1342 } else {
1343 EntryRef::Vacant(VacantEntryRef {
1344 hash,
1345 key: KeyOrRef::Borrowed(key),
1346 table: self,
1347 })
1348 }
1349 }
1350
1351 /// Returns a reference to the value corresponding to the key.
1352 ///
1353 /// The key may be any borrowed form of the map's key type, but
1354 /// [`Hash`] and [`Eq`] on the borrowed form *must* match those for
1355 /// the key type.
1356 ///
1357 /// [`Eq`]: https://doc.rust-lang.org/std/cmp/trait.Eq.html
1358 /// [`Hash`]: https://doc.rust-lang.org/std/hash/trait.Hash.html
1359 ///
1360 /// # Examples
1361 ///
1362 /// ```
1363 /// use rune::alloc::HashMap;
1364 ///
1365 /// let mut map = HashMap::new();
1366 /// map.try_insert(1, "a")?;
1367 /// assert_eq!(map.get(&1), Some(&"a"));
1368 /// assert_eq!(map.get(&2), None);
1369 /// # Ok::<_, rune::alloc::Error>(())
1370 /// ```
1371 #[inline]
1372 pub fn get<Q: ?Sized>(&self, k: &Q) -> Option<&V>
1373 where
1374 Q: Hash + Equivalent<K>,
1375 {
1376 // Avoid `Option::map` because it bloats LLVM IR.
1377 match self.get_inner(k) {
1378 Some((_, v)) => Some(v),
1379 None => None,
1380 }
1381 }
1382
1383 /// Returns the key-value pair corresponding to the supplied key.
1384 ///
1385 /// The supplied key may be any borrowed form of the map's key type, but
1386 /// [`Hash`] and [`Eq`] on the borrowed form *must* match those for
1387 /// the key type.
1388 ///
1389 /// [`Eq`]: https://doc.rust-lang.org/std/cmp/trait.Eq.html
1390 /// [`Hash`]: https://doc.rust-lang.org/std/hash/trait.Hash.html
1391 ///
1392 /// # Examples
1393 ///
1394 /// ```
1395 /// use rune::alloc::HashMap;
1396 ///
1397 /// let mut map = HashMap::new();
1398 /// map.try_insert(1, "a")?;
1399 /// assert_eq!(map.get_key_value(&1), Some((&1, &"a")));
1400 /// assert_eq!(map.get_key_value(&2), None);
1401 /// # Ok::<_, rune::alloc::Error>(())
1402 /// ```
1403 #[inline]
1404 pub fn get_key_value<Q: ?Sized>(&self, k: &Q) -> Option<(&K, &V)>
1405 where
1406 Q: Hash + Equivalent<K>,
1407 {
1408 // Avoid `Option::map` because it bloats LLVM IR.
1409 match self.get_inner(k) {
1410 Some((key, value)) => Some((key, value)),
1411 None => None,
1412 }
1413 }
1414
1415 #[inline]
1416 fn get_inner<Q: ?Sized>(&self, k: &Q) -> Option<&(K, V)>
1417 where
1418 Q: Hash + Equivalent<K>,
1419 {
1420 if self.table.is_empty() {
1421 None
1422 } else {
1423 let hash = make_hash::<Q, S>(&self.hash_builder, k);
1424 into_ok(self.table.get(&mut (), hash, equivalent_key(k)))
1425 }
1426 }
1427
1428 /// Returns the key-value pair corresponding to the supplied key, with a mutable reference to value.
1429 ///
1430 /// The supplied key may be any borrowed form of the map's key type, but
1431 /// [`Hash`] and [`Eq`] on the borrowed form *must* match those for
1432 /// the key type.
1433 ///
1434 /// [`Eq`]: https://doc.rust-lang.org/std/cmp/trait.Eq.html
1435 /// [`Hash`]: https://doc.rust-lang.org/std/hash/trait.Hash.html
1436 ///
1437 /// # Examples
1438 ///
1439 /// ```
1440 /// use rune::alloc::HashMap;
1441 ///
1442 /// let mut map = HashMap::new();
1443 /// map.try_insert(1, "a")?;
1444 /// let (k, v) = map.get_key_value_mut(&1).unwrap();
1445 /// assert_eq!(k, &1);
1446 /// assert_eq!(v, &mut "a");
1447 /// *v = "b";
1448 /// assert_eq!(map.get_key_value_mut(&1), Some((&1, &mut "b")));
1449 /// assert_eq!(map.get_key_value_mut(&2), None);
1450 /// # Ok::<_, rune::alloc::Error>(())
1451 /// ```
1452 #[inline]
1453 pub fn get_key_value_mut<Q: ?Sized>(&mut self, k: &Q) -> Option<(&K, &mut V)>
1454 where
1455 Q: Hash + Equivalent<K>,
1456 {
1457 // Avoid `Option::map` because it bloats LLVM IR.
1458 match self.get_inner_mut(k) {
1459 Some(&mut (ref key, ref mut value)) => Some((key, value)),
1460 None => None,
1461 }
1462 }
1463
1464 /// Returns `true` if the map contains a value for the specified key.
1465 ///
1466 /// The key may be any borrowed form of the map's key type, but
1467 /// [`Hash`] and [`Eq`] on the borrowed form *must* match those for
1468 /// the key type.
1469 ///
1470 /// [`Eq`]: https://doc.rust-lang.org/std/cmp/trait.Eq.html
1471 /// [`Hash`]: https://doc.rust-lang.org/std/hash/trait.Hash.html
1472 ///
1473 /// # Examples
1474 ///
1475 /// ```
1476 /// use rune::alloc::HashMap;
1477 ///
1478 /// let mut map = HashMap::new();
1479 /// map.try_insert(1, "a")?;
1480 /// assert_eq!(map.contains_key(&1), true);
1481 /// assert_eq!(map.contains_key(&2), false);
1482 /// # Ok::<_, rune::alloc::Error>(())
1483 /// ```
1484 #[cfg_attr(feature = "inline-more", inline)]
1485 pub fn contains_key<Q: ?Sized>(&self, k: &Q) -> bool
1486 where
1487 Q: Hash + Equivalent<K>,
1488 {
1489 self.get_inner(k).is_some()
1490 }
1491
1492 /// Returns a mutable reference to the value corresponding to the key.
1493 ///
1494 /// The key may be any borrowed form of the map's key type, but
1495 /// [`Hash`] and [`Eq`] on the borrowed form *must* match those for
1496 /// the key type.
1497 ///
1498 /// [`Eq`]: https://doc.rust-lang.org/std/cmp/trait.Eq.html
1499 /// [`Hash`]: https://doc.rust-lang.org/std/hash/trait.Hash.html
1500 ///
1501 /// # Examples
1502 ///
1503 /// ```
1504 /// use rune::alloc::HashMap;
1505 ///
1506 /// let mut map = HashMap::new();
1507 /// map.try_insert(1, "a")?;
1508 /// if let Some(x) = map.get_mut(&1) {
1509 /// *x = "b";
1510 /// }
1511 /// assert_eq!(map[&1], "b");
1512 ///
1513 /// assert_eq!(map.get_mut(&2), None);
1514 /// # Ok::<_, rune::alloc::Error>(())
1515 /// ```
1516 #[cfg_attr(feature = "inline-more", inline)]
1517 pub fn get_mut<Q: ?Sized>(&mut self, k: &Q) -> Option<&mut V>
1518 where
1519 Q: Hash + Equivalent<K>,
1520 {
1521 // Avoid `Option::map` because it bloats LLVM IR.
1522 match self.get_inner_mut(k) {
1523 Some(&mut (_, ref mut v)) => Some(v),
1524 None => None,
1525 }
1526 }
1527
1528 #[inline]
1529 fn get_inner_mut<Q: ?Sized>(&mut self, k: &Q) -> Option<&mut (K, V)>
1530 where
1531 Q: Hash + Equivalent<K>,
1532 {
1533 if self.table.is_empty() {
1534 None
1535 } else {
1536 let hash = make_hash::<Q, S>(&self.hash_builder, k);
1537 into_ok(self.table.get_mut(&mut (), hash, equivalent_key(k)))
1538 }
1539 }
1540
1541 /// Attempts to get mutable references to `N` values in the map at once.
1542 ///
1543 /// Returns an array of length `N` with the results of each query. For soundness, at most one
1544 /// mutable reference will be returned to any value. `None` will be returned if any of the
1545 /// keys are duplicates or missing.
1546 ///
1547 /// # Examples
1548 ///
1549 /// ```
1550 /// use rune::alloc::HashMap;
1551 ///
1552 /// let mut libraries = HashMap::new();
1553 /// libraries.try_insert("Bodleian Library".to_string(), 1602)?;
1554 /// libraries.try_insert("Athenæum".to_string(), 1807)?;
1555 /// libraries.try_insert("Herzogin-Anna-Amalia-Bibliothek".to_string(), 1691)?;
1556 /// libraries.try_insert("Library of Congress".to_string(), 1800)?;
1557 ///
1558 /// let got = libraries.get_many_mut([
1559 /// "Athenæum",
1560 /// "Library of Congress",
1561 /// ]);
1562 /// assert_eq!(
1563 /// got,
1564 /// Some([
1565 /// &mut 1807,
1566 /// &mut 1800,
1567 /// ]),
1568 /// );
1569 ///
1570 /// // Missing keys result in None
1571 /// let got = libraries.get_many_mut([
1572 /// "Athenæum",
1573 /// "New York Public Library",
1574 /// ]);
1575 /// assert_eq!(got, None);
1576 ///
1577 /// // Duplicate keys result in None
1578 /// let got = libraries.get_many_mut([
1579 /// "Athenæum",
1580 /// "Athenæum",
1581 /// ]);
1582 /// assert_eq!(got, None);
1583 /// # Ok::<_, rune::alloc::Error>(())
1584 /// ```
1585 pub fn get_many_mut<Q: ?Sized, const N: usize>(&mut self, ks: [&Q; N]) -> Option<[&'_ mut V; N]>
1586 where
1587 Q: Hash + Equivalent<K>,
1588 {
1589 self.get_many_mut_inner(ks).map(|res| res.map(|(_, v)| v))
1590 }
1591
1592 /// Attempts to get mutable references to `N` values in the map at once, without validating that
1593 /// the values are unique.
1594 ///
1595 /// Returns an array of length `N` with the results of each query. `None` will be returned if
1596 /// any of the keys are missing.
1597 ///
1598 /// For a safe alternative see [`get_many_mut`](`HashMap::get_many_mut`).
1599 ///
1600 /// # Safety
1601 ///
1602 /// Calling this method with overlapping keys is *[undefined behavior]* even if the resulting
1603 /// references are not used.
1604 ///
1605 /// [undefined behavior]: https://doc.rust-lang.org/reference/behavior-considered-undefined.html
1606 ///
1607 /// # Examples
1608 ///
1609 /// ```
1610 /// use rune::alloc::HashMap;
1611 ///
1612 /// let mut libraries = HashMap::new();
1613 /// libraries.try_insert("Bodleian Library".to_string(), 1602)?;
1614 /// libraries.try_insert("Athenæum".to_string(), 1807)?;
1615 /// libraries.try_insert("Herzogin-Anna-Amalia-Bibliothek".to_string(), 1691)?;
1616 /// libraries.try_insert("Library of Congress".to_string(), 1800)?;
1617 ///
1618 /// let got = libraries.get_many_mut([
1619 /// "Athenæum",
1620 /// "Library of Congress",
1621 /// ]);
1622 /// assert_eq!(
1623 /// got,
1624 /// Some([
1625 /// &mut 1807,
1626 /// &mut 1800,
1627 /// ]),
1628 /// );
1629 ///
1630 /// // Missing keys result in None
1631 /// let got = libraries.get_many_mut([
1632 /// "Athenæum",
1633 /// "New York Public Library",
1634 /// ]);
1635 /// assert_eq!(got, None);
1636 /// # Ok::<_, rune::alloc::Error>(())
1637 /// ```
1638 pub unsafe fn get_many_unchecked_mut<Q: ?Sized, const N: usize>(
1639 &mut self,
1640 ks: [&Q; N],
1641 ) -> Option<[&'_ mut V; N]>
1642 where
1643 Q: Hash + Equivalent<K>,
1644 {
1645 self.get_many_unchecked_mut_inner(ks)
1646 .map(|res| res.map(|(_, v)| v))
1647 }
1648
1649 /// Attempts to get mutable references to `N` values in the map at once, with immutable
1650 /// references to the corresponding keys.
1651 ///
1652 /// Returns an array of length `N` with the results of each query. For soundness, at most one
1653 /// mutable reference will be returned to any value. `None` will be returned if any of the keys
1654 /// are duplicates or missing.
1655 ///
1656 /// # Examples
1657 ///
1658 /// ```
1659 /// use rune::alloc::HashMap;
1660 ///
1661 /// let mut libraries = HashMap::new();
1662 /// libraries.try_insert("Bodleian Library".to_string(), 1602)?;
1663 /// libraries.try_insert("Athenæum".to_string(), 1807)?;
1664 /// libraries.try_insert("Herzogin-Anna-Amalia-Bibliothek".to_string(), 1691)?;
1665 /// libraries.try_insert("Library of Congress".to_string(), 1800)?;
1666 ///
1667 /// let got = libraries.get_many_key_value_mut([
1668 /// "Bodleian Library",
1669 /// "Herzogin-Anna-Amalia-Bibliothek",
1670 /// ]);
1671 /// assert_eq!(
1672 /// got,
1673 /// Some([
1674 /// (&"Bodleian Library".to_string(), &mut 1602),
1675 /// (&"Herzogin-Anna-Amalia-Bibliothek".to_string(), &mut 1691),
1676 /// ]),
1677 /// );
1678 /// // Missing keys result in None
1679 /// let got = libraries.get_many_key_value_mut([
1680 /// "Bodleian Library",
1681 /// "Gewandhaus",
1682 /// ]);
1683 /// assert_eq!(got, None);
1684 ///
1685 /// // Duplicate keys result in None
1686 /// let got = libraries.get_many_key_value_mut([
1687 /// "Bodleian Library",
1688 /// "Herzogin-Anna-Amalia-Bibliothek",
1689 /// "Herzogin-Anna-Amalia-Bibliothek",
1690 /// ]);
1691 /// assert_eq!(got, None);
1692 /// # Ok::<_, rune::alloc::Error>(())
1693 /// ```
1694 pub fn get_many_key_value_mut<Q: ?Sized, const N: usize>(
1695 &mut self,
1696 ks: [&Q; N],
1697 ) -> Option<[(&'_ K, &'_ mut V); N]>
1698 where
1699 Q: Hash + Equivalent<K>,
1700 {
1701 self.get_many_mut_inner(ks)
1702 .map(|res| res.map(|(k, v)| (&*k, v)))
1703 }
1704
1705 /// Attempts to get mutable references to `N` values in the map at once, with immutable
1706 /// references to the corresponding keys, without validating that the values are unique.
1707 ///
1708 /// Returns an array of length `N` with the results of each query. `None` will be returned if
1709 /// any of the keys are missing.
1710 ///
1711 /// For a safe alternative see [`get_many_key_value_mut`](`HashMap::get_many_key_value_mut`).
1712 ///
1713 /// # Safety
1714 ///
1715 /// Calling this method with overlapping keys is *[undefined behavior]* even if the resulting
1716 /// references are not used.
1717 ///
1718 /// [undefined behavior]: https://doc.rust-lang.org/reference/behavior-considered-undefined.html
1719 ///
1720 /// # Examples
1721 ///
1722 /// ```
1723 /// use rune::alloc::HashMap;
1724 ///
1725 /// let mut libraries = HashMap::new();
1726 /// libraries.try_insert("Bodleian Library".to_string(), 1602)?;
1727 /// libraries.try_insert("Athenæum".to_string(), 1807)?;
1728 /// libraries.try_insert("Herzogin-Anna-Amalia-Bibliothek".to_string(), 1691)?;
1729 /// libraries.try_insert("Library of Congress".to_string(), 1800)?;
1730 ///
1731 /// let got = libraries.get_many_key_value_mut([
1732 /// "Bodleian Library",
1733 /// "Herzogin-Anna-Amalia-Bibliothek",
1734 /// ]);
1735 /// assert_eq!(
1736 /// got,
1737 /// Some([
1738 /// (&"Bodleian Library".to_string(), &mut 1602),
1739 /// (&"Herzogin-Anna-Amalia-Bibliothek".to_string(), &mut 1691),
1740 /// ]),
1741 /// );
1742 /// // Missing keys result in None
1743 /// let got = libraries.get_many_key_value_mut([
1744 /// "Bodleian Library",
1745 /// "Gewandhaus",
1746 /// ]);
1747 /// assert_eq!(got, None);
1748 /// # Ok::<_, rune::alloc::Error>(())
1749 /// ```
1750 pub unsafe fn get_many_key_value_unchecked_mut<Q: ?Sized, const N: usize>(
1751 &mut self,
1752 ks: [&Q; N],
1753 ) -> Option<[(&'_ K, &'_ mut V); N]>
1754 where
1755 Q: Hash + Equivalent<K>,
1756 {
1757 self.get_many_unchecked_mut_inner(ks)
1758 .map(|res| res.map(|(k, v)| (&*k, v)))
1759 }
1760
1761 fn get_many_mut_inner<Q: ?Sized, const N: usize>(
1762 &mut self,
1763 ks: [&Q; N],
1764 ) -> Option<[&'_ mut (K, V); N]>
1765 where
1766 Q: Hash + Equivalent<K>,
1767 {
1768 let hashes = self.build_hashes_inner(ks);
1769 into_ok(
1770 self.table
1771 .get_many_mut(&mut (), hashes, |_, i, (k, _)| Ok(ks[i].equivalent(k))),
1772 )
1773 }
1774
1775 unsafe fn get_many_unchecked_mut_inner<Q: ?Sized, const N: usize>(
1776 &mut self,
1777 ks: [&Q; N],
1778 ) -> Option<[&'_ mut (K, V); N]>
1779 where
1780 Q: Hash + Equivalent<K>,
1781 {
1782 let hashes = self.build_hashes_inner(ks);
1783 into_ok(
1784 self.table
1785 .get_many_unchecked_mut(&mut (), hashes, |_, i, (k, _)| Ok(ks[i].equivalent(k))),
1786 )
1787 }
1788
1789 fn build_hashes_inner<Q: ?Sized, const N: usize>(&self, ks: [&Q; N]) -> [u64; N]
1790 where
1791 Q: Hash + Equivalent<K>,
1792 {
1793 let mut hashes = [0_u64; N];
1794 for i in 0..N {
1795 hashes[i] = make_hash::<Q, S>(&self.hash_builder, ks[i]);
1796 }
1797 hashes
1798 }
1799
1800 /// Inserts a key-value pair into the map.
1801 ///
1802 /// If the map did not have this key present, [`None`] is returned.
1803 ///
1804 /// If the map did have this key present, the value is updated, and the old
1805 /// value is returned. The key is not updated, though; this matters for
1806 /// types that can be `==` without being identical. See the [`std::collections`]
1807 /// [module-level documentation] for more.
1808 ///
1809 /// [`None`]: https://doc.rust-lang.org/std/option/enum.Option.html#variant.None
1810 /// [`std::collections`]: https://doc.rust-lang.org/std/collections/index.html
1811 /// [module-level documentation]: https://doc.rust-lang.org/std/collections/index.html#insert-and-complex-keys
1812 ///
1813 /// # Examples
1814 ///
1815 /// ```
1816 /// use rune::alloc::HashMap;
1817 ///
1818 /// let mut map = HashMap::new();
1819 /// assert_eq!(map.try_insert(37, "a")?, None);
1820 /// assert_eq!(map.is_empty(), false);
1821 ///
1822 /// map.try_insert(37, "b")?;
1823 /// assert_eq!(map.try_insert(37, "c")?, Some("b"));
1824 /// assert_eq!(map[&37], "c");
1825 /// # Ok::<_, rune::alloc::Error>(())
1826 /// ```
1827 #[cfg_attr(feature = "inline-more", inline)]
1828 pub fn try_insert(&mut self, k: K, v: V) -> Result<Option<V>, Error> {
1829 let hasher = make_hasher::<K, S>(&self.hash_builder);
1830 let hash = into_ok(hasher.hash(&mut (), &k));
1831
1832 let result = self.table.find_or_find_insert_slot(
1833 &mut (),
1834 hash,
1835 equivalent_key(&k),
1836 hasher.into_tuple(),
1837 );
1838
1839 Ok(match result {
1840 Ok(bucket) => Some(mem::replace(unsafe { &mut bucket.as_mut().1 }, v)),
1841 Err(ErrorOrInsertSlot::InsertSlot(slot)) => {
1842 unsafe {
1843 self.table.insert_in_slot(hash, slot, (k, v));
1844 }
1845 None
1846 }
1847 Err(ErrorOrInsertSlot::Error(error)) => match error {
1848 CustomError::Custom(error) => match error {},
1849 CustomError::Error(error) => return Err(error),
1850 },
1851 })
1852 }
1853
1854 #[cfg(test)]
1855 pub(crate) fn insert(&mut self, k: K, v: V) -> Option<V> {
1856 self.try_insert(k, v).abort()
1857 }
1858
1859 /// Insert a key-value pair into the map without checking
1860 /// if the key already exists in the map.
1861 ///
1862 /// Returns a reference to the key and value just inserted.
1863 ///
1864 /// This operation is safe if a key does not exist in the map.
1865 ///
1866 /// However, if a key exists in the map already, the behavior is unspecified:
1867 /// this operation may panic, loop forever, or any following operation with the map
1868 /// may panic, loop forever or return arbitrary result.
1869 ///
1870 /// That said, this operation (and following operations) are guaranteed to
1871 /// not violate memory safety.
1872 ///
1873 /// This operation is faster than regular insert, because it does not perform
1874 /// lookup before insertion.
1875 ///
1876 /// This operation is useful during initial population of the map.
1877 /// For example, when constructing a map from another map, we know
1878 /// that keys are unique.
1879 ///
1880 /// # Examples
1881 ///
1882 /// ```
1883 /// use rune::alloc::HashMap;
1884 ///
1885 /// let mut map1 = HashMap::new();
1886 /// assert_eq!(map1.try_insert(1, "a")?, None);
1887 /// assert_eq!(map1.try_insert(2, "b")?, None);
1888 /// assert_eq!(map1.try_insert(3, "c")?, None);
1889 /// assert_eq!(map1.len(), 3);
1890 ///
1891 /// let mut map2 = HashMap::new();
1892 ///
1893 /// for (key, value) in map1.into_iter() {
1894 /// map2.try_insert_unique_unchecked(key, value)?;
1895 /// }
1896 ///
1897 /// let (key, value) = map2.try_insert_unique_unchecked(4, "d")?;
1898 /// assert_eq!(key, &4);
1899 /// assert_eq!(value, &mut "d");
1900 /// *value = "e";
1901 ///
1902 /// assert_eq!(map2[&1], "a");
1903 /// assert_eq!(map2[&2], "b");
1904 /// assert_eq!(map2[&3], "c");
1905 /// assert_eq!(map2[&4], "e");
1906 /// assert_eq!(map2.len(), 4);
1907 /// # Ok::<_, rune::alloc::Error>(())
1908 /// ```
1909 #[cfg_attr(feature = "inline-more", inline)]
1910 pub fn try_insert_unique_unchecked(&mut self, k: K, v: V) -> Result<(&K, &mut V), Error> {
1911 let hasher = make_hasher::<K, S>(&self.hash_builder);
1912 let hash = into_ok(hasher.hash(&mut (), &k));
1913 let bucket = into_ok_try(
1914 self.table
1915 .insert(&mut (), hash, (k, v), hasher.into_tuple()),
1916 )?;
1917 let (k_ref, v_ref) = unsafe { bucket.as_mut() };
1918 Ok((k_ref, v_ref))
1919 }
1920
1921 #[cfg(test)]
1922 pub(crate) fn insert_unique_unchecked(&mut self, k: K, v: V) -> (&K, &mut V) {
1923 self.try_insert_unique_unchecked(k, v).abort()
1924 }
1925
1926 /// Tries to insert a key-value pair into the map, and returns
1927 /// a mutable reference to the value in the entry.
1928 ///
1929 /// # Errors
1930 ///
1931 /// If the map already had this key present, nothing is updated, and
1932 /// an error containing the occupied entry and the value is returned.
1933 ///
1934 /// # Examples
1935 ///
1936 /// Basic usage:
1937 ///
1938 /// ```
1939 /// use rune::alloc::HashMap;
1940 /// use rune::alloc::error::CustomError;
1941 /// use rune::alloc::hash_map::OccupiedError;
1942 ///
1943 /// let mut map = HashMap::new();
1944 /// assert_eq!(map.try_insert_or(37, "a").unwrap(), &"a");
1945 ///
1946 /// match map.try_insert_or(37, "b") {
1947 /// Err(CustomError::Custom(OccupiedError { entry, value })) => {
1948 /// assert_eq!(entry.key(), &37);
1949 /// assert_eq!(entry.get(), &"a");
1950 /// assert_eq!(value, "b");
1951 /// }
1952 /// _ => panic!()
1953 /// }
1954 /// # Ok::<_, rune::alloc::Error>(())
1955 /// ```
1956 #[cfg_attr(feature = "inline-more", inline)]
1957 pub fn try_insert_or(
1958 &mut self,
1959 key: K,
1960 value: V,
1961 ) -> Result<&mut V, CustomError<OccupiedError<'_, K, V, S, A>>> {
1962 match self.entry(key) {
1963 Entry::Occupied(entry) => Err(CustomError::Custom(OccupiedError { entry, value })),
1964 Entry::Vacant(entry) => Ok(entry.try_insert(value)?),
1965 }
1966 }
1967
1968 /// Removes a key from the map, returning the value at the key if the key
1969 /// was previously in the map. Keeps the allocated memory for reuse.
1970 ///
1971 /// The key may be any borrowed form of the map's key type, but
1972 /// [`Hash`] and [`Eq`] on the borrowed form *must* match those for
1973 /// the key type.
1974 ///
1975 /// [`Eq`]: https://doc.rust-lang.org/std/cmp/trait.Eq.html
1976 /// [`Hash`]: https://doc.rust-lang.org/std/hash/trait.Hash.html
1977 ///
1978 /// # Examples
1979 ///
1980 /// ```
1981 /// use rune::alloc::HashMap;
1982 ///
1983 /// let mut map = HashMap::new();
1984 /// // The map is empty
1985 /// assert!(map.is_empty() && map.capacity() == 0);
1986 ///
1987 /// map.try_insert(1, "a")?;
1988 ///
1989 /// assert_eq!(map.remove(&1), Some("a"));
1990 /// assert_eq!(map.remove(&1), None);
1991 ///
1992 /// // Now map holds none elements
1993 /// assert!(map.is_empty());
1994 /// # Ok::<_, rune::alloc::Error>(())
1995 /// ```
1996 #[cfg_attr(feature = "inline-more", inline)]
1997 pub fn remove<Q: ?Sized>(&mut self, k: &Q) -> Option<V>
1998 where
1999 Q: Hash + Equivalent<K>,
2000 {
2001 // Avoid `Option::map` because it bloats LLVM IR.
2002 match self.remove_entry(k) {
2003 Some((_, v)) => Some(v),
2004 None => None,
2005 }
2006 }
2007
2008 /// Removes a key from the map, returning the stored key and value if the
2009 /// key was previously in the map. Keeps the allocated memory for reuse.
2010 ///
2011 /// The key may be any borrowed form of the map's key type, but
2012 /// [`Hash`] and [`Eq`] on the borrowed form *must* match those for
2013 /// the key type.
2014 ///
2015 /// [`Eq`]: https://doc.rust-lang.org/std/cmp/trait.Eq.html
2016 /// [`Hash`]: https://doc.rust-lang.org/std/hash/trait.Hash.html
2017 ///
2018 /// # Examples
2019 ///
2020 /// ```
2021 /// use rune::alloc::HashMap;
2022 ///
2023 /// let mut map = HashMap::new();
2024 /// // The map is empty
2025 /// assert!(map.is_empty() && map.capacity() == 0);
2026 ///
2027 /// map.try_insert(1, "a")?;
2028 ///
2029 /// assert_eq!(map.remove_entry(&1), Some((1, "a")));
2030 /// assert_eq!(map.remove(&1), None);
2031 ///
2032 /// // Now map hold none elements
2033 /// assert!(map.is_empty());
2034 /// # Ok::<_, rune::alloc::Error>(())
2035 /// ```
2036 #[cfg_attr(feature = "inline-more", inline)]
2037 pub fn remove_entry<Q: ?Sized>(&mut self, k: &Q) -> Option<(K, V)>
2038 where
2039 Q: Hash + Equivalent<K>,
2040 {
2041 let hash = make_hash::<Q, S>(&self.hash_builder, k);
2042 into_ok(self.table.remove_entry(&mut (), hash, equivalent_key(k)))
2043 }
2044}
2045
2046impl<K, V, S, A: Allocator> HashMap<K, V, S, A> {
2047 /// Creates a raw entry builder for the HashMap.
2048 ///
2049 /// Raw entries provide the lowest level of control for searching and
2050 /// manipulating a map. They must be manually initialized with a hash and
2051 /// then manually searched. After this, insertions into a vacant entry
2052 /// still require an owned key to be provided.
2053 ///
2054 /// Raw entries are useful for such exotic situations as:
2055 ///
2056 /// * Hash memoization
2057 /// * Deferring the creation of an owned key until it is known to be required
2058 /// * Using a search key that doesn't work with the Borrow trait
2059 /// * Using custom comparison logic without newtype wrappers
2060 ///
2061 /// Because raw entries provide much more low-level control, it's much easier
2062 /// to put the HashMap into an inconsistent state which, while memory-safe,
2063 /// will cause the map to produce seemingly random results. Higher-level and
2064 /// more foolproof APIs like `entry` should be preferred when possible.
2065 ///
2066 /// In particular, the hash used to initialized the raw entry must still be
2067 /// consistent with the hash of the key that is ultimately stored in the entry.
2068 /// This is because implementations of HashMap may need to recompute hashes
2069 /// when resizing, at which point only the keys are available.
2070 ///
2071 /// Raw entries give mutable access to the keys. This must not be used
2072 /// to modify how the key would compare or hash, as the map will not re-evaluate
2073 /// where the key should go, meaning the keys may become "lost" if their
2074 /// location does not reflect their state. For instance, if you change a key
2075 /// so that the map now contains keys which compare equal, search may start
2076 /// acting erratically, with two keys randomly masking each other. Implementations
2077 /// are free to assume this doesn't happen (within the limits of memory-safety).
2078 ///
2079 /// # Examples
2080 ///
2081 /// ```
2082 /// use core::hash::{BuildHasher, Hash};
2083 /// use rune::alloc::hash_map::{HashMap, RawEntryMut};
2084 /// use rune::alloc::prelude::*;
2085 ///
2086 /// let mut map = HashMap::new();
2087 /// map.try_extend([("a", 100), ("b", 200), ("c", 300)])?;
2088 ///
2089 /// fn compute_hash<K: Hash + ?Sized, S: BuildHasher>(hash_builder: &S, key: &K) -> u64 {
2090 /// use core::hash::Hasher;
2091 /// let mut state = hash_builder.build_hasher();
2092 /// key.hash(&mut state);
2093 /// state.finish()
2094 /// }
2095 ///
2096 /// // Existing key (insert and update)
2097 /// match map.raw_entry_mut().from_key(&"a") {
2098 /// RawEntryMut::Vacant(_) => unreachable!(),
2099 /// RawEntryMut::Occupied(mut view) => {
2100 /// assert_eq!(view.get(), &100);
2101 /// let v = view.get_mut();
2102 /// let new_v = (*v) * 10;
2103 /// *v = new_v;
2104 /// assert_eq!(view.insert(1111), 1000);
2105 /// }
2106 /// }
2107 ///
2108 /// assert_eq!(map[&"a"], 1111);
2109 /// assert_eq!(map.len(), 3);
2110 ///
2111 /// // Existing key (take)
2112 /// let hash = compute_hash(map.hasher(), &"c");
2113 /// match map.raw_entry_mut().from_key_hashed_nocheck(hash, &"c") {
2114 /// RawEntryMut::Vacant(_) => unreachable!(),
2115 /// RawEntryMut::Occupied(view) => {
2116 /// assert_eq!(view.remove_entry(), ("c", 300));
2117 /// }
2118 /// }
2119 /// assert_eq!(map.raw_entry().from_key(&"c"), None);
2120 /// assert_eq!(map.len(), 2);
2121 ///
2122 /// // Nonexistent key (insert and update)
2123 /// let key = "d";
2124 /// let hash = compute_hash(map.hasher(), &key);
2125 /// match map.raw_entry_mut().from_hash(hash, |q| *q == key) {
2126 /// RawEntryMut::Occupied(_) => unreachable!(),
2127 /// RawEntryMut::Vacant(view) => {
2128 /// let (k, value) = view.try_insert("d", 4000)?;
2129 /// assert_eq!((*k, *value), ("d", 4000));
2130 /// *value = 40000;
2131 /// }
2132 /// }
2133 /// assert_eq!(map[&"d"], 40000);
2134 /// assert_eq!(map.len(), 3);
2135 ///
2136 /// match map.raw_entry_mut().from_hash(hash, |q| *q == key) {
2137 /// RawEntryMut::Vacant(_) => unreachable!(),
2138 /// RawEntryMut::Occupied(view) => {
2139 /// assert_eq!(view.remove_entry(), ("d", 40000));
2140 /// }
2141 /// }
2142 /// assert_eq!(map.get(&"d"), None);
2143 /// assert_eq!(map.len(), 2);
2144 /// # Ok::<_, rune::alloc::Error>(())
2145 /// ```
2146 #[cfg_attr(feature = "inline-more", inline)]
2147 pub fn raw_entry_mut(&mut self) -> RawEntryBuilderMut<'_, K, V, S, A> {
2148 RawEntryBuilderMut { map: self }
2149 }
2150
2151 /// Creates a raw immutable entry builder for the HashMap.
2152 ///
2153 /// Raw entries provide the lowest level of control for searching and
2154 /// manipulating a map. They must be manually initialized with a hash and
2155 /// then manually searched.
2156 ///
2157 /// This is useful for
2158 /// * Hash memoization
2159 /// * Using a search key that doesn't work with the Borrow trait
2160 /// * Using custom comparison logic without newtype wrappers
2161 ///
2162 /// Unless you are in such a situation, higher-level and more foolproof APIs like
2163 /// `get` should be preferred.
2164 ///
2165 /// Immutable raw entries have very limited use; you might instead want `raw_entry_mut`.
2166 ///
2167 /// # Examples
2168 ///
2169 /// ```
2170 /// use core::hash::{BuildHasher, Hash};
2171 /// use rune::alloc::HashMap;
2172 /// use rune::alloc::prelude::*;
2173 ///
2174 /// let mut map = HashMap::new();
2175 /// map.try_extend([("a", 100), ("b", 200), ("c", 300)])?;
2176 ///
2177 /// fn compute_hash<K: Hash + ?Sized, S: BuildHasher>(hash_builder: &S, key: &K) -> u64 {
2178 /// use core::hash::Hasher;
2179 /// let mut state = hash_builder.build_hasher();
2180 /// key.hash(&mut state);
2181 /// state.finish()
2182 /// }
2183 ///
2184 /// for k in ["a", "b", "c", "d", "e", "f"] {
2185 /// let hash = compute_hash(map.hasher(), k);
2186 /// let v = map.get(&k).cloned();
2187 /// let kv = v.as_ref().map(|v| (&k, v));
2188 ///
2189 /// println!("Key: {} and value: {:?}", k, v);
2190 ///
2191 /// assert_eq!(map.raw_entry().from_key(&k), kv);
2192 /// assert_eq!(map.raw_entry().from_hash(hash, |q| *q == k), kv);
2193 /// assert_eq!(map.raw_entry().from_key_hashed_nocheck(hash, &k), kv);
2194 /// }
2195 /// # Ok::<_, rune::alloc::Error>(())
2196 /// ```
2197 #[cfg_attr(feature = "inline-more", inline)]
2198 pub fn raw_entry(&self) -> RawEntryBuilder<'_, K, V, S, A> {
2199 RawEntryBuilder { map: self }
2200 }
2201
2202 /// Returns a reference to the [`RawTable`] used underneath [`HashMap`].
2203 /// This function is only available if the `raw` feature of the crate is enabled.
2204 ///
2205 /// See [`raw_table_mut`] for more.
2206 ///
2207 /// [`raw_table_mut`]: Self::raw_table_mut
2208 #[cfg_attr(feature = "inline-more", inline)]
2209 pub fn raw_table(&self) -> &RawTable<(K, V), A> {
2210 &self.table
2211 }
2212
2213 /// Returns a mutable reference to the [`RawTable`] used underneath [`HashMap`].
2214 /// This function is only available if the `raw` feature of the crate is enabled.
2215 ///
2216 /// # Note
2217 ///
2218 /// Calling this function is safe, but using the raw hash table API may require
2219 /// unsafe functions or blocks.
2220 ///
2221 /// `RawTable` API gives the lowest level of control under the map that can be useful
2222 /// for extending the HashMap's API, but may lead to *[undefined behavior]*.
2223 ///
2224 /// [`RawTable`]: crate::hashbrown::raw::RawTable
2225 /// [undefined behavior]:
2226 /// https://doc.rust-lang.org/reference/behavior-considered-undefined.html
2227 ///
2228 /// # Examples
2229 ///
2230 /// ```
2231 /// use core::hash::{BuildHasher, Hash};
2232 /// use core::convert::Infallible;
2233 /// use rune::alloc::HashMap;
2234 /// use rune::alloc::prelude::*;
2235 ///
2236 /// let mut map = HashMap::new();
2237 /// map.try_extend([("a", 10), ("b", 20), ("c", 30)])?;
2238 /// assert_eq!(map.len(), 3);
2239 ///
2240 /// // Let's imagine that we have a value and a hash of the key, but not the key itself.
2241 /// // However, if you want to remove the value from the map by hash and value, and you
2242 /// // know exactly that the value is unique, then you can create a function like this:
2243 /// fn remove_by_hash<K, V, S, F>(
2244 /// map: &mut HashMap<K, V, S>,
2245 /// hash: u64,
2246 /// is_match: F,
2247 /// ) -> Option<(K, V)>
2248 /// where
2249 /// F: Fn(&(K, V)) -> bool,
2250 /// {
2251 /// let raw_table = map.raw_table_mut();
2252 /// match raw_table.find(&mut (), hash, |_: &mut (), k: &(K, V)| Ok::<_, Infallible>(is_match(k))).unwrap() {
2253 /// Some(bucket) => Some(unsafe { raw_table.remove(bucket).0 }),
2254 /// None => None,
2255 /// }
2256 /// }
2257 ///
2258 /// fn compute_hash<K: Hash + ?Sized, S: BuildHasher>(hash_builder: &S, key: &K) -> u64 {
2259 /// use core::hash::Hasher;
2260 /// let mut state = hash_builder.build_hasher();
2261 /// key.hash(&mut state);
2262 /// state.finish()
2263 /// }
2264 ///
2265 /// let hash = compute_hash(map.hasher(), "a");
2266 /// assert_eq!(remove_by_hash(&mut map, hash, |(_, v)| *v == 10), Some(("a", 10)));
2267 /// assert_eq!(map.get(&"a"), None);
2268 /// assert_eq!(map.len(), 2);
2269 /// # Ok::<_, rune::alloc::Error>(())
2270 /// ```
2271 #[cfg_attr(feature = "inline-more", inline)]
2272 pub fn raw_table_mut(&mut self) -> &mut RawTable<(K, V), A> {
2273 &mut self.table
2274 }
2275}
2276
2277impl<K, V, S, A> PartialEq for HashMap<K, V, S, A>
2278where
2279 K: Eq + Hash,
2280 V: PartialEq,
2281 S: BuildHasher,
2282 A: Allocator,
2283{
2284 fn eq(&self, other: &Self) -> bool {
2285 if self.len() != other.len() {
2286 return false;
2287 }
2288
2289 self.iter()
2290 .all(|(key, value)| other.get(key).map_or(false, |v| *value == *v))
2291 }
2292}
2293
2294impl<K, V, S, A> Eq for HashMap<K, V, S, A>
2295where
2296 K: Eq + Hash,
2297 V: Eq,
2298 S: BuildHasher,
2299 A: Allocator,
2300{
2301}
2302
2303impl<K, V, S, A> Debug for HashMap<K, V, S, A>
2304where
2305 K: Debug,
2306 V: Debug,
2307 A: Allocator,
2308{
2309 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2310 f.debug_map().entries(self.iter()).finish()
2311 }
2312}
2313
2314impl<K, V, S, A> Default for HashMap<K, V, S, A>
2315where
2316 S: Default,
2317 A: Default + Allocator,
2318{
2319 /// Creates an empty `HashMap<K, V, S, A>`, with the `Default` value for the hasher and allocator.
2320 ///
2321 /// # Examples
2322 ///
2323 /// ```
2324 /// use rune::alloc::HashMap;
2325 /// use std::collections::hash_map::RandomState;
2326 ///
2327 /// // You can specify all types of HashMap, including hasher and allocator.
2328 /// // Created map is empty and don't allocate memory
2329 /// let map: HashMap<u32, String> = Default::default();
2330 /// assert_eq!(map.capacity(), 0);
2331 /// let map: HashMap<u32, String, RandomState> = HashMap::default();
2332 /// assert_eq!(map.capacity(), 0);
2333 /// # Ok::<_, rune::alloc::Error>(())
2334 /// ```
2335 #[cfg_attr(feature = "inline-more", inline)]
2336 fn default() -> Self {
2337 Self::with_hasher_in(Default::default(), Default::default())
2338 }
2339}
2340
2341impl<K, Q: ?Sized, V, S, A> Index<&Q> for HashMap<K, V, S, A>
2342where
2343 K: Eq + Hash,
2344 Q: Hash + Equivalent<K>,
2345 S: BuildHasher,
2346 A: Allocator,
2347{
2348 type Output = V;
2349
2350 /// Returns a reference to the value corresponding to the supplied key.
2351 ///
2352 /// # Panics
2353 ///
2354 /// Panics if the key is not present in the `HashMap`.
2355 ///
2356 /// # Examples
2357 ///
2358 /// ```
2359 /// use rune::alloc::HashMap;
2360 ///
2361 /// let map: HashMap<_, _> = [("a", "One"), ("b", "Two")].try_into()?;
2362 ///
2363 /// assert_eq!(map[&"a"], "One");
2364 /// assert_eq!(map[&"b"], "Two");
2365 /// # Ok::<_, rune::alloc::Error>(())
2366 /// ```
2367 #[cfg_attr(feature = "inline-more", inline)]
2368 fn index(&self, key: &Q) -> &V {
2369 self.get(key).expect("no entry found for key")
2370 }
2371}
2372
2373// The default hasher is used to match the std implementation signature
2374impl<K, V, A, const N: usize> TryFrom<[(K, V); N]> for HashMap<K, V, DefaultHashBuilder, A>
2375where
2376 K: Eq + Hash,
2377 A: Default + Allocator,
2378{
2379 type Error = Error;
2380
2381 /// # Examples
2382 ///
2383 /// ```
2384 /// use rune::alloc::HashMap;
2385 ///
2386 /// let map1 = HashMap::try_from([(1, 2), (3, 4)])?;
2387 /// let map2: HashMap<_, _> = [(1, 2), (3, 4)].try_into()?;
2388 /// assert_eq!(map1, map2);
2389 /// # Ok::<_, rune::alloc::Error>(())
2390 /// ```
2391 fn try_from(arr: [(K, V); N]) -> Result<Self, Self::Error> {
2392 HashMap::try_from_iter_in(arr, A::default())
2393 }
2394}
2395
2396/// An iterator over the entries of a `HashMap` in arbitrary order.
2397/// The iterator element type is `(&'a K, &'a V)`.
2398///
2399/// This `struct` is created by the [`iter`] method on [`HashMap`]. See its
2400/// documentation for more.
2401///
2402/// [`iter`]: struct.HashMap.html#method.iter
2403/// [`HashMap`]: struct.HashMap.html
2404///
2405/// # Examples
2406///
2407/// ```
2408/// use rune::alloc::HashMap;
2409///
2410/// let map: HashMap<_, _> = [(1, "a"), (2, "b"), (3, "c")].try_into()?;
2411///
2412/// let mut iter = map.iter();
2413/// let mut vec = vec![iter.next(), iter.next(), iter.next()];
2414///
2415/// // The `Iter` iterator produces items in arbitrary order, so the
2416/// // items must be sorted to test them against a sorted array.
2417/// vec.sort_unstable();
2418/// assert_eq!(vec, [Some((&1, &"a")), Some((&2, &"b")), Some((&3, &"c"))]);
2419///
2420/// // It is fused iterator
2421/// assert_eq!(iter.next(), None);
2422/// assert_eq!(iter.next(), None);
2423/// # Ok::<_, rune::alloc::Error>(())
2424/// ```
2425pub struct Iter<'a, K, V> {
2426 inner: RawIter<(K, V)>,
2427 marker: PhantomData<(&'a K, &'a V)>,
2428}
2429
2430// FIXME(#26925) Remove in favor of `#[derive(Clone)]`
2431impl<K, V> Clone for Iter<'_, K, V> {
2432 #[cfg_attr(feature = "inline-more", inline)]
2433 fn clone(&self) -> Self {
2434 Iter {
2435 inner: self.inner.clone(),
2436 marker: PhantomData,
2437 }
2438 }
2439}
2440
2441impl<K: Debug, V: Debug> fmt::Debug for Iter<'_, K, V> {
2442 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2443 f.debug_list().entries(self.clone()).finish()
2444 }
2445}
2446
2447/// A mutable iterator over the entries of a `HashMap` in arbitrary order.
2448/// The iterator element type is `(&'a K, &'a mut V)`.
2449///
2450/// This `struct` is created by the [`iter_mut`] method on [`HashMap`]. See its
2451/// documentation for more.
2452///
2453/// [`iter_mut`]: struct.HashMap.html#method.iter_mut
2454/// [`HashMap`]: struct.HashMap.html
2455///
2456/// # Examples
2457///
2458/// ```
2459/// use rune::alloc::HashMap;
2460///
2461/// let mut map: HashMap<_, _> = [(1, "One".to_owned()), (2, "Two".into())].try_into()?;
2462///
2463/// let mut iter = map.iter_mut();
2464/// iter.next().map(|(_, v)| v.push_str(" Mississippi"));
2465/// iter.next().map(|(_, v)| v.push_str(" Mississippi"));
2466///
2467/// // It is fused iterator
2468/// assert_eq!(iter.next(), None);
2469/// assert_eq!(iter.next(), None);
2470///
2471/// assert_eq!(map.get(&1).unwrap(), &"One Mississippi".to_owned());
2472/// assert_eq!(map.get(&2).unwrap(), &"Two Mississippi".to_owned());
2473/// # Ok::<_, rune::alloc::Error>(())
2474/// ```
2475pub struct IterMut<'a, K, V> {
2476 inner: RawIter<(K, V)>,
2477 // To ensure invariance with respect to V
2478 marker: PhantomData<(&'a K, &'a mut V)>,
2479}
2480
2481// We override the default Send impl which has K: Sync instead of K: Send. Both
2482// are correct, but this one is more general since it allows keys which
2483// implement Send but not Sync.
2484unsafe impl<K: Send, V: Send> Send for IterMut<'_, K, V> {}
2485
2486impl<K, V> IterMut<'_, K, V> {
2487 /// Returns a iterator of references over the remaining items.
2488 #[cfg_attr(feature = "inline-more", inline)]
2489 pub(super) fn iter(&self) -> Iter<'_, K, V> {
2490 Iter {
2491 inner: self.inner.clone(),
2492 marker: PhantomData,
2493 }
2494 }
2495}
2496
2497/// An owning iterator over the entries of a `HashMap` in arbitrary order.
2498/// The iterator element type is `(K, V)`.
2499///
2500/// This `struct` is created by the [`into_iter`] method on [`HashMap`]
2501/// (provided by the [`IntoIterator`] trait). See its documentation for more.
2502/// The map cannot be used after calling that method.
2503///
2504/// [`into_iter`]: struct.HashMap.html#method.into_iter
2505/// [`HashMap`]: struct.HashMap.html
2506/// [`IntoIterator`]: https://doc.rust-lang.org/core/iter/trait.IntoIterator.html
2507///
2508/// # Examples
2509///
2510/// ```
2511/// use rune::alloc::HashMap;
2512///
2513/// let map: HashMap<_, _> = [(1, "a"), (2, "b"), (3, "c")].try_into()?;
2514///
2515/// let mut iter = map.into_iter();
2516/// let mut vec = vec![iter.next(), iter.next(), iter.next()];
2517///
2518/// // The `IntoIter` iterator produces items in arbitrary order, so the
2519/// // items must be sorted to test them against a sorted array.
2520/// vec.sort_unstable();
2521/// assert_eq!(vec, [Some((1, "a")), Some((2, "b")), Some((3, "c"))]);
2522///
2523/// // It is fused iterator
2524/// assert_eq!(iter.next(), None);
2525/// assert_eq!(iter.next(), None);
2526/// # Ok::<_, rune::alloc::Error>(())
2527/// ```
2528pub struct IntoIter<K, V, A: Allocator = Global> {
2529 inner: RawIntoIter<(K, V), A>,
2530}
2531
2532impl<K, V, A: Allocator> IntoIter<K, V, A> {
2533 /// Returns a iterator of references over the remaining items.
2534 #[cfg_attr(feature = "inline-more", inline)]
2535 pub(super) fn iter(&self) -> Iter<'_, K, V> {
2536 Iter {
2537 inner: self.inner.iter(),
2538 marker: PhantomData,
2539 }
2540 }
2541}
2542
2543/// An owning iterator over the keys of a `HashMap` in arbitrary order.
2544/// The iterator element type is `K`.
2545///
2546/// This `struct` is created by the [`into_keys`] method on [`HashMap`].
2547/// See its documentation for more.
2548/// The map cannot be used after calling that method.
2549///
2550/// [`into_keys`]: struct.HashMap.html#method.into_keys
2551/// [`HashMap`]: struct.HashMap.html
2552///
2553/// # Examples
2554///
2555/// ```
2556/// use rune::alloc::HashMap;
2557///
2558/// let map: HashMap<_, _> = [(1, "a"), (2, "b"), (3, "c")].try_into()?;
2559///
2560/// let mut keys = map.into_keys();
2561/// let mut vec = vec![keys.next(), keys.next(), keys.next()];
2562///
2563/// // The `IntoKeys` iterator produces keys in arbitrary order, so the
2564/// // keys must be sorted to test them against a sorted array.
2565/// vec.sort_unstable();
2566/// assert_eq!(vec, [Some(1), Some(2), Some(3)]);
2567///
2568/// // It is fused iterator
2569/// assert_eq!(keys.next(), None);
2570/// assert_eq!(keys.next(), None);
2571/// # Ok::<_, rune::alloc::Error>(())
2572/// ```
2573pub struct IntoKeys<K, V, A: Allocator = Global> {
2574 inner: IntoIter<K, V, A>,
2575}
2576
2577impl<K, V, A: Allocator> Iterator for IntoKeys<K, V, A> {
2578 type Item = K;
2579
2580 #[inline]
2581 fn next(&mut self) -> Option<K> {
2582 self.inner.next().map(|(k, _)| k)
2583 }
2584 #[inline]
2585 fn size_hint(&self) -> (usize, Option<usize>) {
2586 self.inner.size_hint()
2587 }
2588}
2589
2590impl<K, V, A: Allocator> ExactSizeIterator for IntoKeys<K, V, A> {
2591 #[inline]
2592 fn len(&self) -> usize {
2593 self.inner.len()
2594 }
2595}
2596
2597impl<K, V, A: Allocator> FusedIterator for IntoKeys<K, V, A> {}
2598
2599impl<K: Debug, V: Debug, A: Allocator> fmt::Debug for IntoKeys<K, V, A> {
2600 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2601 f.debug_list()
2602 .entries(self.inner.iter().map(|(k, _)| k))
2603 .finish()
2604 }
2605}
2606
2607/// An owning iterator over the values of a `HashMap` in arbitrary order.
2608/// The iterator element type is `V`.
2609///
2610/// This `struct` is created by the [`into_values`] method on [`HashMap`].
2611/// See its documentation for more. The map cannot be used after calling that method.
2612///
2613/// [`into_values`]: struct.HashMap.html#method.into_values
2614/// [`HashMap`]: struct.HashMap.html
2615///
2616/// # Examples
2617///
2618/// ```
2619/// use rune::alloc::HashMap;
2620///
2621/// let map: HashMap<_, _> = [(1, "a"), (2, "b"), (3, "c")].try_into()?;
2622///
2623/// let mut values = map.into_values();
2624/// let mut vec = vec![values.next(), values.next(), values.next()];
2625///
2626/// // The `IntoValues` iterator produces values in arbitrary order, so
2627/// // the values must be sorted to test them against a sorted array.
2628/// vec.sort_unstable();
2629/// assert_eq!(vec, [Some("a"), Some("b"), Some("c")]);
2630///
2631/// // It is fused iterator
2632/// assert_eq!(values.next(), None);
2633/// assert_eq!(values.next(), None);
2634/// # Ok::<_, rune::alloc::Error>(())
2635/// ```
2636pub struct IntoValues<K, V, A: Allocator = Global> {
2637 inner: IntoIter<K, V, A>,
2638}
2639
2640impl<K, V, A: Allocator> Iterator for IntoValues<K, V, A> {
2641 type Item = V;
2642
2643 #[inline]
2644 fn next(&mut self) -> Option<V> {
2645 self.inner.next().map(|(_, v)| v)
2646 }
2647 #[inline]
2648 fn size_hint(&self) -> (usize, Option<usize>) {
2649 self.inner.size_hint()
2650 }
2651}
2652
2653impl<K, V, A: Allocator> ExactSizeIterator for IntoValues<K, V, A> {
2654 #[inline]
2655 fn len(&self) -> usize {
2656 self.inner.len()
2657 }
2658}
2659
2660impl<K, V, A: Allocator> FusedIterator for IntoValues<K, V, A> {}
2661
2662impl<K, V: Debug, A: Allocator> fmt::Debug for IntoValues<K, V, A> {
2663 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2664 f.debug_list()
2665 .entries(self.inner.iter().map(|(_, v)| v))
2666 .finish()
2667 }
2668}
2669
2670/// An iterator over the keys of a `HashMap` in arbitrary order.
2671/// The iterator element type is `&'a K`.
2672///
2673/// This `struct` is created by the [`keys`] method on [`HashMap`]. See its
2674/// documentation for more.
2675///
2676/// [`keys`]: struct.HashMap.html#method.keys
2677/// [`HashMap`]: struct.HashMap.html
2678///
2679/// # Examples
2680///
2681/// ```
2682/// use rune::alloc::HashMap;
2683///
2684/// let map: HashMap<_, _> = [(1, "a"), (2, "b"), (3, "c")].try_into()?;
2685///
2686/// let mut keys = map.keys();
2687/// let mut vec = vec![keys.next(), keys.next(), keys.next()];
2688///
2689/// // The `Keys` iterator produces keys in arbitrary order, so the
2690/// // keys must be sorted to test them against a sorted array.
2691/// vec.sort_unstable();
2692/// assert_eq!(vec, [Some(&1), Some(&2), Some(&3)]);
2693///
2694/// // It is fused iterator
2695/// assert_eq!(keys.next(), None);
2696/// assert_eq!(keys.next(), None);
2697/// # Ok::<_, rune::alloc::Error>(())
2698/// ```
2699pub struct Keys<'a, K, V> {
2700 inner: Iter<'a, K, V>,
2701}
2702
2703// FIXME(#26925) Remove in favor of `#[derive(Clone)]`
2704impl<K, V> Clone for Keys<'_, K, V> {
2705 #[cfg_attr(feature = "inline-more", inline)]
2706 fn clone(&self) -> Self {
2707 Keys {
2708 inner: self.inner.clone(),
2709 }
2710 }
2711}
2712
2713impl<K: Debug, V> fmt::Debug for Keys<'_, K, V> {
2714 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2715 f.debug_list().entries(self.clone()).finish()
2716 }
2717}
2718
2719/// An iterator over the values of a `HashMap` in arbitrary order.
2720/// The iterator element type is `&'a V`.
2721///
2722/// This `struct` is created by the [`values`] method on [`HashMap`]. See its
2723/// documentation for more.
2724///
2725/// [`values`]: struct.HashMap.html#method.values
2726/// [`HashMap`]: struct.HashMap.html
2727///
2728/// # Examples
2729///
2730/// ```
2731/// use rune::alloc::HashMap;
2732///
2733/// let map: HashMap<_, _> = [(1, "a"), (2, "b"), (3, "c")].try_into()?;
2734///
2735/// let mut values = map.values();
2736/// let mut vec = vec![values.next(), values.next(), values.next()];
2737///
2738/// // The `Values` iterator produces values in arbitrary order, so the
2739/// // values must be sorted to test them against a sorted array.
2740/// vec.sort_unstable();
2741/// assert_eq!(vec, [Some(&"a"), Some(&"b"), Some(&"c")]);
2742///
2743/// // It is fused iterator
2744/// assert_eq!(values.next(), None);
2745/// assert_eq!(values.next(), None);
2746/// # Ok::<_, rune::alloc::Error>(())
2747/// ```
2748pub struct Values<'a, K, V> {
2749 inner: Iter<'a, K, V>,
2750}
2751
2752// FIXME(#26925) Remove in favor of `#[derive(Clone)]`
2753impl<K, V> Clone for Values<'_, K, V> {
2754 #[cfg_attr(feature = "inline-more", inline)]
2755 fn clone(&self) -> Self {
2756 Values {
2757 inner: self.inner.clone(),
2758 }
2759 }
2760}
2761
2762impl<K, V: Debug> fmt::Debug for Values<'_, K, V> {
2763 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2764 f.debug_list().entries(self.clone()).finish()
2765 }
2766}
2767
2768/// A draining iterator over the entries of a `HashMap` in arbitrary
2769/// order. The iterator element type is `(K, V)`.
2770///
2771/// This `struct` is created by the [`drain`] method on [`HashMap`]. See its
2772/// documentation for more.
2773///
2774/// [`drain`]: struct.HashMap.html#method.drain
2775/// [`HashMap`]: struct.HashMap.html
2776///
2777/// # Examples
2778///
2779/// ```
2780/// use rune::alloc::HashMap;
2781///
2782/// let mut map: HashMap<_, _> = [(1, "a"), (2, "b"), (3, "c")].try_into()?;
2783///
2784/// let mut drain_iter = map.drain();
2785/// let mut vec = vec![drain_iter.next(), drain_iter.next(), drain_iter.next()];
2786///
2787/// // The `Drain` iterator produces items in arbitrary order, so the
2788/// // items must be sorted to test them against a sorted array.
2789/// vec.sort_unstable();
2790/// assert_eq!(vec, [Some((1, "a")), Some((2, "b")), Some((3, "c"))]);
2791///
2792/// // It is fused iterator
2793/// assert_eq!(drain_iter.next(), None);
2794/// assert_eq!(drain_iter.next(), None);
2795/// # Ok::<_, rune::alloc::Error>(())
2796/// ```
2797pub struct Drain<'a, K, V, A: Allocator = Global> {
2798 inner: RawDrain<'a, (K, V), A>,
2799}
2800
2801impl<K, V, A: Allocator> Drain<'_, K, V, A> {
2802 /// Returns a iterator of references over the remaining items.
2803 #[cfg_attr(feature = "inline-more", inline)]
2804 pub(super) fn iter(&self) -> Iter<'_, K, V> {
2805 Iter {
2806 inner: self.inner.iter(),
2807 marker: PhantomData,
2808 }
2809 }
2810}
2811
2812/// A draining iterator over entries of a `HashMap` which don't satisfy the predicate
2813/// `f(&k, &mut v)` in arbitrary order. The iterator element type is `(K, V)`.
2814///
2815/// This `struct` is created by the [`extract_if`] method on [`HashMap`]. See its
2816/// documentation for more.
2817///
2818/// [`extract_if`]: struct.HashMap.html#method.extract_if
2819/// [`HashMap`]: struct.HashMap.html
2820///
2821/// # Examples
2822///
2823/// ```
2824/// use rune::alloc::HashMap;
2825///
2826/// let mut map: HashMap<i32, &str> = [(1, "a"), (2, "b"), (3, "c")].try_into()?;
2827///
2828/// let mut extract_if = map.extract_if(|k, _v| k % 2 != 0);
2829/// let mut vec = vec![extract_if.next(), extract_if.next()];
2830///
2831/// // The `ExtractIf` iterator produces items in arbitrary order, so the
2832/// // items must be sorted to test them against a sorted array.
2833/// vec.sort_unstable();
2834/// assert_eq!(vec, [Some((1, "a")),Some((3, "c"))]);
2835///
2836/// // It is fused iterator
2837/// assert_eq!(extract_if.next(), None);
2838/// assert_eq!(extract_if.next(), None);
2839/// drop(extract_if);
2840///
2841/// assert_eq!(map.len(), 1);
2842/// # Ok::<_, rune::alloc::Error>(())
2843/// ```
2844#[must_use = "Iterators are lazy unless consumed"]
2845pub struct ExtractIf<'a, K, V, F, A: Allocator = Global>
2846where
2847 F: FnMut(&K, &mut V) -> bool,
2848{
2849 f: F,
2850 inner: ExtractIfInner<'a, K, V, A>,
2851}
2852
2853impl<K, V, F, A> Iterator for ExtractIf<'_, K, V, F, A>
2854where
2855 F: FnMut(&K, &mut V) -> bool,
2856 A: Allocator,
2857{
2858 type Item = (K, V);
2859
2860 #[cfg_attr(feature = "inline-more", inline)]
2861 fn next(&mut self) -> Option<Self::Item> {
2862 self.inner.next(&mut self.f)
2863 }
2864
2865 #[inline]
2866 fn size_hint(&self) -> (usize, Option<usize>) {
2867 (0, self.inner.iter.size_hint().1)
2868 }
2869}
2870
2871impl<K, V, F> FusedIterator for ExtractIf<'_, K, V, F> where F: FnMut(&K, &mut V) -> bool {}
2872
2873/// Portions of `ExtractIf` shared with `set::ExtractIf`
2874pub(super) struct ExtractIfInner<'a, K, V, A: Allocator> {
2875 pub iter: RawIter<(K, V)>,
2876 pub table: &'a mut RawTable<(K, V), A>,
2877}
2878
2879impl<K, V, A: Allocator> ExtractIfInner<'_, K, V, A> {
2880 #[cfg_attr(feature = "inline-more", inline)]
2881 pub(super) fn next<F>(&mut self, f: &mut F) -> Option<(K, V)>
2882 where
2883 F: FnMut(&K, &mut V) -> bool,
2884 {
2885 unsafe {
2886 for item in &mut self.iter {
2887 let &mut (ref key, ref mut value) = item.as_mut();
2888 if f(key, value) {
2889 return Some(self.table.remove(item).0);
2890 }
2891 }
2892 }
2893 None
2894 }
2895}
2896
2897/// A mutable iterator over the values of a `HashMap` in arbitrary order.
2898/// The iterator element type is `&'a mut V`.
2899///
2900/// This `struct` is created by the [`values_mut`] method on [`HashMap`]. See its
2901/// documentation for more.
2902///
2903/// [`values_mut`]: struct.HashMap.html#method.values_mut
2904/// [`HashMap`]: struct.HashMap.html
2905///
2906/// # Examples
2907///
2908/// ```
2909/// use rune::alloc::HashMap;
2910///
2911/// let mut map: HashMap<_, _> = [(1, "One".to_owned()), (2, "Two".into())].try_into()?;
2912///
2913/// let mut values = map.values_mut();
2914/// values.next().map(|v| v.push_str(" Mississippi"));
2915/// values.next().map(|v| v.push_str(" Mississippi"));
2916///
2917/// // It is fused iterator
2918/// assert_eq!(values.next(), None);
2919/// assert_eq!(values.next(), None);
2920///
2921/// assert_eq!(map.get(&1).unwrap(), &"One Mississippi".to_owned());
2922/// assert_eq!(map.get(&2).unwrap(), &"Two Mississippi".to_owned());
2923/// # Ok::<_, rune::alloc::Error>(())
2924/// ```
2925pub struct ValuesMut<'a, K, V> {
2926 inner: IterMut<'a, K, V>,
2927}
2928
2929/// A builder for computing where in a [`HashMap`] a key-value pair would be stored.
2930///
2931/// See the [`HashMap::raw_entry_mut`] docs for usage examples.
2932///
2933/// [`HashMap::raw_entry_mut`]: struct.HashMap.html#method.raw_entry_mut
2934///
2935/// # Examples
2936///
2937/// ```
2938/// use core::hash::{BuildHasher, Hash};
2939/// use rune::alloc::hash_map::{RawEntryBuilderMut, RawEntryMut::Vacant, RawEntryMut::Occupied};
2940/// use rune::alloc::HashMap;
2941/// use rune::alloc::prelude::*;
2942///
2943/// let mut map = HashMap::new();
2944/// map.try_extend([(1, 11), (2, 12), (3, 13), (4, 14), (5, 15), (6, 16)])?;
2945/// assert_eq!(map.len(), 6);
2946///
2947/// fn compute_hash<K: Hash + ?Sized, S: BuildHasher>(hash_builder: &S, key: &K) -> u64 {
2948/// use core::hash::Hasher;
2949/// let mut state = hash_builder.build_hasher();
2950/// key.hash(&mut state);
2951/// state.finish()
2952/// }
2953///
2954/// let builder: RawEntryBuilderMut<_, _, _> = map.raw_entry_mut();
2955///
2956/// // Existing key
2957/// match builder.from_key(&6) {
2958/// Vacant(_) => unreachable!(),
2959/// Occupied(view) => assert_eq!(view.get(), &16),
2960/// }
2961///
2962/// for key in 0..12 {
2963/// let hash = compute_hash(map.hasher(), &key);
2964/// let value = map.get(&key).cloned();
2965/// let key_value = value.as_ref().map(|v| (&key, v));
2966///
2967/// println!("Key: {} and value: {:?}", key, value);
2968///
2969/// match map.raw_entry_mut().from_key(&key) {
2970/// Occupied(mut o) => assert_eq!(Some(o.get_key_value()), key_value),
2971/// Vacant(_) => assert_eq!(value, None),
2972/// }
2973/// match map.raw_entry_mut().from_key_hashed_nocheck(hash, &key) {
2974/// Occupied(mut o) => assert_eq!(Some(o.get_key_value()), key_value),
2975/// Vacant(_) => assert_eq!(value, None),
2976/// }
2977/// match map.raw_entry_mut().from_hash(hash, |q| *q == key) {
2978/// Occupied(mut o) => assert_eq!(Some(o.get_key_value()), key_value),
2979/// Vacant(_) => assert_eq!(value, None),
2980/// }
2981/// }
2982///
2983/// assert_eq!(map.len(), 6);
2984/// # Ok::<_, rune::alloc::Error>(())
2985/// ```
2986pub struct RawEntryBuilderMut<'a, K, V, S, A: Allocator = Global> {
2987 map: &'a mut HashMap<K, V, S, A>,
2988}
2989
2990/// A view into a single entry in a map, which may either be vacant or occupied.
2991///
2992/// This is a lower-level version of [`Entry`].
2993///
2994/// This `enum` is constructed through the [`raw_entry_mut`] method on [`HashMap`],
2995/// then calling one of the methods of that [`RawEntryBuilderMut`].
2996///
2997/// [`HashMap`]: struct.HashMap.html
2998/// [`Entry`]: enum.Entry.html
2999/// [`raw_entry_mut`]: struct.HashMap.html#method.raw_entry_mut
3000/// [`RawEntryBuilderMut`]: struct.RawEntryBuilderMut.html
3001///
3002/// # Examples
3003///
3004/// ```
3005/// use core::hash::{BuildHasher, Hash};
3006/// use rune::alloc::hash_map::{HashMap, RawEntryMut, RawOccupiedEntryMut};
3007/// use rune::alloc::prelude::*;
3008///
3009/// let mut map = HashMap::new();
3010/// map.try_extend([('a', 1), ('b', 2), ('c', 3)])?;
3011/// assert_eq!(map.len(), 3);
3012///
3013/// fn compute_hash<K: Hash + ?Sized, S: BuildHasher>(hash_builder: &S, key: &K) -> u64 {
3014/// use core::hash::Hasher;
3015/// let mut state = hash_builder.build_hasher();
3016/// key.hash(&mut state);
3017/// state.finish()
3018/// }
3019///
3020/// // Existing key (try_insert)
3021/// let raw: RawEntryMut<_, _, _> = map.raw_entry_mut().from_key(&'a');
3022/// let _raw_o: RawOccupiedEntryMut<_, _, _> = raw.try_insert('a', 10)?;
3023/// assert_eq!(map.len(), 3);
3024///
3025/// // Nonexistent key (try_insert)
3026/// map.raw_entry_mut().from_key(&'d').try_insert('d', 40)?;
3027/// assert_eq!(map.len(), 4);
3028///
3029/// // Existing key (or_try_insert)
3030/// let hash = compute_hash(map.hasher(), &'b');
3031/// let kv = map
3032/// .raw_entry_mut()
3033/// .from_key_hashed_nocheck(hash, &'b')
3034/// .or_try_insert('b', 20)?;
3035/// assert_eq!(kv, (&mut 'b', &mut 2));
3036/// *kv.1 = 20;
3037/// assert_eq!(map.len(), 4);
3038///
3039/// // Nonexistent key (or_try_insert)
3040/// let hash = compute_hash(map.hasher(), &'e');
3041/// let kv = map
3042/// .raw_entry_mut()
3043/// .from_key_hashed_nocheck(hash, &'e')
3044/// .or_try_insert('e', 50)?;
3045/// assert_eq!(kv, (&mut 'e', &mut 50));
3046/// assert_eq!(map.len(), 5);
3047///
3048/// // Existing key (or_try_insert_with)
3049/// let hash = compute_hash(map.hasher(), &'c');
3050/// let kv = map
3051/// .raw_entry_mut()
3052/// .from_hash(hash, |q| q == &'c')
3053/// .or_try_insert_with(|| ('c', 30))?;
3054/// assert_eq!(kv, (&mut 'c', &mut 3));
3055/// *kv.1 = 30;
3056/// assert_eq!(map.len(), 5);
3057///
3058/// // Nonexistent key (or_try_insert_with)
3059/// let hash = compute_hash(map.hasher(), &'f');
3060/// let kv = map
3061/// .raw_entry_mut()
3062/// .from_hash(hash, |q| q == &'f')
3063/// .or_try_insert_with(|| ('f', 60))?;
3064/// assert_eq!(kv, (&mut 'f', &mut 60));
3065/// assert_eq!(map.len(), 6);
3066///
3067/// println!("Our HashMap: {:?}", map);
3068///
3069/// let mut vec: Vec<_> = map.iter().map(|(&k, &v)| (k, v)).collect();
3070/// // The `Iter` iterator produces items in arbitrary order, so the
3071/// // items must be sorted to test them against a sorted array.
3072/// vec.sort_unstable();
3073/// assert_eq!(vec, [('a', 10), ('b', 20), ('c', 30), ('d', 40), ('e', 50), ('f', 60)]);
3074/// # Ok::<_, rune::alloc::Error>(())
3075/// ```
3076pub enum RawEntryMut<'a, K, V, S, A: Allocator = Global> {
3077 /// An occupied entry.
3078 ///
3079 /// # Examples
3080 ///
3081 /// ```
3082 /// use rune::alloc::hash_map::RawEntryMut;
3083 /// use rune::alloc::HashMap;
3084 ///
3085 /// let mut map: HashMap<_, _> = [("a", 100), ("b", 200)].try_into()?;
3086 ///
3087 /// match map.raw_entry_mut().from_key(&"a") {
3088 /// RawEntryMut::Vacant(_) => unreachable!(),
3089 /// RawEntryMut::Occupied(_) => { }
3090 /// }
3091 /// # Ok::<_, rune::alloc::Error>(())
3092 /// ```
3093 Occupied(RawOccupiedEntryMut<'a, K, V, S, A>),
3094 /// A vacant entry.
3095 ///
3096 /// # Examples
3097 ///
3098 /// ```
3099 /// use rune::alloc::{hash_map::RawEntryMut, HashMap};
3100 /// let mut map: HashMap<&str, i32> = HashMap::new();
3101 ///
3102 /// match map.raw_entry_mut().from_key("a") {
3103 /// RawEntryMut::Occupied(_) => unreachable!(),
3104 /// RawEntryMut::Vacant(_) => { }
3105 /// }
3106 /// ```
3107 Vacant(RawVacantEntryMut<'a, K, V, S, A>),
3108}
3109
3110/// A view into an occupied entry in a `HashMap`.
3111/// It is part of the [`RawEntryMut`] enum.
3112///
3113/// [`RawEntryMut`]: enum.RawEntryMut.html
3114///
3115/// # Examples
3116///
3117/// ```
3118/// use core::hash::{BuildHasher, Hash};
3119/// use rune::alloc::hash_map::{RawEntryMut, RawOccupiedEntryMut};
3120/// use rune::alloc::HashMap;
3121/// use rune::alloc::prelude::*;
3122///
3123/// let mut map = HashMap::new();
3124/// map.try_extend([("a", 10), ("b", 20), ("c", 30)])?;
3125///
3126/// fn compute_hash<K: Hash + ?Sized, S: BuildHasher>(hash_builder: &S, key: &K) -> u64 {
3127/// use core::hash::Hasher;
3128/// let mut state = hash_builder.build_hasher();
3129/// key.hash(&mut state);
3130/// state.finish()
3131/// }
3132///
3133/// let _raw_o: RawOccupiedEntryMut<_, _, _> = map.raw_entry_mut().from_key(&"a").try_insert("a", 100)?;
3134/// assert_eq!(map.len(), 3);
3135///
3136/// // Existing key (insert and update)
3137/// match map.raw_entry_mut().from_key(&"a") {
3138/// RawEntryMut::Vacant(_) => unreachable!(),
3139/// RawEntryMut::Occupied(mut view) => {
3140/// assert_eq!(view.get(), &100);
3141/// let v = view.get_mut();
3142/// let new_v = (*v) * 10;
3143/// *v = new_v;
3144/// assert_eq!(view.insert(1111), 1000);
3145/// }
3146/// }
3147///
3148/// assert_eq!(map[&"a"], 1111);
3149/// assert_eq!(map.len(), 3);
3150///
3151/// // Existing key (take)
3152/// let hash = compute_hash(map.hasher(), &"c");
3153/// match map.raw_entry_mut().from_key_hashed_nocheck(hash, &"c") {
3154/// RawEntryMut::Vacant(_) => unreachable!(),
3155/// RawEntryMut::Occupied(view) => {
3156/// assert_eq!(view.remove_entry(), ("c", 30));
3157/// }
3158/// }
3159/// assert_eq!(map.raw_entry().from_key(&"c"), None);
3160/// assert_eq!(map.len(), 2);
3161///
3162/// let hash = compute_hash(map.hasher(), &"b");
3163/// match map.raw_entry_mut().from_hash(hash, |q| *q == "b") {
3164/// RawEntryMut::Vacant(_) => unreachable!(),
3165/// RawEntryMut::Occupied(view) => {
3166/// assert_eq!(view.remove_entry(), ("b", 20));
3167/// }
3168/// }
3169/// assert_eq!(map.get(&"b"), None);
3170/// assert_eq!(map.len(), 1);
3171/// # Ok::<_, rune::alloc::Error>(())
3172/// ```
3173pub struct RawOccupiedEntryMut<'a, K, V, S, A: Allocator = Global> {
3174 elem: Bucket<(K, V)>,
3175 table: &'a mut RawTable<(K, V), A>,
3176 hash_builder: &'a S,
3177}
3178
3179unsafe impl<K, V, S, A> Send for RawOccupiedEntryMut<'_, K, V, S, A>
3180where
3181 K: Send,
3182 V: Send,
3183 S: Send,
3184 A: Send + Allocator,
3185{
3186}
3187unsafe impl<K, V, S, A> Sync for RawOccupiedEntryMut<'_, K, V, S, A>
3188where
3189 K: Sync,
3190 V: Sync,
3191 S: Sync,
3192 A: Sync + Allocator,
3193{
3194}
3195
3196/// A view into a vacant entry in a `HashMap`.
3197/// It is part of the [`RawEntryMut`] enum.
3198///
3199/// [`RawEntryMut`]: enum.RawEntryMut.html
3200///
3201/// # Examples
3202///
3203/// ```
3204/// use core::hash::{BuildHasher, Hash};
3205/// use rune::alloc::hash_map::{RawEntryMut, RawVacantEntryMut};
3206/// use rune::alloc::HashMap;
3207///
3208/// let mut map = HashMap::<&str, i32>::new();
3209///
3210/// fn compute_hash<K: Hash + ?Sized, S: BuildHasher>(hash_builder: &S, key: &K) -> u64 {
3211/// use core::hash::Hasher;
3212/// let mut state = hash_builder.build_hasher();
3213/// key.hash(&mut state);
3214/// state.finish()
3215/// }
3216///
3217/// let raw_v: RawVacantEntryMut<_, _, _> = match map.raw_entry_mut().from_key(&"a") {
3218/// RawEntryMut::Vacant(view) => view,
3219/// RawEntryMut::Occupied(_) => unreachable!(),
3220/// };
3221/// raw_v.try_insert("a", 10)?;
3222/// assert!(map[&"a"] == 10 && map.len() == 1);
3223///
3224/// // Nonexistent key (insert and update)
3225/// let hash = compute_hash(map.hasher(), &"b");
3226/// match map.raw_entry_mut().from_key_hashed_nocheck(hash, &"b") {
3227/// RawEntryMut::Occupied(_) => unreachable!(),
3228/// RawEntryMut::Vacant(view) => {
3229/// let (k, value) = view.try_insert("b", 2)?;
3230/// assert_eq!((*k, *value), ("b", 2));
3231/// *value = 20;
3232/// }
3233/// }
3234/// assert!(map[&"b"] == 20 && map.len() == 2);
3235///
3236/// let hash = compute_hash(map.hasher(), &"c");
3237/// match map.raw_entry_mut().from_hash(hash, |q| *q == "c") {
3238/// RawEntryMut::Occupied(_) => unreachable!(),
3239/// RawEntryMut::Vacant(view) => {
3240/// assert_eq!(view.try_insert("c", 30)?, (&mut "c", &mut 30));
3241/// }
3242/// }
3243/// assert!(map[&"c"] == 30 && map.len() == 3);
3244/// # Ok::<_, rune::alloc::Error>(())
3245/// ```
3246pub struct RawVacantEntryMut<'a, K, V, S, A: Allocator = Global> {
3247 table: &'a mut RawTable<(K, V), A>,
3248 hash_builder: &'a S,
3249}
3250
3251/// A builder for computing where in a [`HashMap`] a key-value pair would be stored.
3252///
3253/// See the [`HashMap::raw_entry`] docs for usage examples.
3254///
3255/// [`HashMap::raw_entry`]: struct.HashMap.html#method.raw_entry
3256///
3257/// # Examples
3258///
3259/// ```
3260/// use core::hash::{BuildHasher, Hash};
3261/// use rune::alloc::hash_map::RawEntryBuilder;
3262/// use rune::alloc::HashMap;
3263/// use rune::alloc::prelude::*;
3264///
3265/// let mut map = HashMap::new();
3266/// map.try_extend([(1, 10), (2, 20), (3, 30)])?;
3267///
3268/// fn compute_hash<K: Hash + ?Sized, S: BuildHasher>(hash_builder: &S, key: &K) -> u64 {
3269/// use core::hash::Hasher;
3270/// let mut state = hash_builder.build_hasher();
3271/// key.hash(&mut state);
3272/// state.finish()
3273/// }
3274///
3275/// for k in 0..6 {
3276/// let hash = compute_hash(map.hasher(), &k);
3277/// let v = map.get(&k).cloned();
3278/// let kv = v.as_ref().map(|v| (&k, v));
3279///
3280/// println!("Key: {} and value: {:?}", k, v);
3281/// let builder: RawEntryBuilder<_, _, _> = map.raw_entry();
3282/// assert_eq!(builder.from_key(&k), kv);
3283/// assert_eq!(map.raw_entry().from_hash(hash, |q| *q == k), kv);
3284/// assert_eq!(map.raw_entry().from_key_hashed_nocheck(hash, &k), kv);
3285/// }
3286/// # Ok::<_, rune::alloc::Error>(())
3287/// ```
3288pub struct RawEntryBuilder<'a, K, V, S, A: Allocator = Global> {
3289 map: &'a HashMap<K, V, S, A>,
3290}
3291
3292impl<'a, K, V, S, A: Allocator> RawEntryBuilderMut<'a, K, V, S, A> {
3293 /// Creates a `RawEntryMut` from the given key.
3294 ///
3295 /// # Examples
3296 ///
3297 /// ```
3298 /// use rune::alloc::hash_map::RawEntryMut;
3299 /// use rune::alloc::HashMap;
3300 ///
3301 /// let mut map: HashMap<&str, u32> = HashMap::new();
3302 /// let key = "a";
3303 /// let entry: RawEntryMut<&str, u32, _> = map.raw_entry_mut().from_key(&key);
3304 /// entry.try_insert(key, 100)?;
3305 /// assert_eq!(map[&"a"], 100);
3306 /// # Ok::<_, rune::alloc::Error>(())
3307 /// ```
3308 #[cfg_attr(feature = "inline-more", inline)]
3309 #[allow(clippy::wrong_self_convention)]
3310 pub fn from_key<Q: ?Sized>(self, k: &Q) -> RawEntryMut<'a, K, V, S, A>
3311 where
3312 S: BuildHasher,
3313 Q: Hash + Equivalent<K>,
3314 {
3315 let hash = make_hash::<Q, S>(&self.map.hash_builder, k);
3316 self.from_key_hashed_nocheck(hash, k)
3317 }
3318
3319 /// Creates a `RawEntryMut` from the given key and its hash.
3320 ///
3321 /// # Examples
3322 ///
3323 /// ```
3324 /// use core::hash::{BuildHasher, Hash};
3325 /// use rune::alloc::hash_map::{HashMap, RawEntryMut};
3326 ///
3327 /// fn compute_hash<K: Hash + ?Sized, S: BuildHasher>(hash_builder: &S, key: &K) -> u64 {
3328 /// use core::hash::Hasher;
3329 /// let mut state = hash_builder.build_hasher();
3330 /// key.hash(&mut state);
3331 /// state.finish()
3332 /// }
3333 ///
3334 /// let mut map: HashMap<&str, u32> = HashMap::new();
3335 /// let key = "a";
3336 /// let hash = compute_hash(map.hasher(), &key);
3337 /// let entry: RawEntryMut<&str, u32, _> = map.raw_entry_mut().from_key_hashed_nocheck(hash, &key);
3338 /// entry.try_insert(key, 100)?;
3339 /// assert_eq!(map[&"a"], 100);
3340 /// # Ok::<_, rune::alloc::Error>(())
3341 /// ```
3342 #[inline]
3343 #[allow(clippy::wrong_self_convention)]
3344 pub fn from_key_hashed_nocheck<Q: ?Sized>(self, hash: u64, k: &Q) -> RawEntryMut<'a, K, V, S, A>
3345 where
3346 Q: Equivalent<K>,
3347 {
3348 self.from_hash(hash, equivalent(k))
3349 }
3350}
3351
3352impl<'a, K, V, S, A: Allocator> RawEntryBuilderMut<'a, K, V, S, A> {
3353 /// Creates a `RawEntryMut` from the given hash and matching function.
3354 ///
3355 /// # Examples
3356 ///
3357 /// ```
3358 /// use core::hash::{BuildHasher, Hash};
3359 /// use rune::alloc::hash_map::{HashMap, RawEntryMut};
3360 ///
3361 /// fn compute_hash<K: Hash + ?Sized, S: BuildHasher>(hash_builder: &S, key: &K) -> u64 {
3362 /// use core::hash::Hasher;
3363 /// let mut state = hash_builder.build_hasher();
3364 /// key.hash(&mut state);
3365 /// state.finish()
3366 /// }
3367 ///
3368 /// let mut map: HashMap<&str, u32> = HashMap::new();
3369 /// let key = "a";
3370 /// let hash = compute_hash(map.hasher(), &key);
3371 /// let entry: RawEntryMut<&str, u32, _> = map.raw_entry_mut().from_hash(hash, |k| k == &key);
3372 /// entry.try_insert(key, 100)?;
3373 /// assert_eq!(map[&"a"], 100);
3374 /// # Ok::<_, rune::alloc::Error>(())
3375 /// ```
3376 #[cfg_attr(feature = "inline-more", inline)]
3377 #[allow(clippy::wrong_self_convention)]
3378 pub fn from_hash<F>(self, hash: u64, is_match: F) -> RawEntryMut<'a, K, V, S, A>
3379 where
3380 F: FnMut(&K) -> bool,
3381 {
3382 self.search(hash, is_match)
3383 }
3384
3385 #[cfg_attr(feature = "inline-more", inline)]
3386 fn search<F>(self, hash: u64, mut is_match: F) -> RawEntryMut<'a, K, V, S, A>
3387 where
3388 F: FnMut(&K) -> bool,
3389 {
3390 match into_ok(self.map.table.find(
3391 &mut is_match,
3392 hash,
3393 move |is_match: &mut F, (k, _): &(K, _)| Ok(is_match(k)),
3394 )) {
3395 Some(elem) => RawEntryMut::Occupied(RawOccupiedEntryMut {
3396 elem,
3397 table: &mut self.map.table,
3398 hash_builder: &self.map.hash_builder,
3399 }),
3400 None => RawEntryMut::Vacant(RawVacantEntryMut {
3401 table: &mut self.map.table,
3402 hash_builder: &self.map.hash_builder,
3403 }),
3404 }
3405 }
3406}
3407
3408impl<'a, K, V, S, A: Allocator> RawEntryBuilder<'a, K, V, S, A> {
3409 /// Access an immutable entry by key.
3410 ///
3411 /// # Examples
3412 ///
3413 /// ```
3414 /// use rune::alloc::HashMap;
3415 ///
3416 /// let map: HashMap<&str, u32> = [("a", 100), ("b", 200)].try_into()?;
3417 /// let key = "a";
3418 /// assert_eq!(map.raw_entry().from_key(&key), Some((&"a", &100)));
3419 /// # Ok::<_, rune::alloc::Error>(())
3420 /// ```
3421 #[cfg_attr(feature = "inline-more", inline)]
3422 #[allow(clippy::wrong_self_convention)]
3423 pub fn from_key<Q: ?Sized>(self, k: &Q) -> Option<(&'a K, &'a V)>
3424 where
3425 S: BuildHasher,
3426 Q: Hash + Equivalent<K>,
3427 {
3428 let hash = make_hash::<Q, S>(&self.map.hash_builder, k);
3429 self.from_key_hashed_nocheck(hash, k)
3430 }
3431
3432 /// Access an immutable entry by a key and its hash.
3433 ///
3434 /// # Examples
3435 ///
3436 /// ```
3437 /// use core::hash::{BuildHasher, Hash};
3438 /// use rune::alloc::HashMap;
3439 ///
3440 /// fn compute_hash<K: Hash + ?Sized, S: BuildHasher>(hash_builder: &S, key: &K) -> u64 {
3441 /// use core::hash::Hasher;
3442 /// let mut state = hash_builder.build_hasher();
3443 /// key.hash(&mut state);
3444 /// state.finish()
3445 /// }
3446 ///
3447 /// let map: HashMap<&str, u32> = [("a", 100), ("b", 200)].try_into()?;
3448 /// let key = "a";
3449 /// let hash = compute_hash(map.hasher(), &key);
3450 /// assert_eq!(map.raw_entry().from_key_hashed_nocheck(hash, &key), Some((&"a", &100)));
3451 /// # Ok::<_, rune::alloc::Error>(())
3452 /// ```
3453 #[cfg_attr(feature = "inline-more", inline)]
3454 #[allow(clippy::wrong_self_convention)]
3455 pub fn from_key_hashed_nocheck<Q: ?Sized>(self, hash: u64, k: &Q) -> Option<(&'a K, &'a V)>
3456 where
3457 Q: Equivalent<K>,
3458 {
3459 self.from_hash(hash, equivalent(k))
3460 }
3461
3462 #[cfg_attr(feature = "inline-more", inline)]
3463 fn search<F>(self, hash: u64, mut is_match: F) -> Option<(&'a K, &'a V)>
3464 where
3465 F: FnMut(&K) -> bool,
3466 {
3467 match into_ok(self.map.table.get(
3468 &mut is_match,
3469 hash,
3470 |is_match: &mut F, (k, _): &(K, _)| Ok(is_match(k)),
3471 )) {
3472 Some((key, value)) => Some((key, value)),
3473 None => None,
3474 }
3475 }
3476
3477 /// Access an immutable entry by hash and matching function.
3478 ///
3479 /// # Examples
3480 ///
3481 /// ```
3482 /// use core::hash::{BuildHasher, Hash};
3483 /// use rune::alloc::HashMap;
3484 ///
3485 /// fn compute_hash<K: Hash + ?Sized, S: BuildHasher>(hash_builder: &S, key: &K) -> u64 {
3486 /// use core::hash::Hasher;
3487 /// let mut state = hash_builder.build_hasher();
3488 /// key.hash(&mut state);
3489 /// state.finish()
3490 /// }
3491 ///
3492 /// let map: HashMap<&str, u32> = [("a", 100), ("b", 200)].try_into()?;
3493 /// let key = "a";
3494 /// let hash = compute_hash(map.hasher(), &key);
3495 /// assert_eq!(map.raw_entry().from_hash(hash, |k| k == &key), Some((&"a", &100)));
3496 /// # Ok::<_, rune::alloc::Error>(())
3497 /// ```
3498 #[cfg_attr(feature = "inline-more", inline)]
3499 #[allow(clippy::wrong_self_convention)]
3500 pub fn from_hash<F>(self, hash: u64, is_match: F) -> Option<(&'a K, &'a V)>
3501 where
3502 F: FnMut(&K) -> bool,
3503 {
3504 self.search(hash, is_match)
3505 }
3506}
3507
3508impl<'a, K, V, S, A: Allocator> RawEntryMut<'a, K, V, S, A> {
3509 /// Sets the value of the entry, and returns a RawOccupiedEntryMut.
3510 ///
3511 /// # Examples
3512 ///
3513 /// ```
3514 /// use rune::alloc::HashMap;
3515 ///
3516 /// let mut map: HashMap<&str, u32> = HashMap::new();
3517 /// let entry = map.raw_entry_mut().from_key("horseyland").try_insert("horseyland", 37)?;
3518 ///
3519 /// assert_eq!(entry.remove_entry(), ("horseyland", 37));
3520 /// # Ok::<_, rune::alloc::Error>(())
3521 /// ```
3522 #[cfg_attr(feature = "inline-more", inline)]
3523 pub fn try_insert(self, key: K, value: V) -> Result<RawOccupiedEntryMut<'a, K, V, S, A>, Error>
3524 where
3525 K: Hash,
3526 S: BuildHasher,
3527 {
3528 match self {
3529 RawEntryMut::Occupied(mut entry) => {
3530 entry.insert(value);
3531 Ok(entry)
3532 }
3533 RawEntryMut::Vacant(entry) => {
3534 let hasher = make_hasher::<K, S>(entry.hash_builder);
3535 into_ok_try(entry.insert_entry(&mut (), hasher, key, value))
3536 }
3537 }
3538 }
3539
3540 #[cfg(test)]
3541 pub(crate) fn insert(self, key: K, value: V) -> RawOccupiedEntryMut<'a, K, V, S, A>
3542 where
3543 K: Hash,
3544 S: BuildHasher,
3545 {
3546 self.try_insert(key, value).abort()
3547 }
3548
3549 /// Ensures a value is in the entry by inserting the default if empty, and returns
3550 /// mutable references to the key and value in the entry.
3551 ///
3552 /// # Examples
3553 ///
3554 /// ```
3555 /// use rune::alloc::HashMap;
3556 ///
3557 /// let mut map: HashMap<&str, u32> = HashMap::new();
3558 ///
3559 /// map.raw_entry_mut().from_key("poneyland").or_try_insert("poneyland", 3)?;
3560 /// assert_eq!(map["poneyland"], 3);
3561 ///
3562 /// *map.raw_entry_mut().from_key("poneyland").or_try_insert("poneyland", 10)?.1 *= 2;
3563 /// assert_eq!(map["poneyland"], 6);
3564 /// # Ok::<_, rune::alloc::Error>(())
3565 /// ```
3566 #[cfg_attr(feature = "inline-more", inline)]
3567 pub fn or_try_insert(
3568 self,
3569 default_key: K,
3570 default_val: V,
3571 ) -> Result<(&'a mut K, &'a mut V), Error>
3572 where
3573 K: Hash,
3574 S: BuildHasher,
3575 {
3576 match self {
3577 RawEntryMut::Occupied(entry) => Ok(entry.into_key_value()),
3578 RawEntryMut::Vacant(entry) => entry.try_insert(default_key, default_val),
3579 }
3580 }
3581
3582 /// Ensures a value is in the entry by inserting the result of the default function if empty,
3583 /// and returns mutable references to the key and value in the entry.
3584 ///
3585 /// # Examples
3586 ///
3587 /// ```
3588 /// use rune::alloc::HashMap;
3589 ///
3590 /// let mut map: HashMap<&str, String> = HashMap::new();
3591 ///
3592 /// map.raw_entry_mut().from_key("poneyland").or_try_insert_with(|| {
3593 /// ("poneyland", "hoho".to_string())
3594 /// })?;
3595 ///
3596 /// assert_eq!(map["poneyland"], "hoho".to_string());
3597 /// # Ok::<_, rune::alloc::Error>(())
3598 /// ```
3599 #[cfg_attr(feature = "inline-more", inline)]
3600 pub fn or_try_insert_with<F>(self, default: F) -> Result<(&'a mut K, &'a mut V), Error>
3601 where
3602 F: FnOnce() -> (K, V),
3603 K: Hash,
3604 S: BuildHasher,
3605 {
3606 match self {
3607 RawEntryMut::Occupied(entry) => Ok(entry.into_key_value()),
3608 RawEntryMut::Vacant(entry) => {
3609 let (k, v) = default();
3610 entry.try_insert(k, v)
3611 }
3612 }
3613 }
3614
3615 /// Provides in-place mutable access to an occupied entry before any
3616 /// potential inserts into the map.
3617 ///
3618 /// # Examples
3619 ///
3620 /// ```
3621 /// use rune::alloc::HashMap;
3622 ///
3623 /// let mut map: HashMap<&str, u32> = HashMap::new();
3624 ///
3625 /// map.raw_entry_mut()
3626 /// .from_key("poneyland")
3627 /// .and_modify(|_k, v| { *v += 1 })
3628 /// .or_try_insert("poneyland", 42)?;
3629 /// assert_eq!(map["poneyland"], 42);
3630 ///
3631 /// map.raw_entry_mut()
3632 /// .from_key("poneyland")
3633 /// .and_modify(|_k, v| { *v += 1 })
3634 /// .or_try_insert("poneyland", 0)?;
3635 /// assert_eq!(map["poneyland"], 43);
3636 /// # Ok::<_, rune::alloc::Error>(())
3637 /// ```
3638 #[cfg_attr(feature = "inline-more", inline)]
3639 pub fn and_modify<F>(self, f: F) -> Self
3640 where
3641 F: FnOnce(&mut K, &mut V),
3642 {
3643 match self {
3644 RawEntryMut::Occupied(mut entry) => {
3645 {
3646 let (k, v) = entry.get_key_value_mut();
3647 f(k, v);
3648 }
3649 RawEntryMut::Occupied(entry)
3650 }
3651 RawEntryMut::Vacant(entry) => RawEntryMut::Vacant(entry),
3652 }
3653 }
3654
3655 /// Provides shared access to the key and owned access to the value of
3656 /// an occupied entry and allows to replace or remove it based on the
3657 /// value of the returned option.
3658 ///
3659 /// # Examples
3660 ///
3661 /// ```
3662 /// use rune::alloc::HashMap;
3663 /// use rune::alloc::hash_map::RawEntryMut;
3664 ///
3665 /// let mut map: HashMap<&str, u32> = HashMap::new();
3666 ///
3667 /// let entry = map
3668 /// .raw_entry_mut()
3669 /// .from_key("poneyland")
3670 /// .and_replace_entry_with(|_k, _v| panic!());
3671 ///
3672 /// match entry {
3673 /// RawEntryMut::Vacant(_) => {},
3674 /// RawEntryMut::Occupied(_) => panic!(),
3675 /// }
3676 ///
3677 /// map.try_insert("poneyland", 42)?;
3678 ///
3679 /// let entry = map
3680 /// .raw_entry_mut()
3681 /// .from_key("poneyland")
3682 /// .and_replace_entry_with(|k, v| {
3683 /// assert_eq!(k, &"poneyland");
3684 /// assert_eq!(v, 42);
3685 /// Some(v + 1)
3686 /// });
3687 ///
3688 /// match entry {
3689 /// RawEntryMut::Occupied(e) => {
3690 /// assert_eq!(e.key(), &"poneyland");
3691 /// assert_eq!(e.get(), &43);
3692 /// },
3693 /// RawEntryMut::Vacant(_) => panic!(),
3694 /// }
3695 ///
3696 /// assert_eq!(map["poneyland"], 43);
3697 ///
3698 /// let entry = map
3699 /// .raw_entry_mut()
3700 /// .from_key("poneyland")
3701 /// .and_replace_entry_with(|_k, _v| None);
3702 ///
3703 /// match entry {
3704 /// RawEntryMut::Vacant(_) => {},
3705 /// RawEntryMut::Occupied(_) => panic!(),
3706 /// }
3707 ///
3708 /// assert!(!map.contains_key("poneyland"));
3709 /// # Ok::<_, rune::alloc::Error>(())
3710 /// ```
3711 #[cfg_attr(feature = "inline-more", inline)]
3712 pub fn and_replace_entry_with<F>(self, f: F) -> Self
3713 where
3714 F: FnOnce(&K, V) -> Option<V>,
3715 {
3716 match self {
3717 RawEntryMut::Occupied(entry) => entry.replace_entry_with(f),
3718 RawEntryMut::Vacant(_) => self,
3719 }
3720 }
3721}
3722
3723impl<'a, K, V, S, A: Allocator> RawOccupiedEntryMut<'a, K, V, S, A> {
3724 /// Gets a reference to the key in the entry.
3725 ///
3726 /// # Examples
3727 ///
3728 /// ```
3729 /// use rune::alloc::hash_map::{HashMap, RawEntryMut};
3730 ///
3731 /// let mut map: HashMap<&str, u32> = [("a", 100), ("b", 200)].try_into()?;
3732 ///
3733 /// match map.raw_entry_mut().from_key(&"a") {
3734 /// RawEntryMut::Vacant(_) => panic!(),
3735 /// RawEntryMut::Occupied(o) => assert_eq!(o.key(), &"a")
3736 /// }
3737 /// # Ok::<_, rune::alloc::Error>(())
3738 /// ```
3739 #[cfg_attr(feature = "inline-more", inline)]
3740 pub fn key(&self) -> &K {
3741 unsafe { &self.elem.as_ref().0 }
3742 }
3743
3744 /// Gets a mutable reference to the key in the entry.
3745 ///
3746 /// # Examples
3747 ///
3748 /// ```
3749 /// use rune::alloc::hash_map::{HashMap, RawEntryMut};
3750 /// use std::rc::Rc;
3751 ///
3752 /// let key_one = Rc::new("a");
3753 /// let key_two = Rc::new("a");
3754 ///
3755 /// let mut map: HashMap<Rc<&str>, u32> = HashMap::new();
3756 /// map.try_insert(key_one.clone(), 10)?;
3757 ///
3758 /// assert_eq!(map[&key_one], 10);
3759 /// assert!(Rc::strong_count(&key_one) == 2 && Rc::strong_count(&key_two) == 1);
3760 ///
3761 /// match map.raw_entry_mut().from_key(&key_one) {
3762 /// RawEntryMut::Vacant(_) => panic!(),
3763 /// RawEntryMut::Occupied(mut o) => {
3764 /// *o.key_mut() = key_two.clone();
3765 /// }
3766 /// }
3767 /// assert_eq!(map[&key_two], 10);
3768 /// assert!(Rc::strong_count(&key_one) == 1 && Rc::strong_count(&key_two) == 2);
3769 /// # Ok::<_, rune::alloc::Error>(())
3770 /// ```
3771 #[cfg_attr(feature = "inline-more", inline)]
3772 pub fn key_mut(&mut self) -> &mut K {
3773 unsafe { &mut self.elem.as_mut().0 }
3774 }
3775
3776 /// Converts the entry into a mutable reference to the key in the entry
3777 /// with a lifetime bound to the map itself.
3778 ///
3779 /// # Examples
3780 ///
3781 /// ```
3782 /// use rune::alloc::hash_map::{HashMap, RawEntryMut};
3783 /// use std::rc::Rc;
3784 ///
3785 /// let key_one = Rc::new("a");
3786 /// let key_two = Rc::new("a");
3787 ///
3788 /// let mut map: HashMap<Rc<&str>, u32> = HashMap::new();
3789 /// map.try_insert(key_one.clone(), 10)?;
3790 ///
3791 /// assert_eq!(map[&key_one], 10);
3792 /// assert!(Rc::strong_count(&key_one) == 2 && Rc::strong_count(&key_two) == 1);
3793 ///
3794 /// let inside_key: &mut Rc<&str>;
3795 ///
3796 /// match map.raw_entry_mut().from_key(&key_one) {
3797 /// RawEntryMut::Vacant(_) => panic!(),
3798 /// RawEntryMut::Occupied(o) => inside_key = o.into_key(),
3799 /// }
3800 /// *inside_key = key_two.clone();
3801 ///
3802 /// assert_eq!(map[&key_two], 10);
3803 /// assert!(Rc::strong_count(&key_one) == 1 && Rc::strong_count(&key_two) == 2);
3804 /// # Ok::<_, rune::alloc::Error>(())
3805 /// ```
3806 #[cfg_attr(feature = "inline-more", inline)]
3807 pub fn into_key(self) -> &'a mut K {
3808 unsafe { &mut self.elem.as_mut().0 }
3809 }
3810
3811 /// Gets a reference to the value in the entry.
3812 ///
3813 /// # Examples
3814 ///
3815 /// ```
3816 /// use rune::alloc::hash_map::{HashMap, RawEntryMut};
3817 ///
3818 /// let mut map: HashMap<&str, u32> = [("a", 100), ("b", 200)].try_into()?;
3819 ///
3820 /// match map.raw_entry_mut().from_key(&"a") {
3821 /// RawEntryMut::Vacant(_) => panic!(),
3822 /// RawEntryMut::Occupied(o) => assert_eq!(o.get(), &100),
3823 /// }
3824 /// # Ok::<_, rune::alloc::Error>(())
3825 /// ```
3826 #[cfg_attr(feature = "inline-more", inline)]
3827 pub fn get(&self) -> &V {
3828 unsafe { &self.elem.as_ref().1 }
3829 }
3830
3831 /// Converts the OccupiedEntry into a mutable reference to the value in the entry
3832 /// with a lifetime bound to the map itself.
3833 ///
3834 /// # Examples
3835 ///
3836 /// ```
3837 /// use rune::alloc::hash_map::{HashMap, RawEntryMut};
3838 ///
3839 /// let mut map: HashMap<&str, u32> = [("a", 100), ("b", 200)].try_into()?;
3840 ///
3841 /// let value: &mut u32;
3842 ///
3843 /// match map.raw_entry_mut().from_key(&"a") {
3844 /// RawEntryMut::Vacant(_) => panic!(),
3845 /// RawEntryMut::Occupied(o) => value = o.into_mut(),
3846 /// }
3847 /// *value += 900;
3848 ///
3849 /// assert_eq!(map[&"a"], 1000);
3850 /// # Ok::<_, rune::alloc::Error>(())
3851 /// ```
3852 #[cfg_attr(feature = "inline-more", inline)]
3853 pub fn into_mut(self) -> &'a mut V {
3854 unsafe { &mut self.elem.as_mut().1 }
3855 }
3856
3857 /// Gets a mutable reference to the value in the entry.
3858 ///
3859 /// # Examples
3860 ///
3861 /// ```
3862 /// use rune::alloc::hash_map::{HashMap, RawEntryMut};
3863 ///
3864 /// let mut map: HashMap<&str, u32> = [("a", 100), ("b", 200)].try_into()?;
3865 ///
3866 /// match map.raw_entry_mut().from_key(&"a") {
3867 /// RawEntryMut::Vacant(_) => panic!(),
3868 /// RawEntryMut::Occupied(mut o) => *o.get_mut() += 900,
3869 /// }
3870 ///
3871 /// assert_eq!(map[&"a"], 1000);
3872 /// # Ok::<_, rune::alloc::Error>(())
3873 /// ```
3874 #[cfg_attr(feature = "inline-more", inline)]
3875 pub fn get_mut(&mut self) -> &mut V {
3876 unsafe { &mut self.elem.as_mut().1 }
3877 }
3878
3879 /// Gets a reference to the key and value in the entry.
3880 ///
3881 /// # Examples
3882 ///
3883 /// ```
3884 /// use rune::alloc::hash_map::{HashMap, RawEntryMut};
3885 ///
3886 /// let mut map: HashMap<&str, u32> = [("a", 100), ("b", 200)].try_into()?;
3887 ///
3888 /// match map.raw_entry_mut().from_key(&"a") {
3889 /// RawEntryMut::Vacant(_) => panic!(),
3890 /// RawEntryMut::Occupied(o) => assert_eq!(o.get_key_value(), (&"a", &100)),
3891 /// }
3892 /// # Ok::<_, rune::alloc::Error>(())
3893 /// ```
3894 #[cfg_attr(feature = "inline-more", inline)]
3895 pub fn get_key_value(&self) -> (&K, &V) {
3896 unsafe {
3897 let (key, value) = self.elem.as_ref();
3898 (key, value)
3899 }
3900 }
3901
3902 /// Gets a mutable reference to the key and value in the entry.
3903 ///
3904 /// # Examples
3905 ///
3906 /// ```
3907 /// use rune::alloc::hash_map::{HashMap, RawEntryMut};
3908 /// use std::rc::Rc;
3909 ///
3910 /// let key_one = Rc::new("a");
3911 /// let key_two = Rc::new("a");
3912 ///
3913 /// let mut map: HashMap<Rc<&str>, u32> = HashMap::new();
3914 /// map.try_insert(key_one.clone(), 10)?;
3915 ///
3916 /// assert_eq!(map[&key_one], 10);
3917 /// assert!(Rc::strong_count(&key_one) == 2 && Rc::strong_count(&key_two) == 1);
3918 ///
3919 /// match map.raw_entry_mut().from_key(&key_one) {
3920 /// RawEntryMut::Vacant(_) => panic!(),
3921 /// RawEntryMut::Occupied(mut o) => {
3922 /// let (inside_key, inside_value) = o.get_key_value_mut();
3923 /// *inside_key = key_two.clone();
3924 /// *inside_value = 100;
3925 /// }
3926 /// }
3927 /// assert_eq!(map[&key_two], 100);
3928 /// assert!(Rc::strong_count(&key_one) == 1 && Rc::strong_count(&key_two) == 2);
3929 /// # Ok::<_, rune::alloc::Error>(())
3930 /// ```
3931 #[cfg_attr(feature = "inline-more", inline)]
3932 pub fn get_key_value_mut(&mut self) -> (&mut K, &mut V) {
3933 unsafe {
3934 let &mut (ref mut key, ref mut value) = self.elem.as_mut();
3935 (key, value)
3936 }
3937 }
3938
3939 /// Converts the OccupiedEntry into a mutable reference to the key and value in the entry
3940 /// with a lifetime bound to the map itself.
3941 ///
3942 /// # Examples
3943 ///
3944 /// ```
3945 /// use rune::alloc::hash_map::{HashMap, RawEntryMut};
3946 /// use std::rc::Rc;
3947 ///
3948 /// let key_one = Rc::new("a");
3949 /// let key_two = Rc::new("a");
3950 ///
3951 /// let mut map: HashMap<Rc<&str>, u32> = HashMap::new();
3952 /// map.try_insert(key_one.clone(), 10)?;
3953 ///
3954 /// assert_eq!(map[&key_one], 10);
3955 /// assert!(Rc::strong_count(&key_one) == 2 && Rc::strong_count(&key_two) == 1);
3956 ///
3957 /// let inside_key: &mut Rc<&str>;
3958 /// let inside_value: &mut u32;
3959 /// match map.raw_entry_mut().from_key(&key_one) {
3960 /// RawEntryMut::Vacant(_) => panic!(),
3961 /// RawEntryMut::Occupied(o) => {
3962 /// let tuple = o.into_key_value();
3963 /// inside_key = tuple.0;
3964 /// inside_value = tuple.1;
3965 /// }
3966 /// }
3967 /// *inside_key = key_two.clone();
3968 /// *inside_value = 100;
3969 /// assert_eq!(map[&key_two], 100);
3970 /// assert!(Rc::strong_count(&key_one) == 1 && Rc::strong_count(&key_two) == 2);
3971 /// # Ok::<_, rune::alloc::Error>(())
3972 /// ```
3973 #[cfg_attr(feature = "inline-more", inline)]
3974 pub fn into_key_value(self) -> (&'a mut K, &'a mut V) {
3975 unsafe {
3976 let &mut (ref mut key, ref mut value) = self.elem.as_mut();
3977 (key, value)
3978 }
3979 }
3980
3981 /// Sets the value of the entry, and returns the entry's old value.
3982 ///
3983 /// # Examples
3984 ///
3985 /// ```
3986 /// use rune::alloc::hash_map::{HashMap, RawEntryMut};
3987 ///
3988 /// let mut map: HashMap<&str, u32> = [("a", 100), ("b", 200)].try_into()?;
3989 ///
3990 /// match map.raw_entry_mut().from_key(&"a") {
3991 /// RawEntryMut::Vacant(_) => panic!(),
3992 /// RawEntryMut::Occupied(mut o) => assert_eq!(o.insert(1000), 100),
3993 /// }
3994 ///
3995 /// assert_eq!(map[&"a"], 1000);
3996 /// # Ok::<_, rune::alloc::Error>(())
3997 /// ```
3998 #[cfg_attr(feature = "inline-more", inline)]
3999 pub fn insert(&mut self, value: V) -> V {
4000 mem::replace(self.get_mut(), value)
4001 }
4002
4003 /// Sets the value of the entry, and returns the entry's old value.
4004 ///
4005 /// # Examples
4006 ///
4007 /// ```
4008 /// use rune::alloc::hash_map::{HashMap, RawEntryMut};
4009 /// use std::rc::Rc;
4010 ///
4011 /// let key_one = Rc::new("a");
4012 /// let key_two = Rc::new("a");
4013 ///
4014 /// let mut map: HashMap<Rc<&str>, u32> = HashMap::new();
4015 /// map.try_insert(key_one.clone(), 10)?;
4016 ///
4017 /// assert_eq!(map[&key_one], 10);
4018 /// assert!(Rc::strong_count(&key_one) == 2 && Rc::strong_count(&key_two) == 1);
4019 ///
4020 /// match map.raw_entry_mut().from_key(&key_one) {
4021 /// RawEntryMut::Vacant(_) => panic!(),
4022 /// RawEntryMut::Occupied(mut o) => {
4023 /// let old_key = o.insert_key(key_two.clone());
4024 /// assert!(Rc::ptr_eq(&old_key, &key_one));
4025 /// }
4026 /// }
4027 /// assert_eq!(map[&key_two], 10);
4028 /// assert!(Rc::strong_count(&key_one) == 1 && Rc::strong_count(&key_two) == 2);
4029 /// # Ok::<_, rune::alloc::Error>(())
4030 /// ```
4031 #[cfg_attr(feature = "inline-more", inline)]
4032 pub fn insert_key(&mut self, key: K) -> K {
4033 mem::replace(self.key_mut(), key)
4034 }
4035
4036 /// Takes the value out of the entry, and returns it.
4037 ///
4038 /// # Examples
4039 ///
4040 /// ```
4041 /// use rune::alloc::hash_map::{HashMap, RawEntryMut};
4042 ///
4043 /// let mut map: HashMap<&str, u32> = [("a", 100), ("b", 200)].try_into()?;
4044 ///
4045 /// match map.raw_entry_mut().from_key(&"a") {
4046 /// RawEntryMut::Vacant(_) => panic!(),
4047 /// RawEntryMut::Occupied(o) => assert_eq!(o.remove(), 100),
4048 /// }
4049 /// assert_eq!(map.get(&"a"), None);
4050 /// # Ok::<_, rune::alloc::Error>(())
4051 /// ```
4052 #[cfg_attr(feature = "inline-more", inline)]
4053 pub fn remove(self) -> V {
4054 self.remove_entry().1
4055 }
4056
4057 /// Take the ownership of the key and value from the map.
4058 ///
4059 /// # Examples
4060 ///
4061 /// ```
4062 /// use rune::alloc::hash_map::{HashMap, RawEntryMut};
4063 ///
4064 /// let mut map: HashMap<&str, u32> = [("a", 100), ("b", 200)].try_into()?;
4065 ///
4066 /// match map.raw_entry_mut().from_key(&"a") {
4067 /// RawEntryMut::Vacant(_) => panic!(),
4068 /// RawEntryMut::Occupied(o) => assert_eq!(o.remove_entry(), ("a", 100)),
4069 /// }
4070 /// assert_eq!(map.get(&"a"), None);
4071 /// # Ok::<_, rune::alloc::Error>(())
4072 /// ```
4073 #[cfg_attr(feature = "inline-more", inline)]
4074 pub fn remove_entry(self) -> (K, V) {
4075 unsafe { self.table.remove(self.elem).0 }
4076 }
4077
4078 /// Provides shared access to the key and owned access to the value of
4079 /// the entry and allows to replace or remove it based on the
4080 /// value of the returned option.
4081 ///
4082 /// # Examples
4083 ///
4084 /// ```
4085 /// use rune::alloc::hash_map::{HashMap, RawEntryMut};
4086 ///
4087 /// let mut map: HashMap<&str, u32> = [("a", 100), ("b", 200)].try_into()?;
4088 ///
4089 /// let raw_entry = match map.raw_entry_mut().from_key(&"a") {
4090 /// RawEntryMut::Vacant(_) => panic!(),
4091 /// RawEntryMut::Occupied(o) => o.replace_entry_with(|k, v| {
4092 /// assert_eq!(k, &"a");
4093 /// assert_eq!(v, 100);
4094 /// Some(v + 900)
4095 /// }),
4096 /// };
4097 /// let raw_entry = match raw_entry {
4098 /// RawEntryMut::Vacant(_) => panic!(),
4099 /// RawEntryMut::Occupied(o) => o.replace_entry_with(|k, v| {
4100 /// assert_eq!(k, &"a");
4101 /// assert_eq!(v, 1000);
4102 /// None
4103 /// }),
4104 /// };
4105 /// match raw_entry {
4106 /// RawEntryMut::Vacant(_) => { },
4107 /// RawEntryMut::Occupied(_) => panic!(),
4108 /// };
4109 /// assert_eq!(map.get(&"a"), None);
4110 /// # Ok::<_, rune::alloc::Error>(())
4111 /// ```
4112 #[cfg_attr(feature = "inline-more", inline)]
4113 pub fn replace_entry_with<F>(self, f: F) -> RawEntryMut<'a, K, V, S, A>
4114 where
4115 F: FnOnce(&K, V) -> Option<V>,
4116 {
4117 unsafe {
4118 let still_occupied = self
4119 .table
4120 .replace_bucket_with(self.elem.clone(), |(key, value)| {
4121 f(&key, value).map(|new_value| (key, new_value))
4122 });
4123
4124 if still_occupied {
4125 RawEntryMut::Occupied(self)
4126 } else {
4127 RawEntryMut::Vacant(RawVacantEntryMut {
4128 table: self.table,
4129 hash_builder: self.hash_builder,
4130 })
4131 }
4132 }
4133 }
4134}
4135
4136impl<'a, K, V, S, A: Allocator> RawVacantEntryMut<'a, K, V, S, A> {
4137 /// Sets the value of the entry with the VacantEntry's key,
4138 /// and returns a mutable reference to it.
4139 ///
4140 /// # Examples
4141 ///
4142 /// ```
4143 /// use rune::alloc::hash_map::{HashMap, RawEntryMut};
4144 ///
4145 /// let mut map: HashMap<&str, u32> = [("a", 100), ("b", 200)].try_into()?;
4146 ///
4147 /// match map.raw_entry_mut().from_key(&"c") {
4148 /// RawEntryMut::Occupied(_) => panic!(),
4149 /// RawEntryMut::Vacant(v) => assert_eq!(v.try_insert("c", 300)?, (&mut "c", &mut 300)),
4150 /// }
4151 ///
4152 /// assert_eq!(map[&"c"], 300);
4153 /// # Ok::<_, rune::alloc::Error>(())
4154 /// ```
4155 #[cfg_attr(feature = "inline-more", inline)]
4156 pub fn try_insert(self, key: K, value: V) -> Result<(&'a mut K, &'a mut V), Error>
4157 where
4158 K: Hash,
4159 S: BuildHasher,
4160 {
4161 let hasher = make_hasher(self.hash_builder);
4162 let hash = into_ok(hasher.hash(&mut (), &key));
4163
4164 let &mut (ref mut k, ref mut v) =
4165 into_ok_try(
4166 self.table
4167 .insert_entry(&mut (), hash, (key, value), hasher.into_tuple()),
4168 )?;
4169
4170 Ok((k, v))
4171 }
4172
4173 #[cfg(test)]
4174 pub(crate) fn insert(self, key: K, value: V) -> (&'a mut K, &'a mut V)
4175 where
4176 K: Hash,
4177 S: BuildHasher,
4178 {
4179 self.try_insert(key, value).abort()
4180 }
4181
4182 /// Sets the value of the entry with the VacantEntry's key, and returns a
4183 /// mutable reference to it.
4184 ///
4185 /// # Examples
4186 ///
4187 /// ```
4188 /// use core::hash::{BuildHasher, Hash};
4189 /// use rune::alloc::hash_map::{HashMap, RawEntryMut};
4190 ///
4191 /// fn compute_hash<K: Hash + ?Sized, S: BuildHasher>(hash_builder: &S, key: &K) -> u64 {
4192 /// use core::hash::Hasher;
4193 /// let mut state = hash_builder.build_hasher();
4194 /// key.hash(&mut state);
4195 /// state.finish()
4196 /// }
4197 ///
4198 /// let mut map: HashMap<&str, u32> = [("a", 100), ("b", 200)].try_into()?;
4199 /// let key = "c";
4200 /// let hash = compute_hash(map.hasher(), &key);
4201 ///
4202 /// match map.raw_entry_mut().from_key_hashed_nocheck(hash, &key) {
4203 /// RawEntryMut::Occupied(_) => panic!(),
4204 /// RawEntryMut::Vacant(v) => assert_eq!(
4205 /// v.try_insert_hashed_nocheck(hash, key, 300)?,
4206 /// (&mut "c", &mut 300)
4207 /// ),
4208 /// }
4209 ///
4210 /// assert_eq!(map[&"c"], 300);
4211 /// # Ok::<_, rune::alloc::Error>(())
4212 /// ```
4213 #[cfg_attr(feature = "inline-more", inline)]
4214 #[allow(clippy::shadow_unrelated)]
4215 pub fn try_insert_hashed_nocheck(
4216 self,
4217 hash: u64,
4218 key: K,
4219 value: V,
4220 ) -> Result<(&'a mut K, &'a mut V), Error>
4221 where
4222 K: Hash,
4223 S: BuildHasher,
4224 {
4225 let hasher = make_hasher::<K, S>(self.hash_builder);
4226 let &mut (ref mut k, ref mut v) =
4227 into_ok_try(
4228 self.table
4229 .insert_entry(&mut (), hash, (key, value), hasher.into_tuple()),
4230 )?;
4231 Ok((k, v))
4232 }
4233
4234 /// Set the value of an entry with a custom hasher function.
4235 ///
4236 /// # Examples
4237 ///
4238 /// ```
4239 /// use core::hash::{BuildHasher, Hash};
4240 /// use rune::alloc::hash_map::{HashMap, RawEntryMut};
4241 /// use rune::alloc::prelude::*;
4242 ///
4243 /// fn make_hasher<K, S>(hash_builder: &S) -> impl Fn(&K) -> u64 + '_
4244 /// where
4245 /// K: Hash + ?Sized,
4246 /// S: BuildHasher,
4247 /// {
4248 /// move |key: &K| {
4249 /// use core::hash::Hasher;
4250 /// let mut state = hash_builder.build_hasher();
4251 /// key.hash(&mut state);
4252 /// state.finish()
4253 /// }
4254 /// }
4255 ///
4256 /// let mut map: HashMap<&str, u32> = HashMap::new();
4257 /// let key = "a";
4258 /// let hash_builder = map.hasher().clone();
4259 /// let hash = make_hasher(&hash_builder)(&key);
4260 ///
4261 /// match map.raw_entry_mut().from_hash(hash, |q| q == &key) {
4262 /// RawEntryMut::Occupied(_) => panic!(),
4263 /// RawEntryMut::Vacant(v) => assert_eq!(
4264 /// v.try_insert_with_hasher(hash, key, 100, make_hasher(&hash_builder))?,
4265 /// (&mut "a", &mut 100)
4266 /// ),
4267 /// }
4268 ///
4269 /// map.try_extend([("b", 200), ("c", 300), ("d", 400), ("e", 500), ("f", 600)])?;
4270 /// assert_eq!(map[&"a"], 100);
4271 /// # Ok::<_, rune::alloc::Error>(())
4272 /// ```
4273 #[cfg_attr(feature = "inline-more", inline)]
4274 pub fn try_insert_with_hasher<H>(
4275 self,
4276 hash: u64,
4277 key: K,
4278 value: V,
4279 hasher: H,
4280 ) -> Result<(&'a mut K, &'a mut V), Error>
4281 where
4282 H: Fn(&K) -> u64,
4283 {
4284 let &mut (ref mut k, ref mut v) = into_ok_try(self.table.insert_entry(
4285 &mut (),
4286 hash,
4287 (key, value),
4288 move |_: &mut (), x: &(K, V)| Ok(hasher(&x.0)),
4289 ))?;
4290
4291 Ok((k, v))
4292 }
4293
4294 #[cfg(test)]
4295 pub(crate) fn insert_with_hasher<H>(
4296 self,
4297 hash: u64,
4298 key: K,
4299 value: V,
4300 hasher: H,
4301 ) -> (&'a mut K, &'a mut V)
4302 where
4303 H: Fn(&K) -> u64,
4304 {
4305 self.try_insert_with_hasher(hash, key, value, hasher)
4306 .abort()
4307 }
4308
4309 #[cfg_attr(feature = "inline-more", inline)]
4310 fn insert_entry<C, E>(
4311 self,
4312 cx: &mut C,
4313 hasher: impl HasherFn<C, K, E>,
4314 key: K,
4315 value: V,
4316 ) -> Result<RawOccupiedEntryMut<'a, K, V, S, A>, CustomError<E>>
4317 where
4318 K: Hash,
4319 S: BuildHasher,
4320 {
4321 let hash = hasher.hash(cx, &key).map_err(CustomError::Custom)?;
4322
4323 let elem = self
4324 .table
4325 .insert(cx, hash, (key, value), hasher.into_tuple())?;
4326
4327 Ok(RawOccupiedEntryMut {
4328 elem,
4329 table: self.table,
4330 hash_builder: self.hash_builder,
4331 })
4332 }
4333}
4334
4335impl<K, V, S, A: Allocator> Debug for RawEntryBuilderMut<'_, K, V, S, A> {
4336 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
4337 f.debug_struct("RawEntryBuilder").finish()
4338 }
4339}
4340
4341impl<K: Debug, V: Debug, S, A: Allocator> Debug for RawEntryMut<'_, K, V, S, A> {
4342 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
4343 match *self {
4344 RawEntryMut::Vacant(ref v) => f.debug_tuple("RawEntry").field(v).finish(),
4345 RawEntryMut::Occupied(ref o) => f.debug_tuple("RawEntry").field(o).finish(),
4346 }
4347 }
4348}
4349
4350impl<K: Debug, V: Debug, S, A: Allocator> Debug for RawOccupiedEntryMut<'_, K, V, S, A> {
4351 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
4352 f.debug_struct("RawOccupiedEntryMut")
4353 .field("key", self.key())
4354 .field("value", self.get())
4355 .finish()
4356 }
4357}
4358
4359impl<K, V, S, A: Allocator> Debug for RawVacantEntryMut<'_, K, V, S, A> {
4360 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
4361 f.debug_struct("RawVacantEntryMut").finish()
4362 }
4363}
4364
4365impl<K, V, S, A: Allocator> Debug for RawEntryBuilder<'_, K, V, S, A> {
4366 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
4367 f.debug_struct("RawEntryBuilder").finish()
4368 }
4369}
4370
4371/// A view into a single entry in a map, which may either be vacant or occupied.
4372///
4373/// This `enum` is constructed from the [`entry`] method on [`HashMap`].
4374///
4375/// [`HashMap`]: struct.HashMap.html
4376/// [`entry`]: struct.HashMap.html#method.entry
4377///
4378/// # Examples
4379///
4380/// ```
4381/// use rune::alloc::hash_map::{Entry, HashMap, OccupiedEntry};
4382/// use rune::alloc::prelude::*;
4383///
4384/// let mut map = HashMap::new();
4385/// map.try_extend([("a", 10), ("b", 20), ("c", 30)])?;
4386/// assert_eq!(map.len(), 3);
4387///
4388/// // Existing key (try_insert)
4389/// let entry: Entry<_, _, _> = map.entry("a");
4390/// let _raw_o: OccupiedEntry<_, _, _> = entry.try_insert(1)?;
4391/// assert_eq!(map.len(), 3);
4392/// // Nonexistent key (try_insert)
4393/// map.entry("d").try_insert(4)?;
4394///
4395/// // Existing key (or_try_insert)
4396/// let v = map.entry("b").or_try_insert(2)?;
4397/// assert_eq!(std::mem::replace(v, 2), 20);
4398/// // Nonexistent key (or_try_insert)
4399/// map.entry("e").or_try_insert(5)?;
4400///
4401/// // Existing key (or_try_insert_with)
4402/// let v = map.entry("c").or_try_insert_with(|| 3)?;
4403/// assert_eq!(std::mem::replace(v, 3), 30);
4404/// // Nonexistent key (or_try_insert_with)
4405/// map.entry("f").or_try_insert_with(|| 6)?;
4406///
4407/// println!("Our HashMap: {:?}", map);
4408///
4409/// let mut vec: Vec<_> = map.iter().map(|(&k, &v)| (k, v)).collect();
4410/// // The `Iter` iterator produces items in arbitrary order, so the
4411/// // items must be sorted to test them against a sorted array.
4412/// vec.sort_unstable();
4413/// assert_eq!(vec, [("a", 1), ("b", 2), ("c", 3), ("d", 4), ("e", 5), ("f", 6)]);
4414/// # Ok::<_, rune::alloc::Error>(())
4415/// ```
4416pub enum Entry<'a, K, V, S, A = Global>
4417where
4418 A: Allocator,
4419{
4420 /// An occupied entry.
4421 ///
4422 /// # Examples
4423 ///
4424 /// ```
4425 /// use rune::alloc::hash_map::{Entry, HashMap};
4426 /// let mut map: HashMap<_, _> = [("a", 100), ("b", 200)].try_into()?;
4427 ///
4428 /// match map.entry("a") {
4429 /// Entry::Vacant(_) => unreachable!(),
4430 /// Entry::Occupied(_) => { }
4431 /// }
4432 /// # Ok::<_, rune::alloc::Error>(())
4433 /// ```
4434 Occupied(OccupiedEntry<'a, K, V, S, A>),
4435
4436 /// A vacant entry.
4437 ///
4438 /// # Examples
4439 ///
4440 /// ```
4441 /// use rune::alloc::hash_map::{Entry, HashMap};
4442 /// let mut map: HashMap<&str, i32> = HashMap::new();
4443 ///
4444 /// match map.entry("a") {
4445 /// Entry::Occupied(_) => unreachable!(),
4446 /// Entry::Vacant(_) => { }
4447 /// }
4448 /// ```
4449 Vacant(VacantEntry<'a, K, V, S, A>),
4450}
4451
4452impl<K: Debug, V: Debug, S, A: Allocator> Debug for Entry<'_, K, V, S, A> {
4453 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
4454 match *self {
4455 Entry::Vacant(ref v) => f.debug_tuple("Entry").field(v).finish(),
4456 Entry::Occupied(ref o) => f.debug_tuple("Entry").field(o).finish(),
4457 }
4458 }
4459}
4460
4461/// A view into an occupied entry in a `HashMap`.
4462/// It is part of the [`Entry`] enum.
4463///
4464/// [`Entry`]: enum.Entry.html
4465///
4466/// # Examples
4467///
4468/// ```
4469/// use rune::alloc::hash_map::{Entry, HashMap, OccupiedEntry};
4470/// use rune::alloc::prelude::*;
4471///
4472/// let mut map = HashMap::new();
4473/// map.try_extend([("a", 10), ("b", 20), ("c", 30)])?;
4474///
4475/// let _entry_o: OccupiedEntry<_, _, _> = map.entry("a").try_insert(100)?;
4476/// assert_eq!(map.len(), 3);
4477///
4478/// // Existing key (insert and update)
4479/// match map.entry("a") {
4480/// Entry::Vacant(_) => unreachable!(),
4481/// Entry::Occupied(mut view) => {
4482/// assert_eq!(view.get(), &100);
4483/// let v = view.get_mut();
4484/// *v *= 10;
4485/// assert_eq!(view.insert(1111), 1000);
4486/// }
4487/// }
4488///
4489/// assert_eq!(map[&"a"], 1111);
4490/// assert_eq!(map.len(), 3);
4491///
4492/// // Existing key (take)
4493/// match map.entry("c") {
4494/// Entry::Vacant(_) => unreachable!(),
4495/// Entry::Occupied(view) => {
4496/// assert_eq!(view.remove_entry(), ("c", 30));
4497/// }
4498/// }
4499/// assert_eq!(map.get(&"c"), None);
4500/// assert_eq!(map.len(), 2);
4501/// # Ok::<_, rune::alloc::Error>(())
4502/// ```
4503pub struct OccupiedEntry<'a, K, V, S = DefaultHashBuilder, A: Allocator = Global> {
4504 hash: u64,
4505 key: Option<K>,
4506 elem: Bucket<(K, V)>,
4507 table: &'a mut HashMap<K, V, S, A>,
4508}
4509
4510unsafe impl<K, V, S, A> Send for OccupiedEntry<'_, K, V, S, A>
4511where
4512 K: Send,
4513 V: Send,
4514 S: Send,
4515 A: Send + Allocator,
4516{
4517}
4518unsafe impl<K, V, S, A> Sync for OccupiedEntry<'_, K, V, S, A>
4519where
4520 K: Sync,
4521 V: Sync,
4522 S: Sync,
4523 A: Sync + Allocator,
4524{
4525}
4526
4527impl<K: Debug, V: Debug, S, A: Allocator> Debug for OccupiedEntry<'_, K, V, S, A> {
4528 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
4529 f.debug_struct("OccupiedEntry")
4530 .field("key", self.key())
4531 .field("value", self.get())
4532 .finish()
4533 }
4534}
4535
4536/// A view into a vacant entry in a `HashMap`.
4537/// It is part of the [`Entry`] enum.
4538///
4539/// [`Entry`]: enum.Entry.html
4540///
4541/// # Examples
4542///
4543/// ```
4544/// use rune::alloc::hash_map::{Entry, HashMap, VacantEntry};
4545///
4546/// let mut map = HashMap::<&str, i32>::new();
4547///
4548/// let entry_v: VacantEntry<_, _, _> = match map.entry("a") {
4549/// Entry::Vacant(view) => view,
4550/// Entry::Occupied(_) => unreachable!(),
4551/// };
4552/// entry_v.try_insert(10)?;
4553/// assert!(map[&"a"] == 10 && map.len() == 1);
4554///
4555/// // Nonexistent key (insert and update)
4556/// match map.entry("b") {
4557/// Entry::Occupied(_) => unreachable!(),
4558/// Entry::Vacant(view) => {
4559/// let value = view.try_insert(2)?;
4560/// assert_eq!(*value, 2);
4561/// *value = 20;
4562/// }
4563/// }
4564/// assert!(map[&"b"] == 20 && map.len() == 2);
4565/// # Ok::<_, rune::alloc::Error>(())
4566/// ```
4567pub struct VacantEntry<'a, K, V, S = DefaultHashBuilder, A: Allocator = Global> {
4568 hash: u64,
4569 key: K,
4570 table: &'a mut HashMap<K, V, S, A>,
4571}
4572
4573impl<K: Debug, V, S, A: Allocator> Debug for VacantEntry<'_, K, V, S, A> {
4574 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
4575 f.debug_tuple("VacantEntry").field(self.key()).finish()
4576 }
4577}
4578
4579/// A view into a single entry in a map, which may either be vacant or occupied,
4580/// with any borrowed form of the map's key type.
4581///
4582///
4583/// This `enum` is constructed from the [`entry_ref`] method on [`HashMap`].
4584///
4585/// [`Hash`] and [`Eq`] on the borrowed form of the map's key type *must* match those
4586/// for the key type. It also require that key may be constructed from the borrowed
4587/// form through the [`From`] trait.
4588///
4589/// [`HashMap`]: struct.HashMap.html
4590/// [`entry_ref`]: struct.HashMap.html#method.entry_ref
4591/// [`Eq`]: https://doc.rust-lang.org/std/cmp/trait.Eq.html
4592/// [`Hash`]: https://doc.rust-lang.org/std/hash/trait.Hash.html
4593/// [`From`]: https://doc.rust-lang.org/std/convert/trait.From.html
4594///
4595/// # Examples
4596///
4597/// ```
4598/// use rune::alloc::hash_map::{EntryRef, HashMap, OccupiedEntryRef};
4599/// use rune::alloc::prelude::*;
4600///
4601/// let mut map = HashMap::new();
4602/// map.try_extend([("a".to_owned(), 10), ("b".into(), 20), ("c".into(), 30)])?;
4603/// assert_eq!(map.len(), 3);
4604///
4605/// // Existing key (try_insert)
4606/// let key = String::from("a");
4607/// let entry: EntryRef<_, _, _, _> = map.entry_ref(&key);
4608/// let _raw_o: OccupiedEntryRef<_, _, _, _> = entry.try_insert(1)?;
4609/// assert_eq!(map.len(), 3);
4610/// // Nonexistent key (try_insert)
4611/// map.entry_ref("d").try_insert(4)?;
4612///
4613/// // Existing key (or_try_insert)
4614/// let v = map.entry_ref("b").or_try_insert(2)?;
4615/// assert_eq!(std::mem::replace(v, 2), 20);
4616/// // Nonexistent key (or_try_insert)
4617/// map.entry_ref("e").or_try_insert(5)?;
4618///
4619/// // Existing key (or_try_insert_with)
4620/// let v = map.entry_ref("c").or_try_insert_with(|| 3)?;
4621/// assert_eq!(std::mem::replace(v, 3), 30);
4622/// // Nonexistent key (or_try_insert_with)
4623/// map.entry_ref("f").or_try_insert_with(|| 6)?;
4624///
4625/// println!("Our HashMap: {:?}", map);
4626///
4627/// for (key, value) in ["a", "b", "c", "d", "e", "f"].into_iter().zip(1..=6) {
4628/// assert_eq!(map[key], value)
4629/// }
4630/// assert_eq!(map.len(), 6);
4631/// # Ok::<_, rune::alloc::Error>(())
4632/// ```
4633pub enum EntryRef<'a, 'b, K, Q: ?Sized, V, S, A = Global>
4634where
4635 A: Allocator,
4636{
4637 /// An occupied entry.
4638 ///
4639 /// # Examples
4640 ///
4641 /// ```
4642 /// use rune::alloc::hash_map::{EntryRef, HashMap};
4643 /// let mut map: HashMap<_, _> = [("a".to_owned(), 100), ("b".into(), 200)].try_into()?;
4644 ///
4645 /// match map.entry_ref("a") {
4646 /// EntryRef::Vacant(_) => unreachable!(),
4647 /// EntryRef::Occupied(_) => { }
4648 /// }
4649 /// # Ok::<_, rune::alloc::Error>(())
4650 /// ```
4651 Occupied(OccupiedEntryRef<'a, 'b, K, Q, V, S, A>),
4652
4653 /// A vacant entry.
4654 ///
4655 /// # Examples
4656 ///
4657 /// ```
4658 /// use rune::alloc::hash_map::{EntryRef, HashMap};
4659 /// let mut map: HashMap<String, i32> = HashMap::new();
4660 ///
4661 /// match map.entry_ref("a") {
4662 /// EntryRef::Occupied(_) => unreachable!(),
4663 /// EntryRef::Vacant(_) => { }
4664 /// }
4665 /// ```
4666 Vacant(VacantEntryRef<'a, 'b, K, Q, V, S, A>),
4667}
4668
4669impl<K: Borrow<Q>, Q: ?Sized + Debug, V: Debug, S, A: Allocator> Debug
4670 for EntryRef<'_, '_, K, Q, V, S, A>
4671{
4672 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
4673 match *self {
4674 EntryRef::Vacant(ref v) => f.debug_tuple("EntryRef").field(v).finish(),
4675 EntryRef::Occupied(ref o) => f.debug_tuple("EntryRef").field(o).finish(),
4676 }
4677 }
4678}
4679
4680enum KeyOrRef<'a, K, Q: ?Sized> {
4681 Borrowed(&'a Q),
4682 Owned(K),
4683}
4684
4685impl<'a, K, Q: ?Sized> KeyOrRef<'a, K, Q> {
4686 fn into_owned(self) -> K
4687 where
4688 K: From<&'a Q>,
4689 {
4690 match self {
4691 Self::Borrowed(borrowed) => borrowed.into(),
4692 Self::Owned(owned) => owned,
4693 }
4694 }
4695}
4696
4697impl<'a, K: Borrow<Q>, Q: ?Sized> AsRef<Q> for KeyOrRef<'a, K, Q> {
4698 fn as_ref(&self) -> &Q {
4699 match self {
4700 Self::Borrowed(borrowed) => borrowed,
4701 Self::Owned(owned) => owned.borrow(),
4702 }
4703 }
4704}
4705
4706/// A view into an occupied entry in a `HashMap`.
4707/// It is part of the [`EntryRef`] enum.
4708///
4709/// [`EntryRef`]: enum.EntryRef.html
4710///
4711/// # Examples
4712///
4713/// ```
4714/// use rune::alloc::hash_map::{EntryRef, HashMap, OccupiedEntryRef};
4715/// use rune::alloc::prelude::*;
4716///
4717/// let mut map = HashMap::new();
4718/// map.try_extend([("a".to_owned(), 10), ("b".into(), 20), ("c".into(), 30)])?;
4719///
4720/// let key = String::from("a");
4721/// let _entry_o: OccupiedEntryRef<_, _, _, _> = map.entry_ref(&key).try_insert(100)?;
4722/// assert_eq!(map.len(), 3);
4723///
4724/// // Existing key (insert and update)
4725/// match map.entry_ref("a") {
4726/// EntryRef::Vacant(_) => unreachable!(),
4727/// EntryRef::Occupied(mut view) => {
4728/// assert_eq!(view.get(), &100);
4729/// let v = view.get_mut();
4730/// *v *= 10;
4731/// assert_eq!(view.insert(1111), 1000);
4732/// }
4733/// }
4734///
4735/// assert_eq!(map["a"], 1111);
4736/// assert_eq!(map.len(), 3);
4737///
4738/// // Existing key (take)
4739/// match map.entry_ref("c") {
4740/// EntryRef::Vacant(_) => unreachable!(),
4741/// EntryRef::Occupied(view) => {
4742/// assert_eq!(view.remove_entry(), ("c".to_owned(), 30));
4743/// }
4744/// }
4745/// assert_eq!(map.get("c"), None);
4746/// assert_eq!(map.len(), 2);
4747/// # Ok::<_, rune::alloc::Error>(())
4748/// ```
4749pub struct OccupiedEntryRef<'a, 'b, K, Q: ?Sized, V, S, A: Allocator = Global> {
4750 hash: u64,
4751 key: Option<KeyOrRef<'b, K, Q>>,
4752 elem: Bucket<(K, V)>,
4753 table: &'a mut HashMap<K, V, S, A>,
4754}
4755
4756unsafe impl<'a, 'b, K, Q, V, S, A> Send for OccupiedEntryRef<'a, 'b, K, Q, V, S, A>
4757where
4758 K: Send,
4759 Q: Sync + ?Sized,
4760 V: Send,
4761 S: Send,
4762 A: Send + Allocator,
4763{
4764}
4765unsafe impl<'a, 'b, K, Q, V, S, A> Sync for OccupiedEntryRef<'a, 'b, K, Q, V, S, A>
4766where
4767 K: Sync,
4768 Q: Sync + ?Sized,
4769 V: Sync,
4770 S: Sync,
4771 A: Sync + Allocator,
4772{
4773}
4774
4775impl<K: Borrow<Q>, Q: ?Sized + Debug, V: Debug, S, A: Allocator> Debug
4776 for OccupiedEntryRef<'_, '_, K, Q, V, S, A>
4777{
4778 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
4779 f.debug_struct("OccupiedEntryRef")
4780 .field("key", &self.key().borrow())
4781 .field("value", &self.get())
4782 .finish()
4783 }
4784}
4785
4786/// A view into a vacant entry in a `HashMap`.
4787/// It is part of the [`EntryRef`] enum.
4788///
4789/// [`EntryRef`]: enum.EntryRef.html
4790///
4791/// # Examples
4792///
4793/// ```
4794/// use rune::alloc::hash_map::{EntryRef, HashMap, VacantEntryRef};
4795///
4796/// let mut map = HashMap::<String, i32>::new();
4797///
4798/// let entry_v: VacantEntryRef<_, _, _, _> = match map.entry_ref("a") {
4799/// EntryRef::Vacant(view) => view,
4800/// EntryRef::Occupied(_) => unreachable!(),
4801/// };
4802/// entry_v.try_insert(10)?;
4803/// assert!(map["a"] == 10 && map.len() == 1);
4804///
4805/// // Nonexistent key (insert and update)
4806/// match map.entry_ref("b") {
4807/// EntryRef::Occupied(_) => unreachable!(),
4808/// EntryRef::Vacant(view) => {
4809/// let value = view.try_insert(2)?;
4810/// assert_eq!(*value, 2);
4811/// *value = 20;
4812/// }
4813/// }
4814/// assert!(map["b"] == 20 && map.len() == 2);
4815/// # Ok::<_, rune::alloc::Error>(())
4816/// ```
4817pub struct VacantEntryRef<'a, 'b, K, Q: ?Sized, V, S, A: Allocator = Global> {
4818 hash: u64,
4819 key: KeyOrRef<'b, K, Q>,
4820 table: &'a mut HashMap<K, V, S, A>,
4821}
4822
4823impl<K: Borrow<Q>, Q: ?Sized + Debug, V, S, A: Allocator> Debug
4824 for VacantEntryRef<'_, '_, K, Q, V, S, A>
4825{
4826 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
4827 f.debug_tuple("VacantEntryRef").field(&self.key()).finish()
4828 }
4829}
4830
4831/// The error returned by [`try_insert`](HashMap::try_insert) when the key already exists.
4832///
4833/// Contains the occupied entry, and the value that was not inserted.
4834///
4835/// # Examples
4836///
4837/// ```
4838/// use rune::alloc::hash_map::{HashMap, OccupiedError};
4839/// use rune::alloc::error::CustomError;
4840///
4841/// let mut map: HashMap<_, _> = [("a", 10), ("b", 20)].try_into()?;
4842///
4843/// // try_insert method returns mutable reference to the value if keys are vacant,
4844/// // but if the map did have key present, nothing is updated, and the provided
4845/// // value is returned inside `Err(_)` variant
4846/// match map.try_insert_or("a", 100) {
4847/// Err(CustomError::Custom(OccupiedError { mut entry, value })) => {
4848/// assert_eq!(entry.key(), &"a");
4849/// assert_eq!(value, 100);
4850/// assert_eq!(entry.insert(100), 10)
4851/// }
4852/// _ => unreachable!(),
4853/// }
4854/// assert_eq!(map[&"a"], 100);
4855/// # Ok::<_, rune::alloc::Error>(())
4856/// ```
4857pub struct OccupiedError<'a, K, V, S, A: Allocator = Global> {
4858 /// The entry in the map that was already occupied.
4859 pub entry: OccupiedEntry<'a, K, V, S, A>,
4860 /// The value which was not inserted, because the entry was already occupied.
4861 pub value: V,
4862}
4863
4864impl<K: Debug, V: Debug, S, A: Allocator> Debug for OccupiedError<'_, K, V, S, A> {
4865 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
4866 f.debug_struct("OccupiedError")
4867 .field("key", self.entry.key())
4868 .field("old_value", self.entry.get())
4869 .field("new_value", &self.value)
4870 .finish()
4871 }
4872}
4873
4874impl<'a, K: Debug, V: Debug, S, A: Allocator> fmt::Display for OccupiedError<'a, K, V, S, A> {
4875 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
4876 write!(
4877 f,
4878 "failed to insert {:?}, key {:?} already exists with value {:?}",
4879 self.value,
4880 self.entry.key(),
4881 self.entry.get(),
4882 )
4883 }
4884}
4885
4886impl<'a, K, V, S, A: Allocator> IntoIterator for &'a HashMap<K, V, S, A> {
4887 type Item = (&'a K, &'a V);
4888 type IntoIter = Iter<'a, K, V>;
4889
4890 /// Creates an iterator over the entries of a `HashMap` in arbitrary order.
4891 /// The iterator element type is `(&'a K, &'a V)`.
4892 ///
4893 /// Return the same `Iter` struct as by the [`iter`] method on [`HashMap`].
4894 ///
4895 /// [`iter`]: struct.HashMap.html#method.iter
4896 /// [`HashMap`]: struct.HashMap.html
4897 ///
4898 /// # Examples
4899 ///
4900 /// ```
4901 /// use rune::alloc::HashMap;
4902 /// let map_one: HashMap<_, _> = [(1, "a"), (2, "b"), (3, "c")].try_into()?;
4903 /// let mut map_two = HashMap::new();
4904 ///
4905 /// for (key, value) in &map_one {
4906 /// println!("Key: {}, Value: {}", key, value);
4907 /// map_two.try_insert_unique_unchecked(*key, *value)?;
4908 /// }
4909 ///
4910 /// assert_eq!(map_one, map_two);
4911 /// # Ok::<_, rune::alloc::Error>(())
4912 /// ```
4913 #[cfg_attr(feature = "inline-more", inline)]
4914 fn into_iter(self) -> Iter<'a, K, V> {
4915 self.iter()
4916 }
4917}
4918
4919impl<'a, K, V, S, A: Allocator> IntoIterator for &'a mut HashMap<K, V, S, A> {
4920 type Item = (&'a K, &'a mut V);
4921 type IntoIter = IterMut<'a, K, V>;
4922
4923 /// Creates an iterator over the entries of a `HashMap` in arbitrary order
4924 /// with mutable references to the values. The iterator element type is
4925 /// `(&'a K, &'a mut V)`.
4926 ///
4927 /// Return the same `IterMut` struct as by the [`iter_mut`] method on
4928 /// [`HashMap`].
4929 ///
4930 /// [`iter_mut`]: struct.HashMap.html#method.iter_mut
4931 /// [`HashMap`]: struct.HashMap.html
4932 ///
4933 /// # Examples
4934 ///
4935 /// ```
4936 /// use rune::alloc::HashMap;
4937 /// let mut map: HashMap<_, _> = [("a", 1), ("b", 2), ("c", 3)].try_into()?;
4938 ///
4939 /// for (key, value) in &mut map {
4940 /// println!("Key: {}, Value: {}", key, value);
4941 /// *value *= 2;
4942 /// }
4943 ///
4944 /// let mut vec = map.iter().collect::<Vec<_>>();
4945 /// // The `Iter` iterator produces items in arbitrary order, so the
4946 /// // items must be sorted to test them against a sorted array.
4947 /// vec.sort_unstable();
4948 /// assert_eq!(vec, [(&"a", &2), (&"b", &4), (&"c", &6)]);
4949 /// # Ok::<_, rune::alloc::Error>(())
4950 /// ```
4951 #[cfg_attr(feature = "inline-more", inline)]
4952 fn into_iter(self) -> IterMut<'a, K, V> {
4953 self.iter_mut()
4954 }
4955}
4956
4957impl<K, V, S, A: Allocator> IntoIterator for HashMap<K, V, S, A> {
4958 type Item = (K, V);
4959 type IntoIter = IntoIter<K, V, A>;
4960
4961 /// Creates a consuming iterator, that is, one that moves each key-value
4962 /// pair out of the map in arbitrary order. The map cannot be used after
4963 /// calling this.
4964 ///
4965 /// # Examples
4966 ///
4967 /// ```
4968 /// use rune::alloc::HashMap;
4969 ///
4970 /// let map: HashMap<_, _> = [("a", 1), ("b", 2), ("c", 3)].try_into()?;
4971 ///
4972 /// // Not possible with .iter()
4973 /// let mut vec: Vec<(&str, i32)> = map.into_iter().collect();
4974 /// // The `IntoIter` iterator produces items in arbitrary order, so
4975 /// // the items must be sorted to test them against a sorted array.
4976 /// vec.sort_unstable();
4977 /// assert_eq!(vec, [("a", 1), ("b", 2), ("c", 3)]);
4978 /// # Ok::<_, rune::alloc::Error>(())
4979 /// ```
4980 #[cfg_attr(feature = "inline-more", inline)]
4981 fn into_iter(self) -> IntoIter<K, V, A> {
4982 IntoIter {
4983 inner: self.table.into_iter(),
4984 }
4985 }
4986}
4987
4988impl<'a, K, V> Iterator for Iter<'a, K, V> {
4989 type Item = (&'a K, &'a V);
4990
4991 #[cfg_attr(feature = "inline-more", inline)]
4992 fn next(&mut self) -> Option<(&'a K, &'a V)> {
4993 // Avoid `Option::map` because it bloats LLVM IR.
4994 match self.inner.next() {
4995 Some(x) => unsafe {
4996 let r = x.as_ref();
4997 Some((&r.0, &r.1))
4998 },
4999 None => None,
5000 }
5001 }
5002 #[cfg_attr(feature = "inline-more", inline)]
5003 fn size_hint(&self) -> (usize, Option<usize>) {
5004 self.inner.size_hint()
5005 }
5006}
5007impl<K, V> ExactSizeIterator for Iter<'_, K, V> {
5008 #[cfg_attr(feature = "inline-more", inline)]
5009 fn len(&self) -> usize {
5010 self.inner.len()
5011 }
5012}
5013
5014impl<K, V> FusedIterator for Iter<'_, K, V> {}
5015
5016impl<'a, K, V> Iterator for IterMut<'a, K, V> {
5017 type Item = (&'a K, &'a mut V);
5018
5019 #[cfg_attr(feature = "inline-more", inline)]
5020 fn next(&mut self) -> Option<(&'a K, &'a mut V)> {
5021 // Avoid `Option::map` because it bloats LLVM IR.
5022 match self.inner.next() {
5023 Some(x) => unsafe {
5024 let r = x.as_mut();
5025 Some((&r.0, &mut r.1))
5026 },
5027 None => None,
5028 }
5029 }
5030 #[cfg_attr(feature = "inline-more", inline)]
5031 fn size_hint(&self) -> (usize, Option<usize>) {
5032 self.inner.size_hint()
5033 }
5034}
5035impl<K, V> ExactSizeIterator for IterMut<'_, K, V> {
5036 #[cfg_attr(feature = "inline-more", inline)]
5037 fn len(&self) -> usize {
5038 self.inner.len()
5039 }
5040}
5041impl<K, V> FusedIterator for IterMut<'_, K, V> {}
5042
5043impl<K, V> fmt::Debug for IterMut<'_, K, V>
5044where
5045 K: fmt::Debug,
5046 V: fmt::Debug,
5047{
5048 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
5049 f.debug_list().entries(self.iter()).finish()
5050 }
5051}
5052
5053impl<K, V, A: Allocator> Iterator for IntoIter<K, V, A> {
5054 type Item = (K, V);
5055
5056 #[cfg_attr(feature = "inline-more", inline)]
5057 fn next(&mut self) -> Option<(K, V)> {
5058 self.inner.next()
5059 }
5060 #[cfg_attr(feature = "inline-more", inline)]
5061 fn size_hint(&self) -> (usize, Option<usize>) {
5062 self.inner.size_hint()
5063 }
5064}
5065impl<K, V, A: Allocator> ExactSizeIterator for IntoIter<K, V, A> {
5066 #[cfg_attr(feature = "inline-more", inline)]
5067 fn len(&self) -> usize {
5068 self.inner.len()
5069 }
5070}
5071impl<K, V, A: Allocator> FusedIterator for IntoIter<K, V, A> {}
5072
5073impl<K: Debug, V: Debug, A: Allocator> fmt::Debug for IntoIter<K, V, A> {
5074 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
5075 f.debug_list().entries(self.iter()).finish()
5076 }
5077}
5078
5079impl<'a, K, V> Iterator for Keys<'a, K, V> {
5080 type Item = &'a K;
5081
5082 #[cfg_attr(feature = "inline-more", inline)]
5083 fn next(&mut self) -> Option<&'a K> {
5084 // Avoid `Option::map` because it bloats LLVM IR.
5085 match self.inner.next() {
5086 Some((k, _)) => Some(k),
5087 None => None,
5088 }
5089 }
5090 #[cfg_attr(feature = "inline-more", inline)]
5091 fn size_hint(&self) -> (usize, Option<usize>) {
5092 self.inner.size_hint()
5093 }
5094}
5095impl<K, V> ExactSizeIterator for Keys<'_, K, V> {
5096 #[cfg_attr(feature = "inline-more", inline)]
5097 fn len(&self) -> usize {
5098 self.inner.len()
5099 }
5100}
5101impl<K, V> FusedIterator for Keys<'_, K, V> {}
5102
5103impl<'a, K, V> Iterator for Values<'a, K, V> {
5104 type Item = &'a V;
5105
5106 #[cfg_attr(feature = "inline-more", inline)]
5107 fn next(&mut self) -> Option<&'a V> {
5108 // Avoid `Option::map` because it bloats LLVM IR.
5109 match self.inner.next() {
5110 Some((_, v)) => Some(v),
5111 None => None,
5112 }
5113 }
5114 #[cfg_attr(feature = "inline-more", inline)]
5115 fn size_hint(&self) -> (usize, Option<usize>) {
5116 self.inner.size_hint()
5117 }
5118}
5119impl<K, V> ExactSizeIterator for Values<'_, K, V> {
5120 #[cfg_attr(feature = "inline-more", inline)]
5121 fn len(&self) -> usize {
5122 self.inner.len()
5123 }
5124}
5125impl<K, V> FusedIterator for Values<'_, K, V> {}
5126
5127impl<'a, K, V> Iterator for ValuesMut<'a, K, V> {
5128 type Item = &'a mut V;
5129
5130 #[cfg_attr(feature = "inline-more", inline)]
5131 fn next(&mut self) -> Option<&'a mut V> {
5132 // Avoid `Option::map` because it bloats LLVM IR.
5133 match self.inner.next() {
5134 Some((_, v)) => Some(v),
5135 None => None,
5136 }
5137 }
5138 #[cfg_attr(feature = "inline-more", inline)]
5139 fn size_hint(&self) -> (usize, Option<usize>) {
5140 self.inner.size_hint()
5141 }
5142}
5143impl<K, V> ExactSizeIterator for ValuesMut<'_, K, V> {
5144 #[cfg_attr(feature = "inline-more", inline)]
5145 fn len(&self) -> usize {
5146 self.inner.len()
5147 }
5148}
5149impl<K, V> FusedIterator for ValuesMut<'_, K, V> {}
5150
5151impl<K, V: Debug> fmt::Debug for ValuesMut<'_, K, V> {
5152 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
5153 f.debug_list()
5154 .entries(self.inner.iter().map(|(_, val)| val))
5155 .finish()
5156 }
5157}
5158
5159impl<'a, K, V, A: Allocator> Iterator for Drain<'a, K, V, A> {
5160 type Item = (K, V);
5161
5162 #[cfg_attr(feature = "inline-more", inline)]
5163 fn next(&mut self) -> Option<(K, V)> {
5164 self.inner.next()
5165 }
5166 #[cfg_attr(feature = "inline-more", inline)]
5167 fn size_hint(&self) -> (usize, Option<usize>) {
5168 self.inner.size_hint()
5169 }
5170}
5171impl<K, V, A: Allocator> ExactSizeIterator for Drain<'_, K, V, A> {
5172 #[cfg_attr(feature = "inline-more", inline)]
5173 fn len(&self) -> usize {
5174 self.inner.len()
5175 }
5176}
5177impl<K, V, A: Allocator> FusedIterator for Drain<'_, K, V, A> {}
5178
5179impl<K, V, A> fmt::Debug for Drain<'_, K, V, A>
5180where
5181 K: fmt::Debug,
5182 V: fmt::Debug,
5183 A: Allocator,
5184{
5185 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
5186 f.debug_list().entries(self.iter()).finish()
5187 }
5188}
5189
5190impl<'a, K, V, S, A: Allocator> Entry<'a, K, V, S, A> {
5191 /// Sets the value of the entry, and returns an OccupiedEntry.
5192 ///
5193 /// # Examples
5194 ///
5195 /// ```
5196 /// use rune::alloc::HashMap;
5197 ///
5198 /// let mut map: HashMap<&str, u32> = HashMap::new();
5199 /// let entry = map.entry("horseyland").try_insert(37)?;
5200 ///
5201 /// assert_eq!(entry.key(), &"horseyland");
5202 /// # Ok::<_, rune::alloc::Error>(())
5203 /// ```
5204 #[cfg_attr(feature = "inline-more", inline)]
5205 pub fn try_insert(self, value: V) -> Result<OccupiedEntry<'a, K, V, S, A>, Error>
5206 where
5207 K: Hash,
5208 S: BuildHasher,
5209 {
5210 match self {
5211 Entry::Occupied(mut entry) => {
5212 entry.insert(value);
5213 Ok(entry)
5214 }
5215 Entry::Vacant(entry) => entry.try_insert_entry(value),
5216 }
5217 }
5218
5219 #[cfg(test)]
5220 pub(crate) fn insert(self, value: V) -> OccupiedEntry<'a, K, V, S, A>
5221 where
5222 K: Hash,
5223 S: BuildHasher,
5224 {
5225 self.try_insert(value).abort()
5226 }
5227
5228 /// Ensures a value is in the entry by inserting the default if empty, and returns
5229 /// a mutable reference to the value in the entry.
5230 ///
5231 /// # Examples
5232 ///
5233 /// ```
5234 /// use rune::alloc::HashMap;
5235 ///
5236 /// let mut map: HashMap<&str, u32> = HashMap::new();
5237 ///
5238 /// // nonexistent key
5239 /// map.entry("poneyland").or_try_insert(3)?;
5240 /// assert_eq!(map["poneyland"], 3);
5241 ///
5242 /// // existing key
5243 /// *map.entry("poneyland").or_try_insert(10)? *= 2;
5244 /// assert_eq!(map["poneyland"], 6);
5245 /// # Ok::<_, rune::alloc::Error>(())
5246 /// ```
5247 #[cfg_attr(feature = "inline-more", inline)]
5248 pub fn or_try_insert(self, default: V) -> Result<&'a mut V, Error>
5249 where
5250 K: Hash,
5251 S: BuildHasher,
5252 {
5253 match self {
5254 Entry::Occupied(entry) => Ok(entry.into_mut()),
5255 Entry::Vacant(entry) => entry.try_insert(default),
5256 }
5257 }
5258
5259 #[cfg(test)]
5260 pub(crate) fn or_insert(self, default: V) -> &'a mut V
5261 where
5262 K: Hash,
5263 S: BuildHasher,
5264 {
5265 self.or_try_insert(default).abort()
5266 }
5267
5268 /// Ensures a value is in the entry by inserting the result of the default function if empty,
5269 /// and returns a mutable reference to the value in the entry.
5270 ///
5271 /// # Examples
5272 ///
5273 /// ```
5274 /// use rune::alloc::HashMap;
5275 ///
5276 /// let mut map: HashMap<&str, u32> = HashMap::new();
5277 ///
5278 /// // nonexistent key
5279 /// map.entry("poneyland").or_try_insert_with(|| 3)?;
5280 /// assert_eq!(map["poneyland"], 3);
5281 ///
5282 /// // existing key
5283 /// *map.entry("poneyland").or_try_insert_with(|| 10)? *= 2;
5284 /// assert_eq!(map["poneyland"], 6);
5285 /// # Ok::<_, rune::alloc::Error>(())
5286 /// ```
5287 #[cfg_attr(feature = "inline-more", inline)]
5288 pub fn or_try_insert_with<F>(self, default: F) -> Result<&'a mut V, Error>
5289 where
5290 K: Hash,
5291 S: BuildHasher,
5292 F: FnOnce() -> V,
5293 {
5294 match self {
5295 Entry::Occupied(entry) => Ok(entry.into_mut()),
5296 Entry::Vacant(entry) => entry.try_insert(default()),
5297 }
5298 }
5299
5300 /// Ensures a value is in the entry by inserting, if empty, the result of
5301 /// the default function. This method allows for generating key-derived
5302 /// values for insertion by providing the default function a reference to
5303 /// the key that was moved during the `.entry(key)` method call.
5304 ///
5305 /// The reference to the moved key is provided so that cloning or copying
5306 /// the key is unnecessary, unlike with `.or_insert_with(|| ... )`.
5307 ///
5308 /// # Examples
5309 ///
5310 /// ```
5311 /// use rune::alloc::HashMap;
5312 ///
5313 /// let mut map: HashMap<&str, usize> = HashMap::new();
5314 ///
5315 /// // nonexistent key
5316 /// map.entry("poneyland").or_try_insert_with_key(|key| key.chars().count())?;
5317 /// assert_eq!(map["poneyland"], 9);
5318 ///
5319 /// // existing key
5320 /// *map.entry("poneyland").or_try_insert_with_key(|key| key.chars().count() * 10)? *= 2;
5321 /// assert_eq!(map["poneyland"], 18);
5322 /// # Ok::<_, rune::alloc::Error>(())
5323 /// ```
5324 #[cfg_attr(feature = "inline-more", inline)]
5325 pub fn or_try_insert_with_key<F>(self, default: F) -> Result<&'a mut V, Error>
5326 where
5327 K: Hash,
5328 S: BuildHasher,
5329 F: FnOnce(&K) -> V,
5330 {
5331 match self {
5332 Entry::Occupied(entry) => Ok(entry.into_mut()),
5333 Entry::Vacant(entry) => {
5334 let value = default(entry.key());
5335 entry.try_insert(value)
5336 }
5337 }
5338 }
5339
5340 /// Returns a reference to this entry's key.
5341 ///
5342 /// # Examples
5343 ///
5344 /// ```
5345 /// use rune::alloc::HashMap;
5346 ///
5347 /// let mut map: HashMap<&str, u32> = HashMap::new();
5348 /// map.entry("poneyland").or_try_insert(3)?;
5349 /// // existing key
5350 /// assert_eq!(map.entry("poneyland").key(), &"poneyland");
5351 /// // nonexistent key
5352 /// assert_eq!(map.entry("horseland").key(), &"horseland");
5353 /// # Ok::<_, rune::alloc::Error>(())
5354 /// ```
5355 #[cfg_attr(feature = "inline-more", inline)]
5356 pub fn key(&self) -> &K {
5357 match *self {
5358 Entry::Occupied(ref entry) => entry.key(),
5359 Entry::Vacant(ref entry) => entry.key(),
5360 }
5361 }
5362
5363 /// Provides in-place mutable access to an occupied entry before any
5364 /// potential inserts into the map.
5365 ///
5366 /// # Examples
5367 ///
5368 /// ```
5369 /// use rune::alloc::HashMap;
5370 ///
5371 /// let mut map: HashMap<&str, u32> = HashMap::new();
5372 ///
5373 /// map.entry("poneyland")
5374 /// .and_modify(|e| { *e += 1 })
5375 /// .or_try_insert(42);
5376 /// assert_eq!(map["poneyland"], 42);
5377 ///
5378 /// map.entry("poneyland")
5379 /// .and_modify(|e| { *e += 1 })
5380 /// .or_try_insert(42);
5381 /// assert_eq!(map["poneyland"], 43);
5382 /// # Ok::<_, rune::alloc::Error>(())
5383 /// ```
5384 #[cfg_attr(feature = "inline-more", inline)]
5385 pub fn and_modify<F>(self, f: F) -> Self
5386 where
5387 F: FnOnce(&mut V),
5388 {
5389 match self {
5390 Entry::Occupied(mut entry) => {
5391 f(entry.get_mut());
5392 Entry::Occupied(entry)
5393 }
5394 Entry::Vacant(entry) => Entry::Vacant(entry),
5395 }
5396 }
5397
5398 /// Provides shared access to the key and owned access to the value of
5399 /// an occupied entry and allows to replace or remove it based on the
5400 /// value of the returned option.
5401 ///
5402 /// # Examples
5403 ///
5404 /// ```
5405 /// use rune::alloc::HashMap;
5406 /// use rune::alloc::hash_map::Entry;
5407 ///
5408 /// let mut map: HashMap<&str, u32> = HashMap::new();
5409 ///
5410 /// let entry = map
5411 /// .entry("poneyland")
5412 /// .and_replace_entry_with(|_k, _v| panic!());
5413 ///
5414 /// match entry {
5415 /// Entry::Vacant(e) => {
5416 /// assert_eq!(e.key(), &"poneyland");
5417 /// }
5418 /// Entry::Occupied(_) => panic!(),
5419 /// }
5420 ///
5421 /// map.try_insert("poneyland", 42)?;
5422 ///
5423 /// let entry = map
5424 /// .entry("poneyland")
5425 /// .and_replace_entry_with(|k, v| {
5426 /// assert_eq!(k, &"poneyland");
5427 /// assert_eq!(v, 42);
5428 /// Some(v + 1)
5429 /// });
5430 ///
5431 /// match entry {
5432 /// Entry::Occupied(e) => {
5433 /// assert_eq!(e.key(), &"poneyland");
5434 /// assert_eq!(e.get(), &43);
5435 /// }
5436 /// Entry::Vacant(_) => panic!(),
5437 /// }
5438 ///
5439 /// assert_eq!(map["poneyland"], 43);
5440 ///
5441 /// let entry = map
5442 /// .entry("poneyland")
5443 /// .and_replace_entry_with(|_k, _v| None);
5444 ///
5445 /// match entry {
5446 /// Entry::Vacant(e) => assert_eq!(e.key(), &"poneyland"),
5447 /// Entry::Occupied(_) => panic!(),
5448 /// }
5449 ///
5450 /// assert!(!map.contains_key("poneyland"));
5451 /// # Ok::<_, rune::alloc::Error>(())
5452 /// ```
5453 #[cfg_attr(feature = "inline-more", inline)]
5454 pub fn and_replace_entry_with<F>(self, f: F) -> Self
5455 where
5456 F: FnOnce(&K, V) -> Option<V>,
5457 {
5458 match self {
5459 Entry::Occupied(entry) => entry.replace_entry_with(f),
5460 Entry::Vacant(_) => self,
5461 }
5462 }
5463}
5464
5465impl<'a, K, V: Default, S, A: Allocator> Entry<'a, K, V, S, A> {
5466 /// Ensures a value is in the entry by inserting the default value if empty,
5467 /// and returns a mutable reference to the value in the entry.
5468 ///
5469 /// # Examples
5470 ///
5471 /// ```
5472 /// use rune::alloc::HashMap;
5473 ///
5474 /// let mut map: HashMap<&str, Option<u32>> = HashMap::new();
5475 ///
5476 /// // nonexistent key
5477 /// map.entry("poneyland").or_try_default()?;
5478 /// assert_eq!(map["poneyland"], None);
5479 ///
5480 /// map.try_insert("horseland", Some(3))?;
5481 ///
5482 /// // existing key
5483 /// assert_eq!(map.entry("horseland").or_try_default()?, &mut Some(3));
5484 /// # Ok::<_, rune::alloc::Error>(())
5485 /// ```
5486 #[cfg_attr(feature = "inline-more", inline)]
5487 pub fn or_try_default(self) -> Result<&'a mut V, Error>
5488 where
5489 K: Hash,
5490 S: BuildHasher,
5491 {
5492 match self {
5493 Entry::Occupied(entry) => Ok(entry.into_mut()),
5494 Entry::Vacant(entry) => entry.try_insert(Default::default()),
5495 }
5496 }
5497}
5498
5499impl<'a, K, V, S, A: Allocator> OccupiedEntry<'a, K, V, S, A> {
5500 /// Gets a reference to the key in the entry.
5501 ///
5502 /// # Examples
5503 ///
5504 /// ```
5505 /// use rune::alloc::HashMap;
5506 /// use rune::alloc::hash_map::{Entry};
5507 ///
5508 /// let mut map: HashMap<&str, u32> = HashMap::new();
5509 /// map.entry("poneyland").or_try_insert(12)?;
5510 ///
5511 /// match map.entry("poneyland") {
5512 /// Entry::Vacant(_) => panic!(),
5513 /// Entry::Occupied(entry) => assert_eq!(entry.key(), &"poneyland"),
5514 /// }
5515 /// # Ok::<_, rune::alloc::Error>(())
5516 /// ```
5517 #[cfg_attr(feature = "inline-more", inline)]
5518 pub fn key(&self) -> &K {
5519 unsafe { &self.elem.as_ref().0 }
5520 }
5521
5522 /// Take the ownership of the key and value from the map.
5523 /// Keeps the allocated memory for reuse.
5524 ///
5525 /// # Examples
5526 ///
5527 /// ```
5528 /// use rune::alloc::HashMap;
5529 /// use rune::alloc::hash_map::Entry;
5530 ///
5531 /// let mut map: HashMap<&str, u32> = HashMap::new();
5532 /// // The map is empty
5533 /// assert!(map.is_empty() && map.capacity() == 0);
5534 ///
5535 /// map.entry("poneyland").or_try_insert(12)?;
5536 ///
5537 /// if let Entry::Occupied(o) = map.entry("poneyland") {
5538 /// // We delete the entry from the map.
5539 /// assert_eq!(o.remove_entry(), ("poneyland", 12));
5540 /// }
5541 ///
5542 /// assert_eq!(map.contains_key("poneyland"), false);
5543 /// // Now map hold none elements
5544 /// assert!(map.is_empty());
5545 /// # Ok::<_, rune::alloc::Error>(())
5546 /// ```
5547 #[cfg_attr(feature = "inline-more", inline)]
5548 pub fn remove_entry(self) -> (K, V) {
5549 unsafe { self.table.table.remove(self.elem).0 }
5550 }
5551
5552 /// Gets a reference to the value in the entry.
5553 ///
5554 /// # Examples
5555 ///
5556 /// ```
5557 /// use rune::alloc::HashMap;
5558 /// use rune::alloc::hash_map::Entry;
5559 ///
5560 /// let mut map: HashMap<&str, u32> = HashMap::new();
5561 /// map.entry("poneyland").or_try_insert(12)?;
5562 ///
5563 /// match map.entry("poneyland") {
5564 /// Entry::Vacant(_) => panic!(),
5565 /// Entry::Occupied(entry) => assert_eq!(entry.get(), &12),
5566 /// }
5567 /// # Ok::<_, rune::alloc::Error>(())
5568 /// ```
5569 #[cfg_attr(feature = "inline-more", inline)]
5570 pub fn get(&self) -> &V {
5571 unsafe { &self.elem.as_ref().1 }
5572 }
5573
5574 /// Gets a mutable reference to the value in the entry.
5575 ///
5576 /// If you need a reference to the `OccupiedEntry` which may outlive the
5577 /// destruction of the `Entry` value, see [`into_mut`].
5578 ///
5579 /// [`into_mut`]: #method.into_mut
5580 ///
5581 /// # Examples
5582 ///
5583 /// ```
5584 /// use rune::alloc::HashMap;
5585 /// use rune::alloc::hash_map::Entry;
5586 ///
5587 /// let mut map: HashMap<&str, u32> = HashMap::new();
5588 /// map.entry("poneyland").or_try_insert(12)?;
5589 ///
5590 /// assert_eq!(map["poneyland"], 12);
5591 /// if let Entry::Occupied(mut o) = map.entry("poneyland") {
5592 /// *o.get_mut() += 10;
5593 /// assert_eq!(*o.get(), 22);
5594 ///
5595 /// // We can use the same Entry multiple times.
5596 /// *o.get_mut() += 2;
5597 /// }
5598 ///
5599 /// assert_eq!(map["poneyland"], 24);
5600 /// # Ok::<_, rune::alloc::Error>(())
5601 /// ```
5602 #[cfg_attr(feature = "inline-more", inline)]
5603 pub fn get_mut(&mut self) -> &mut V {
5604 unsafe { &mut self.elem.as_mut().1 }
5605 }
5606
5607 /// Converts the OccupiedEntry into a mutable reference to the value in the entry
5608 /// with a lifetime bound to the map itself.
5609 ///
5610 /// If you need multiple references to the `OccupiedEntry`, see [`get_mut`].
5611 ///
5612 /// [`get_mut`]: #method.get_mut
5613 ///
5614 /// # Examples
5615 ///
5616 /// ```
5617 /// use rune::alloc::HashMap;
5618 /// use rune::alloc::hash_map::Entry;
5619 ///
5620 /// let mut map: HashMap<&str, u32> = HashMap::new();
5621 /// map.entry("poneyland").or_try_insert(12)?;
5622 ///
5623 /// assert_eq!(map["poneyland"], 12);
5624 ///
5625 /// let value: &mut u32;
5626 /// match map.entry("poneyland") {
5627 /// Entry::Occupied(entry) => value = entry.into_mut(),
5628 /// Entry::Vacant(_) => panic!(),
5629 /// }
5630 /// *value += 10;
5631 ///
5632 /// assert_eq!(map["poneyland"], 22);
5633 /// # Ok::<_, rune::alloc::Error>(())
5634 /// ```
5635 #[cfg_attr(feature = "inline-more", inline)]
5636 pub fn into_mut(self) -> &'a mut V {
5637 unsafe { &mut self.elem.as_mut().1 }
5638 }
5639
5640 /// Sets the value of the entry, and returns the entry's old value.
5641 ///
5642 /// # Examples
5643 ///
5644 /// ```
5645 /// use rune::alloc::HashMap;
5646 /// use rune::alloc::hash_map::Entry;
5647 ///
5648 /// let mut map: HashMap<&str, u32> = HashMap::new();
5649 /// map.entry("poneyland").or_try_insert(12)?;
5650 ///
5651 /// if let Entry::Occupied(mut o) = map.entry("poneyland") {
5652 /// assert_eq!(o.insert(15), 12);
5653 /// }
5654 ///
5655 /// assert_eq!(map["poneyland"], 15);
5656 /// # Ok::<_, rune::alloc::Error>(())
5657 /// ```
5658 #[cfg_attr(feature = "inline-more", inline)]
5659 pub fn insert(&mut self, value: V) -> V {
5660 mem::replace(self.get_mut(), value)
5661 }
5662
5663 /// Takes the value out of the entry, and returns it.
5664 /// Keeps the allocated memory for reuse.
5665 ///
5666 /// # Examples
5667 ///
5668 /// ```
5669 /// use rune::alloc::HashMap;
5670 /// use rune::alloc::hash_map::Entry;
5671 ///
5672 /// let mut map: HashMap<&str, u32> = HashMap::new();
5673 /// // The map is empty
5674 /// assert!(map.is_empty() && map.capacity() == 0);
5675 ///
5676 /// map.entry("poneyland").or_try_insert(12)?;
5677 ///
5678 /// if let Entry::Occupied(o) = map.entry("poneyland") {
5679 /// assert_eq!(o.remove(), 12);
5680 /// }
5681 ///
5682 /// assert_eq!(map.contains_key("poneyland"), false);
5683 /// // Now map hold none elements
5684 /// assert!(map.is_empty());
5685 /// # Ok::<_, rune::alloc::Error>(())
5686 /// ```
5687 #[cfg_attr(feature = "inline-more", inline)]
5688 pub fn remove(self) -> V {
5689 self.remove_entry().1
5690 }
5691
5692 /// Replaces the entry, returning the old key and value. The new key in the hash map will be
5693 /// the key used to create this entry.
5694 ///
5695 /// # Panics
5696 ///
5697 /// Will panic if this OccupiedEntry was created through [`Entry::try_insert`].
5698 ///
5699 /// # Examples
5700 ///
5701 /// ```
5702 /// use rune::alloc::HashMap;
5703 /// use rune::alloc::hash_map::Entry;
5704 /// use std::rc::Rc;
5705 ///
5706 /// let mut map: HashMap<Rc<String>, u32> = HashMap::new();
5707 /// let key_one = Rc::new("Stringthing".to_string());
5708 /// let key_two = Rc::new("Stringthing".to_string());
5709 ///
5710 /// map.try_insert(key_one.clone(), 15)?;
5711 /// assert!(Rc::strong_count(&key_one) == 2 && Rc::strong_count(&key_two) == 1);
5712 ///
5713 /// match map.entry(key_two.clone()) {
5714 /// Entry::Occupied(entry) => {
5715 /// let (old_key, old_value): (Rc<String>, u32) = entry.replace_entry(16);
5716 /// assert!(Rc::ptr_eq(&key_one, &old_key) && old_value == 15);
5717 /// }
5718 /// Entry::Vacant(_) => panic!(),
5719 /// }
5720 ///
5721 /// assert!(Rc::strong_count(&key_one) == 1 && Rc::strong_count(&key_two) == 2);
5722 /// assert_eq!(map[&"Stringthing".to_owned()], 16);
5723 /// # Ok::<_, rune::alloc::Error>(())
5724 /// ```
5725 #[cfg_attr(feature = "inline-more", inline)]
5726 pub fn replace_entry(self, value: V) -> (K, V) {
5727 let entry = unsafe { self.elem.as_mut() };
5728
5729 let old_key = mem::replace(&mut entry.0, self.key.unwrap());
5730 let old_value = mem::replace(&mut entry.1, value);
5731
5732 (old_key, old_value)
5733 }
5734
5735 /// Replaces the key in the hash map with the key used to create this entry.
5736 ///
5737 /// # Panics
5738 ///
5739 /// Will panic if this OccupiedEntry was created through [`Entry::try_insert`].
5740 ///
5741 /// # Examples
5742 ///
5743 /// ```
5744 /// use rune::alloc::hash_map::{Entry, HashMap};
5745 /// use std::rc::Rc;
5746 ///
5747 /// let mut map: HashMap<Rc<String>, usize> = HashMap::try_with_capacity(6)?;
5748 /// let mut keys_one: Vec<Rc<String>> = Vec::with_capacity(6);
5749 /// let mut keys_two: Vec<Rc<String>> = Vec::with_capacity(6);
5750 ///
5751 /// for (value, key) in ["a", "b", "c", "d", "e", "f"].into_iter().enumerate() {
5752 /// let rc_key = Rc::new(key.to_owned());
5753 /// keys_one.push(rc_key.clone());
5754 /// map.try_insert(rc_key.clone(), value)?;
5755 /// keys_two.push(Rc::new(key.to_owned()));
5756 /// }
5757 ///
5758 /// assert!(
5759 /// keys_one.iter().all(|key| Rc::strong_count(key) == 2)
5760 /// && keys_two.iter().all(|key| Rc::strong_count(key) == 1)
5761 /// );
5762 ///
5763 /// reclaim_memory(&mut map, &keys_two);
5764 ///
5765 /// assert!(
5766 /// keys_one.iter().all(|key| Rc::strong_count(key) == 1)
5767 /// && keys_two.iter().all(|key| Rc::strong_count(key) == 2)
5768 /// );
5769 ///
5770 /// fn reclaim_memory(map: &mut HashMap<Rc<String>, usize>, keys: &[Rc<String>]) {
5771 /// for key in keys {
5772 /// if let Entry::Occupied(entry) = map.entry(key.clone()) {
5773 /// // Replaces the entry's key with our version of it in `keys`.
5774 /// entry.replace_key();
5775 /// }
5776 /// }
5777 /// }
5778 /// # Ok::<_, rune::alloc::Error>(())
5779 /// ```
5780 #[cfg_attr(feature = "inline-more", inline)]
5781 pub fn replace_key(self) -> K {
5782 let entry = unsafe { self.elem.as_mut() };
5783 mem::replace(&mut entry.0, self.key.unwrap())
5784 }
5785
5786 /// Provides shared access to the key and owned access to the value of
5787 /// the entry and allows to replace or remove it based on the
5788 /// value of the returned option.
5789 ///
5790 /// # Examples
5791 ///
5792 /// ```
5793 /// use rune::alloc::HashMap;
5794 /// use rune::alloc::hash_map::Entry;
5795 ///
5796 /// let mut map: HashMap<&str, u32> = HashMap::new();
5797 /// map.try_insert("poneyland", 42)?;
5798 ///
5799 /// let entry = match map.entry("poneyland") {
5800 /// Entry::Occupied(e) => {
5801 /// e.replace_entry_with(|k, v| {
5802 /// assert_eq!(k, &"poneyland");
5803 /// assert_eq!(v, 42);
5804 /// Some(v + 1)
5805 /// })
5806 /// }
5807 /// Entry::Vacant(_) => panic!(),
5808 /// };
5809 ///
5810 /// match entry {
5811 /// Entry::Occupied(e) => {
5812 /// assert_eq!(e.key(), &"poneyland");
5813 /// assert_eq!(e.get(), &43);
5814 /// }
5815 /// Entry::Vacant(_) => panic!(),
5816 /// }
5817 ///
5818 /// assert_eq!(map["poneyland"], 43);
5819 ///
5820 /// let entry = match map.entry("poneyland") {
5821 /// Entry::Occupied(e) => e.replace_entry_with(|_k, _v| None),
5822 /// Entry::Vacant(_) => panic!(),
5823 /// };
5824 ///
5825 /// match entry {
5826 /// Entry::Vacant(e) => {
5827 /// assert_eq!(e.key(), &"poneyland");
5828 /// }
5829 /// Entry::Occupied(_) => panic!(),
5830 /// }
5831 ///
5832 /// assert!(!map.contains_key("poneyland"));
5833 /// # Ok::<_, rune::alloc::Error>(())
5834 /// ```
5835 #[cfg_attr(feature = "inline-more", inline)]
5836 pub fn replace_entry_with<F>(self, f: F) -> Entry<'a, K, V, S, A>
5837 where
5838 F: FnOnce(&K, V) -> Option<V>,
5839 {
5840 unsafe {
5841 let mut spare_key = None;
5842
5843 self.table
5844 .table
5845 .replace_bucket_with(self.elem.clone(), |(key, value)| {
5846 if let Some(new_value) = f(&key, value) {
5847 Some((key, new_value))
5848 } else {
5849 spare_key = Some(key);
5850 None
5851 }
5852 });
5853
5854 if let Some(key) = spare_key {
5855 Entry::Vacant(VacantEntry {
5856 hash: self.hash,
5857 key,
5858 table: self.table,
5859 })
5860 } else {
5861 Entry::Occupied(self)
5862 }
5863 }
5864 }
5865}
5866
5867impl<'a, K, V, S, A: Allocator> VacantEntry<'a, K, V, S, A> {
5868 /// Gets a reference to the key that would be used when inserting a value
5869 /// through the `VacantEntry`.
5870 ///
5871 /// # Examples
5872 ///
5873 /// ```
5874 /// use rune::alloc::HashMap;
5875 ///
5876 /// let mut map: HashMap<&str, u32> = HashMap::new();
5877 /// assert_eq!(map.entry("poneyland").key(), &"poneyland");
5878 /// ```
5879 #[cfg_attr(feature = "inline-more", inline)]
5880 pub fn key(&self) -> &K {
5881 &self.key
5882 }
5883
5884 /// Take ownership of the key.
5885 ///
5886 /// # Examples
5887 ///
5888 /// ```
5889 /// use rune::alloc::hash_map::{Entry, HashMap};
5890 ///
5891 /// let mut map: HashMap<&str, u32> = HashMap::new();
5892 ///
5893 /// match map.entry("poneyland") {
5894 /// Entry::Occupied(_) => panic!(),
5895 /// Entry::Vacant(v) => assert_eq!(v.into_key(), "poneyland"),
5896 /// }
5897 /// ```
5898 #[cfg_attr(feature = "inline-more", inline)]
5899 pub fn into_key(self) -> K {
5900 self.key
5901 }
5902
5903 /// Sets the value of the entry with the VacantEntry's key,
5904 /// and returns a mutable reference to it.
5905 ///
5906 /// # Examples
5907 ///
5908 /// ```
5909 /// use rune::alloc::HashMap;
5910 /// use rune::alloc::hash_map::Entry;
5911 ///
5912 /// let mut map: HashMap<&str, u32> = HashMap::new();
5913 ///
5914 /// if let Entry::Vacant(o) = map.entry("poneyland") {
5915 /// o.try_insert(37)?;
5916 /// }
5917 ///
5918 /// assert_eq!(map["poneyland"], 37);
5919 /// # Ok::<_, rune::alloc::Error>(())
5920 /// ```
5921 #[cfg_attr(feature = "inline-more", inline)]
5922 pub fn try_insert(self, value: V) -> Result<&'a mut V, Error>
5923 where
5924 K: Hash,
5925 S: BuildHasher,
5926 {
5927 let table = &mut self.table.table;
5928 let hasher = make_hasher::<K, S>(&self.table.hash_builder);
5929 let entry = into_ok_try(table.insert_entry(
5930 &mut (),
5931 self.hash,
5932 (self.key, value),
5933 hasher.into_tuple(),
5934 ))?;
5935 Ok(&mut entry.1)
5936 }
5937
5938 #[cfg(test)]
5939 pub(crate) fn insert(self, value: V) -> &'a mut V
5940 where
5941 K: Hash,
5942 S: BuildHasher,
5943 {
5944 self.try_insert(value).abort()
5945 }
5946
5947 #[cfg_attr(feature = "inline-more", inline)]
5948 pub(crate) fn try_insert_entry(self, value: V) -> Result<OccupiedEntry<'a, K, V, S, A>, Error>
5949 where
5950 K: Hash,
5951 S: BuildHasher,
5952 {
5953 let hasher = make_hasher::<K, S>(&self.table.hash_builder);
5954
5955 let elem = into_ok_try(self.table.table.insert(
5956 &mut (),
5957 self.hash,
5958 (self.key, value),
5959 hasher.into_tuple(),
5960 ))?;
5961
5962 Ok(OccupiedEntry {
5963 hash: self.hash,
5964 key: None,
5965 elem,
5966 table: self.table,
5967 })
5968 }
5969}
5970
5971impl<'a, 'b, K, Q: ?Sized, V, S, A: Allocator> EntryRef<'a, 'b, K, Q, V, S, A> {
5972 /// Sets the value of the entry, and returns an OccupiedEntryRef.
5973 ///
5974 /// # Examples
5975 ///
5976 /// ```
5977 /// use rune::alloc::HashMap;
5978 ///
5979 /// let mut map: HashMap<String, u32> = HashMap::new();
5980 /// let entry = map.entry_ref("horseyland").try_insert(37)?;
5981 ///
5982 /// assert_eq!(entry.key(), "horseyland");
5983 /// # Ok::<_, rune::alloc::Error>(())
5984 /// ```
5985 #[cfg_attr(feature = "inline-more", inline)]
5986 pub fn try_insert(self, value: V) -> Result<OccupiedEntryRef<'a, 'b, K, Q, V, S, A>, Error>
5987 where
5988 K: Hash + From<&'b Q>,
5989 S: BuildHasher,
5990 {
5991 match self {
5992 EntryRef::Occupied(mut entry) => {
5993 entry.insert(value);
5994 Ok(entry)
5995 }
5996 EntryRef::Vacant(entry) => entry.try_insert_entry(value),
5997 }
5998 }
5999
6000 #[cfg(test)]
6001 pub(crate) fn insert(self, value: V) -> OccupiedEntryRef<'a, 'b, K, Q, V, S, A>
6002 where
6003 K: Hash + From<&'b Q>,
6004 S: BuildHasher,
6005 {
6006 self.try_insert(value).abort()
6007 }
6008
6009 /// Ensures a value is in the entry by inserting the default if empty, and returns
6010 /// a mutable reference to the value in the entry.
6011 ///
6012 /// # Examples
6013 ///
6014 /// ```
6015 /// use rune::alloc::HashMap;
6016 ///
6017 /// let mut map: HashMap<String, u32> = HashMap::new();
6018 ///
6019 /// // nonexistent key
6020 /// map.entry_ref("poneyland").or_try_insert(3)?;
6021 /// assert_eq!(map["poneyland"], 3);
6022 ///
6023 /// // existing key
6024 /// *map.entry_ref("poneyland").or_try_insert(10)? *= 2;
6025 /// assert_eq!(map["poneyland"], 6);
6026 /// # Ok::<_, rune::alloc::Error>(())
6027 /// ```
6028 #[cfg_attr(feature = "inline-more", inline)]
6029 pub fn or_try_insert(self, default: V) -> Result<&'a mut V, Error>
6030 where
6031 K: Hash + From<&'b Q>,
6032 S: BuildHasher,
6033 {
6034 match self {
6035 EntryRef::Occupied(entry) => Ok(entry.into_mut()),
6036 EntryRef::Vacant(entry) => entry.try_insert(default),
6037 }
6038 }
6039
6040 #[cfg(test)]
6041 pub(crate) fn or_insert(self, default: V) -> &'a mut V
6042 where
6043 K: Hash + From<&'b Q>,
6044 S: BuildHasher,
6045 {
6046 self.or_try_insert(default).abort()
6047 }
6048
6049 /// Ensures a value is in the entry by inserting the result of the default function if empty,
6050 /// and returns a mutable reference to the value in the entry.
6051 ///
6052 /// # Examples
6053 ///
6054 /// ```
6055 /// use rune::alloc::HashMap;
6056 ///
6057 /// let mut map: HashMap<String, u32> = HashMap::new();
6058 ///
6059 /// // nonexistent key
6060 /// map.entry_ref("poneyland").or_try_insert_with(|| 3)?;
6061 /// assert_eq!(map["poneyland"], 3);
6062 ///
6063 /// // existing key
6064 /// *map.entry_ref("poneyland").or_try_insert_with(|| 10)? *= 2;
6065 /// assert_eq!(map["poneyland"], 6);
6066 /// # Ok::<_, rune::alloc::Error>(())
6067 /// ```
6068 #[cfg_attr(feature = "inline-more", inline)]
6069 pub fn or_try_insert_with<F: FnOnce() -> V>(self, default: F) -> Result<&'a mut V, Error>
6070 where
6071 K: Hash + From<&'b Q>,
6072 S: BuildHasher,
6073 {
6074 match self {
6075 EntryRef::Occupied(entry) => Ok(entry.into_mut()),
6076 EntryRef::Vacant(entry) => entry.try_insert(default()),
6077 }
6078 }
6079
6080 /// Ensures a value is in the entry by inserting, if empty, the result of the default function.
6081 /// This method allows for generating key-derived values for insertion by providing the default
6082 /// function an access to the borrower form of the key.
6083 ///
6084 /// # Examples
6085 ///
6086 /// ```
6087 /// use rune::alloc::HashMap;
6088 ///
6089 /// let mut map: HashMap<String, usize> = HashMap::new();
6090 ///
6091 /// // nonexistent key
6092 /// map.entry_ref("poneyland").or_try_insert_with_key(|key| key.chars().count())?;
6093 /// assert_eq!(map["poneyland"], 9);
6094 ///
6095 /// // existing key
6096 /// *map.entry_ref("poneyland").or_try_insert_with_key(|key| key.chars().count() * 10)? *= 2;
6097 /// assert_eq!(map["poneyland"], 18);
6098 /// # Ok::<_, rune::alloc::Error>(())
6099 /// ```
6100 #[cfg_attr(feature = "inline-more", inline)]
6101 pub fn or_try_insert_with_key<F: FnOnce(&Q) -> V>(self, default: F) -> Result<&'a mut V, Error>
6102 where
6103 K: Hash + Borrow<Q> + From<&'b Q>,
6104 S: BuildHasher,
6105 {
6106 match self {
6107 EntryRef::Occupied(entry) => Ok(entry.into_mut()),
6108 EntryRef::Vacant(entry) => {
6109 let value = default(entry.key.as_ref());
6110 entry.try_insert(value)
6111 }
6112 }
6113 }
6114
6115 /// Returns a reference to this entry's key.
6116 ///
6117 /// # Examples
6118 ///
6119 /// ```
6120 /// use rune::alloc::HashMap;
6121 ///
6122 /// let mut map: HashMap<String, u32> = HashMap::new();
6123 /// map.entry_ref("poneyland").or_try_insert(3)?;
6124 /// // existing key
6125 /// assert_eq!(map.entry_ref("poneyland").key(), "poneyland");
6126 /// // nonexistent key
6127 /// assert_eq!(map.entry_ref("horseland").key(), "horseland");
6128 /// # Ok::<_, rune::alloc::Error>(())
6129 /// ```
6130 #[cfg_attr(feature = "inline-more", inline)]
6131 pub fn key(&self) -> &Q
6132 where
6133 K: Borrow<Q>,
6134 {
6135 match *self {
6136 EntryRef::Occupied(ref entry) => entry.key().borrow(),
6137 EntryRef::Vacant(ref entry) => entry.key(),
6138 }
6139 }
6140
6141 /// Provides in-place mutable access to an occupied entry before any
6142 /// potential inserts into the map.
6143 ///
6144 /// # Examples
6145 ///
6146 /// ```
6147 /// use rune::alloc::HashMap;
6148 ///
6149 /// let mut map: HashMap<String, u32> = HashMap::new();
6150 ///
6151 /// map.entry_ref("poneyland")
6152 /// .and_modify(|e| { *e += 1 })
6153 /// .or_try_insert(42)?;
6154 /// assert_eq!(map["poneyland"], 42);
6155 ///
6156 /// map.entry_ref("poneyland")
6157 /// .and_modify(|e| { *e += 1 })
6158 /// .or_try_insert(42)?;
6159 /// assert_eq!(map["poneyland"], 43);
6160 /// # Ok::<_, rune::alloc::Error>(())
6161 /// ```
6162 #[cfg_attr(feature = "inline-more", inline)]
6163 pub fn and_modify<F>(self, f: F) -> Self
6164 where
6165 F: FnOnce(&mut V),
6166 {
6167 match self {
6168 EntryRef::Occupied(mut entry) => {
6169 f(entry.get_mut());
6170 EntryRef::Occupied(entry)
6171 }
6172 EntryRef::Vacant(entry) => EntryRef::Vacant(entry),
6173 }
6174 }
6175
6176 /// Provides shared access to the key and owned access to the value of
6177 /// an occupied entry and allows to replace or remove it based on the
6178 /// value of the returned option.
6179 ///
6180 /// # Examples
6181 ///
6182 /// ```
6183 /// use rune::alloc::HashMap;
6184 /// use rune::alloc::hash_map::EntryRef;
6185 ///
6186 /// let mut map: HashMap<String, u32> = HashMap::new();
6187 ///
6188 /// let entry = map
6189 /// .entry_ref("poneyland")
6190 /// .and_replace_entry_with(|_k, _v| panic!());
6191 ///
6192 /// match entry {
6193 /// EntryRef::Vacant(e) => {
6194 /// assert_eq!(e.key(), "poneyland");
6195 /// }
6196 /// EntryRef::Occupied(_) => panic!(),
6197 /// }
6198 ///
6199 /// map.try_insert("poneyland".to_string(), 42)?;
6200 ///
6201 /// let entry = map
6202 /// .entry_ref("poneyland")
6203 /// .and_replace_entry_with(|k, v| {
6204 /// assert_eq!(k, "poneyland");
6205 /// assert_eq!(v, 42);
6206 /// Some(v + 1)
6207 /// });
6208 ///
6209 /// match entry {
6210 /// EntryRef::Occupied(e) => {
6211 /// assert_eq!(e.key(), "poneyland");
6212 /// assert_eq!(e.get(), &43);
6213 /// }
6214 /// EntryRef::Vacant(_) => panic!(),
6215 /// }
6216 ///
6217 /// assert_eq!(map["poneyland"], 43);
6218 ///
6219 /// let entry = map
6220 /// .entry_ref("poneyland")
6221 /// .and_replace_entry_with(|_k, _v| None);
6222 ///
6223 /// match entry {
6224 /// EntryRef::Vacant(e) => assert_eq!(e.key(), "poneyland"),
6225 /// EntryRef::Occupied(_) => panic!(),
6226 /// }
6227 ///
6228 /// assert!(!map.contains_key("poneyland"));
6229 /// # Ok::<_, rune::alloc::Error>(())
6230 /// ```
6231 #[cfg_attr(feature = "inline-more", inline)]
6232 pub fn and_replace_entry_with<F>(self, f: F) -> Self
6233 where
6234 F: FnOnce(&K, V) -> Option<V>,
6235 {
6236 match self {
6237 EntryRef::Occupied(entry) => entry.replace_entry_with(f),
6238 EntryRef::Vacant(_) => self,
6239 }
6240 }
6241}
6242
6243impl<'a, 'b, K, Q: ?Sized, V: Default, S, A: Allocator> EntryRef<'a, 'b, K, Q, V, S, A> {
6244 /// Ensures a value is in the entry by inserting the default value if empty,
6245 /// and returns a mutable reference to the value in the entry.
6246 ///
6247 /// # Examples
6248 ///
6249 /// ```
6250 /// use rune::alloc::HashMap;
6251 ///
6252 /// let mut map: HashMap<String, Option<u32>> = HashMap::new();
6253 ///
6254 /// // nonexistent key
6255 /// map.entry_ref("poneyland").or_try_default()?;
6256 /// assert_eq!(map["poneyland"], None);
6257 ///
6258 /// map.try_insert("horseland".to_string(), Some(3))?;
6259 ///
6260 /// // existing key
6261 /// assert_eq!(map.entry_ref("horseland").or_try_default()?, &mut Some(3));
6262 /// # Ok::<_, rune::alloc::Error>(())
6263 /// ```
6264 #[cfg_attr(feature = "inline-more", inline)]
6265 pub fn or_try_default(self) -> Result<&'a mut V, Error>
6266 where
6267 K: Hash + From<&'b Q>,
6268 S: BuildHasher,
6269 {
6270 match self {
6271 EntryRef::Occupied(entry) => Ok(entry.into_mut()),
6272 EntryRef::Vacant(entry) => entry.try_insert(Default::default()),
6273 }
6274 }
6275}
6276
6277impl<'a, 'b, K, Q: ?Sized, V, S, A: Allocator> OccupiedEntryRef<'a, 'b, K, Q, V, S, A> {
6278 /// Gets a reference to the key in the entry.
6279 ///
6280 /// # Examples
6281 ///
6282 /// ```
6283 /// use rune::alloc::hash_map::{EntryRef, HashMap};
6284 ///
6285 /// let mut map: HashMap<String, u32> = HashMap::new();
6286 /// map.entry_ref("poneyland").or_try_insert(12)?;
6287 ///
6288 /// match map.entry_ref("poneyland") {
6289 /// EntryRef::Vacant(_) => panic!(),
6290 /// EntryRef::Occupied(entry) => assert_eq!(entry.key(), "poneyland"),
6291 /// }
6292 /// # Ok::<_, rune::alloc::Error>(())
6293 /// ```
6294 #[cfg_attr(feature = "inline-more", inline)]
6295 pub fn key(&self) -> &K {
6296 unsafe { &self.elem.as_ref().0 }
6297 }
6298
6299 /// Take the ownership of the key and value from the map.
6300 /// Keeps the allocated memory for reuse.
6301 ///
6302 /// # Examples
6303 ///
6304 /// ```
6305 /// use rune::alloc::HashMap;
6306 /// use rune::alloc::hash_map::EntryRef;
6307 ///
6308 /// let mut map: HashMap<String, u32> = HashMap::new();
6309 /// // The map is empty
6310 /// assert!(map.is_empty() && map.capacity() == 0);
6311 ///
6312 /// map.entry_ref("poneyland").or_try_insert(12)?;
6313 ///
6314 /// if let EntryRef::Occupied(o) = map.entry_ref("poneyland") {
6315 /// // We delete the entry from the map.
6316 /// assert_eq!(o.remove_entry(), ("poneyland".to_owned(), 12));
6317 /// }
6318 ///
6319 /// assert_eq!(map.contains_key("poneyland"), false);
6320 /// // Now map hold none elements but capacity is equal to the old one
6321 /// assert!(map.is_empty());
6322 /// # Ok::<_, rune::alloc::Error>(())
6323 /// ```
6324 #[cfg_attr(feature = "inline-more", inline)]
6325 pub fn remove_entry(self) -> (K, V) {
6326 unsafe { self.table.table.remove(self.elem).0 }
6327 }
6328
6329 /// Gets a reference to the value in the entry.
6330 ///
6331 /// # Examples
6332 ///
6333 /// ```
6334 /// use rune::alloc::HashMap;
6335 /// use rune::alloc::hash_map::EntryRef;
6336 ///
6337 /// let mut map: HashMap<String, u32> = HashMap::new();
6338 /// map.entry_ref("poneyland").or_try_insert(12)?;
6339 ///
6340 /// match map.entry_ref("poneyland") {
6341 /// EntryRef::Vacant(_) => panic!(),
6342 /// EntryRef::Occupied(entry) => assert_eq!(entry.get(), &12),
6343 /// }
6344 /// # Ok::<_, rune::alloc::Error>(())
6345 /// ```
6346 #[cfg_attr(feature = "inline-more", inline)]
6347 pub fn get(&self) -> &V {
6348 unsafe { &self.elem.as_ref().1 }
6349 }
6350
6351 /// Gets a mutable reference to the value in the entry.
6352 ///
6353 /// If you need a reference to the `OccupiedEntryRef` which may outlive the
6354 /// destruction of the `EntryRef` value, see [`into_mut`].
6355 ///
6356 /// [`into_mut`]: #method.into_mut
6357 ///
6358 /// # Examples
6359 ///
6360 /// ```
6361 /// use rune::alloc::HashMap;
6362 /// use rune::alloc::hash_map::EntryRef;
6363 ///
6364 /// let mut map: HashMap<String, u32> = HashMap::new();
6365 /// map.entry_ref("poneyland").or_try_insert(12)?;
6366 ///
6367 /// assert_eq!(map["poneyland"], 12);
6368 /// if let EntryRef::Occupied(mut o) = map.entry_ref("poneyland") {
6369 /// *o.get_mut() += 10;
6370 /// assert_eq!(*o.get(), 22);
6371 ///
6372 /// // We can use the same Entry multiple times.
6373 /// *o.get_mut() += 2;
6374 /// }
6375 ///
6376 /// assert_eq!(map["poneyland"], 24);
6377 /// # Ok::<_, rune::alloc::Error>(())
6378 /// ```
6379 #[cfg_attr(feature = "inline-more", inline)]
6380 pub fn get_mut(&mut self) -> &mut V {
6381 unsafe { &mut self.elem.as_mut().1 }
6382 }
6383
6384 /// Converts the OccupiedEntryRef into a mutable reference to the value in the entry
6385 /// with a lifetime bound to the map itself.
6386 ///
6387 /// If you need multiple references to the `OccupiedEntryRef`, see [`get_mut`].
6388 ///
6389 /// [`get_mut`]: #method.get_mut
6390 ///
6391 /// # Examples
6392 ///
6393 /// ```
6394 /// use rune::alloc::hash_map::{EntryRef, HashMap};
6395 ///
6396 /// let mut map: HashMap<String, u32> = HashMap::new();
6397 /// map.entry_ref("poneyland").or_try_insert(12)?;
6398 ///
6399 /// let value: &mut u32;
6400 /// match map.entry_ref("poneyland") {
6401 /// EntryRef::Occupied(entry) => value = entry.into_mut(),
6402 /// EntryRef::Vacant(_) => panic!(),
6403 /// }
6404 /// *value += 10;
6405 ///
6406 /// assert_eq!(map["poneyland"], 22);
6407 /// # Ok::<_, rune::alloc::Error>(())
6408 /// ```
6409 #[cfg_attr(feature = "inline-more", inline)]
6410 pub fn into_mut(self) -> &'a mut V {
6411 unsafe { &mut self.elem.as_mut().1 }
6412 }
6413
6414 /// Sets the value of the entry, and returns the entry's old value.
6415 ///
6416 /// # Examples
6417 ///
6418 /// ```
6419 /// use rune::alloc::HashMap;
6420 /// use rune::alloc::hash_map::EntryRef;
6421 ///
6422 /// let mut map: HashMap<String, u32> = HashMap::new();
6423 /// map.entry_ref("poneyland").or_try_insert(12)?;
6424 ///
6425 /// if let EntryRef::Occupied(mut o) = map.entry_ref("poneyland") {
6426 /// assert_eq!(o.insert(15), 12);
6427 /// }
6428 ///
6429 /// assert_eq!(map["poneyland"], 15);
6430 /// # Ok::<_, rune::alloc::Error>(())
6431 /// ```
6432 #[cfg_attr(feature = "inline-more", inline)]
6433 pub fn insert(&mut self, value: V) -> V {
6434 mem::replace(self.get_mut(), value)
6435 }
6436
6437 /// Takes the value out of the entry, and returns it.
6438 /// Keeps the allocated memory for reuse.
6439 ///
6440 /// # Examples
6441 ///
6442 /// ```
6443 /// use rune::alloc::HashMap;
6444 /// use rune::alloc::hash_map::EntryRef;
6445 ///
6446 /// let mut map: HashMap<String, u32> = HashMap::new();
6447 /// // The map is empty
6448 /// assert!(map.is_empty() && map.capacity() == 0);
6449 ///
6450 /// map.entry_ref("poneyland").or_try_insert(12)?;
6451 ///
6452 /// if let EntryRef::Occupied(o) = map.entry_ref("poneyland") {
6453 /// assert_eq!(o.remove(), 12);
6454 /// }
6455 ///
6456 /// assert_eq!(map.contains_key("poneyland"), false);
6457 /// // Now map hold none elements but capacity is equal to the old one
6458 /// assert!(map.is_empty());
6459 /// # Ok::<_, rune::alloc::Error>(())
6460 /// ```
6461 #[cfg_attr(feature = "inline-more", inline)]
6462 pub fn remove(self) -> V {
6463 self.remove_entry().1
6464 }
6465
6466 /// Replaces the entry, returning the old key and value. The new key in the hash map will be
6467 /// the key used to create this entry.
6468 ///
6469 /// # Panics
6470 ///
6471 /// Will panic if this OccupiedEntryRef was created through [`EntryRef::try_insert`].
6472 ///
6473 /// # Examples
6474 ///
6475 /// ```
6476 /// use rune::alloc::hash_map::{EntryRef, HashMap};
6477 /// use std::rc::Rc;
6478 ///
6479 /// let mut map: HashMap<Rc<str>, u32> = HashMap::new();
6480 /// let key: Rc<str> = Rc::from("Stringthing");
6481 ///
6482 /// map.try_insert(key.clone(), 15)?;
6483 /// assert_eq!(Rc::strong_count(&key), 2);
6484 ///
6485 /// match map.entry_ref("Stringthing") {
6486 /// EntryRef::Occupied(entry) => {
6487 /// let (old_key, old_value): (Rc<str>, u32) = entry.replace_entry(16);
6488 /// assert!(Rc::ptr_eq(&key, &old_key) && old_value == 15);
6489 /// }
6490 /// EntryRef::Vacant(_) => panic!(),
6491 /// }
6492 ///
6493 /// assert_eq!(Rc::strong_count(&key), 1);
6494 /// assert_eq!(map["Stringthing"], 16);
6495 /// # Ok::<_, rune::alloc::Error>(())
6496 /// ```
6497 #[cfg_attr(feature = "inline-more", inline)]
6498 pub fn replace_entry(self, value: V) -> (K, V)
6499 where
6500 K: From<&'b Q>,
6501 {
6502 let entry = unsafe { self.elem.as_mut() };
6503
6504 let old_key = mem::replace(&mut entry.0, self.key.unwrap().into_owned());
6505 let old_value = mem::replace(&mut entry.1, value);
6506
6507 (old_key, old_value)
6508 }
6509
6510 /// Replaces the key in the hash map with the key used to create this entry.
6511 ///
6512 /// # Panics
6513 ///
6514 /// Will panic if this OccupiedEntryRef was created through
6515 /// [`EntryRef::try_insert`].
6516 ///
6517 /// # Examples
6518 ///
6519 /// ```
6520 /// use rune::alloc::hash_map::{EntryRef, HashMap};
6521 /// use std::rc::Rc;
6522 ///
6523 /// let mut map: HashMap<Rc<str>, usize> = HashMap::try_with_capacity(6)?;
6524 /// let mut keys: Vec<Rc<str>> = Vec::with_capacity(6);
6525 ///
6526 /// for (value, key) in ["a", "b", "c", "d", "e", "f"].into_iter().enumerate() {
6527 /// let rc_key: Rc<str> = Rc::from(key);
6528 /// keys.push(rc_key.clone());
6529 /// map.try_insert(rc_key.clone(), value)?;
6530 /// }
6531 ///
6532 /// assert!(keys.iter().all(|key| Rc::strong_count(key) == 2));
6533 ///
6534 /// // It doesn't matter that we kind of use a vector with the same keys,
6535 /// // because all keys will be newly created from the references
6536 /// reclaim_memory(&mut map, &keys);
6537 ///
6538 /// assert!(keys.iter().all(|key| Rc::strong_count(key) == 1));
6539 ///
6540 /// fn reclaim_memory(map: &mut HashMap<Rc<str>, usize>, keys: &[Rc<str>]) {
6541 /// for key in keys {
6542 /// if let EntryRef::Occupied(entry) = map.entry_ref(key.as_ref()) {
6543 /// // Replaces the entry's key with our version of it in `keys`.
6544 /// entry.replace_key();
6545 /// }
6546 /// }
6547 /// }
6548 /// # Ok::<_, rune::alloc::Error>(())
6549 /// ```
6550 #[cfg_attr(feature = "inline-more", inline)]
6551 pub fn replace_key(self) -> K
6552 where
6553 K: From<&'b Q>,
6554 {
6555 let entry = unsafe { self.elem.as_mut() };
6556 mem::replace(&mut entry.0, self.key.unwrap().into_owned())
6557 }
6558
6559 /// Provides shared access to the key and owned access to the value of
6560 /// the entry and allows to replace or remove it based on the
6561 /// value of the returned option.
6562 ///
6563 /// # Examples
6564 ///
6565 /// ```
6566 /// use rune::alloc::HashMap;
6567 /// use rune::alloc::hash_map::EntryRef;
6568 ///
6569 /// let mut map: HashMap<String, u32> = HashMap::new();
6570 /// map.try_insert("poneyland".to_string(), 42)?;
6571 ///
6572 /// let entry = match map.entry_ref("poneyland") {
6573 /// EntryRef::Occupied(e) => {
6574 /// e.replace_entry_with(|k, v| {
6575 /// assert_eq!(k, "poneyland");
6576 /// assert_eq!(v, 42);
6577 /// Some(v + 1)
6578 /// })
6579 /// }
6580 /// EntryRef::Vacant(_) => panic!(),
6581 /// };
6582 ///
6583 /// match entry {
6584 /// EntryRef::Occupied(e) => {
6585 /// assert_eq!(e.key(), "poneyland");
6586 /// assert_eq!(e.get(), &43);
6587 /// }
6588 /// EntryRef::Vacant(_) => panic!(),
6589 /// }
6590 ///
6591 /// assert_eq!(map["poneyland"], 43);
6592 ///
6593 /// let entry = match map.entry_ref("poneyland") {
6594 /// EntryRef::Occupied(e) => e.replace_entry_with(|_k, _v| None),
6595 /// EntryRef::Vacant(_) => panic!(),
6596 /// };
6597 ///
6598 /// match entry {
6599 /// EntryRef::Vacant(e) => {
6600 /// assert_eq!(e.key(), "poneyland");
6601 /// }
6602 /// EntryRef::Occupied(_) => panic!(),
6603 /// }
6604 ///
6605 /// assert!(!map.contains_key("poneyland"));
6606 /// # Ok::<_, rune::alloc::Error>(())
6607 /// ```
6608 #[cfg_attr(feature = "inline-more", inline)]
6609 pub fn replace_entry_with<F>(self, f: F) -> EntryRef<'a, 'b, K, Q, V, S, A>
6610 where
6611 F: FnOnce(&K, V) -> Option<V>,
6612 {
6613 unsafe {
6614 let mut spare_key = None;
6615
6616 self.table
6617 .table
6618 .replace_bucket_with(self.elem.clone(), |(key, value)| {
6619 if let Some(new_value) = f(&key, value) {
6620 Some((key, new_value))
6621 } else {
6622 spare_key = Some(KeyOrRef::Owned(key));
6623 None
6624 }
6625 });
6626
6627 if let Some(key) = spare_key {
6628 EntryRef::Vacant(VacantEntryRef {
6629 hash: self.hash,
6630 key,
6631 table: self.table,
6632 })
6633 } else {
6634 EntryRef::Occupied(self)
6635 }
6636 }
6637 }
6638}
6639
6640impl<'a, 'b, K, Q: ?Sized, V, S, A: Allocator> VacantEntryRef<'a, 'b, K, Q, V, S, A> {
6641 /// Gets a reference to the key that would be used when inserting a value
6642 /// through the `VacantEntryRef`.
6643 ///
6644 /// # Examples
6645 ///
6646 /// ```
6647 /// use rune::alloc::HashMap;
6648 ///
6649 /// let mut map: HashMap<String, u32> = HashMap::new();
6650 /// let key: &str = "poneyland";
6651 /// assert_eq!(map.entry_ref(key).key(), "poneyland");
6652 /// ```
6653 #[cfg_attr(feature = "inline-more", inline)]
6654 pub fn key(&self) -> &Q
6655 where
6656 K: Borrow<Q>,
6657 {
6658 self.key.as_ref()
6659 }
6660
6661 /// Take ownership of the key.
6662 ///
6663 /// # Examples
6664 ///
6665 /// ```
6666 /// use rune::alloc::hash_map::{EntryRef, HashMap};
6667 ///
6668 /// let mut map: HashMap<String, u32> = HashMap::new();
6669 /// let key: &str = "poneyland";
6670 ///
6671 /// if let EntryRef::Vacant(v) = map.entry_ref(key) {
6672 /// assert_eq!(v.into_key(), "poneyland");
6673 /// }
6674 /// ```
6675 #[cfg_attr(feature = "inline-more", inline)]
6676 pub fn into_key(self) -> K
6677 where
6678 K: From<&'b Q>,
6679 {
6680 self.key.into_owned()
6681 }
6682
6683 /// Sets the value of the entry with the VacantEntryRef's key, and returns a
6684 /// mutable reference to it.
6685 ///
6686 /// # Examples
6687 ///
6688 /// ```
6689 /// use rune::alloc::HashMap;
6690 /// use rune::alloc::hash_map::EntryRef;
6691 ///
6692 /// let mut map: HashMap<String, u32> = HashMap::new();
6693 /// let key: &str = "poneyland";
6694 ///
6695 /// if let EntryRef::Vacant(o) = map.entry_ref(key) {
6696 /// o.try_insert(37)?;
6697 /// }
6698 ///
6699 /// assert_eq!(map["poneyland"], 37);
6700 /// # Ok::<_, rune::alloc::Error>(())
6701 /// ```
6702 #[cfg_attr(feature = "inline-more", inline)]
6703 pub fn try_insert(self, value: V) -> Result<&'a mut V, Error>
6704 where
6705 K: Hash + From<&'b Q>,
6706 S: BuildHasher,
6707 {
6708 let table = &mut self.table.table;
6709 let hasher = make_hasher::<K, S>(&self.table.hash_builder);
6710
6711 let entry = into_ok_try(table.insert_entry(
6712 &mut (),
6713 self.hash,
6714 (self.key.into_owned(), value),
6715 hasher.into_tuple(),
6716 ))?;
6717
6718 Ok(&mut entry.1)
6719 }
6720
6721 #[cfg(test)]
6722 pub(crate) fn insert(self, value: V) -> &'a mut V
6723 where
6724 K: Hash + From<&'b Q>,
6725 S: BuildHasher,
6726 {
6727 self.try_insert(value).abort()
6728 }
6729
6730 #[cfg_attr(feature = "inline-more", inline)]
6731 fn try_insert_entry(self, value: V) -> Result<OccupiedEntryRef<'a, 'b, K, Q, V, S, A>, Error>
6732 where
6733 S: BuildHasher,
6734 K: Hash + From<&'b Q>,
6735 {
6736 let hasher = make_hasher::<K, S>(&self.table.hash_builder);
6737
6738 let elem = into_ok_try(self.table.table.insert(
6739 &mut (),
6740 self.hash,
6741 (self.key.into_owned(), value),
6742 hasher.into_tuple(),
6743 ))?;
6744
6745 Ok(OccupiedEntryRef {
6746 hash: self.hash,
6747 key: None,
6748 elem,
6749 table: self.table,
6750 })
6751 }
6752}
6753
6754impl<K, V, S, A: Allocator> TryFromIteratorIn<(K, V), A> for HashMap<K, V, S, A>
6755where
6756 K: Eq + Hash,
6757 S: BuildHasher + Default,
6758{
6759 #[cfg_attr(feature = "inline-more", inline)]
6760 fn try_from_iter_in<T: IntoIterator<Item = (K, V)>>(iter: T, alloc: A) -> Result<Self, Error> {
6761 let iter = iter.into_iter();
6762
6763 let mut map =
6764 Self::try_with_capacity_and_hasher_in(iter.size_hint().0, S::default(), alloc)?;
6765
6766 for (k, v) in iter {
6767 map.try_insert(k, v)?;
6768 }
6769
6770 Ok(map)
6771 }
6772}
6773
6774#[cfg(test)]
6775impl<K, V, S, A: Allocator + Default> FromIterator<(K, V)> for HashMap<K, V, S, A>
6776where
6777 K: Eq + Hash,
6778 S: BuildHasher + Default,
6779{
6780 #[cfg_attr(feature = "inline-more", inline)]
6781 fn from_iter<T: IntoIterator<Item = (K, V)>>(iter: T) -> Self {
6782 Self::try_from_iter_in(iter, A::default()).abort()
6783 }
6784}
6785
6786/// Inserts all new key-values from the iterator and replaces values with existing
6787/// keys with new values returned from the iterator.
6788impl<K, V, S, A> TryExtend<(K, V)> for HashMap<K, V, S, A>
6789where
6790 K: Eq + Hash,
6791 S: BuildHasher,
6792 A: Allocator,
6793{
6794 /// Inserts all new key-values from the iterator to existing `HashMap<K, V, S, A>`.
6795 /// Replace values with existing keys with new values returned from the iterator.
6796 ///
6797 /// # Examples
6798 ///
6799 /// ```
6800 /// use rune::alloc::{try_vec, HashMap, Vec};
6801 /// use rune::alloc::prelude::*;
6802 ///
6803 /// let mut map = HashMap::new();
6804 /// map.try_insert(1, 100)?;
6805 ///
6806 /// let some_iter = [(1, 1), (2, 2)].into_iter();
6807 /// map.try_extend(some_iter)?;
6808 /// // Replace values with existing keys with new values returned from the iterator.
6809 /// // So that the map.get(&1) doesn't return Some(&100).
6810 /// assert_eq!(map.get(&1), Some(&1));
6811 ///
6812 /// let some_vec: Vec<_> = try_vec![(3, 3), (4, 4)];
6813 /// map.try_extend(some_vec)?;
6814 ///
6815 /// let some_arr = [(5, 5), (6, 6)];
6816 /// map.try_extend(some_arr)?;
6817 /// let old_map_len = map.len();
6818 ///
6819 /// // You can also extend from another HashMap
6820 /// let mut new_map = HashMap::new();
6821 /// new_map.try_extend(map)?;
6822 /// assert_eq!(new_map.len(), old_map_len);
6823 ///
6824 /// let mut vec: Vec<_> = new_map.into_iter().try_collect()?;
6825 /// // The `IntoIter` iterator produces items in arbitrary order, so the
6826 /// // items must be sorted to test them against a sorted array.
6827 /// vec.sort_unstable();
6828 /// assert_eq!(vec, [(1, 1), (2, 2), (3, 3), (4, 4), (5, 5), (6, 6)]);
6829 /// # Ok::<_, rune::alloc::Error>(())
6830 /// ```
6831 #[cfg_attr(feature = "inline-more", inline)]
6832 fn try_extend<T: IntoIterator<Item = (K, V)>>(&mut self, iter: T) -> Result<(), Error> {
6833 // Keys may be already present or show multiple times in the iterator.
6834 // Reserve the entire hint lower bound if the map is empty.
6835 // Otherwise reserve half the hint (rounded up), so the map
6836 // will only resize twice in the worst case.
6837 let iter = iter.into_iter();
6838
6839 let reserve = if self.is_empty() {
6840 iter.size_hint().0
6841 } else {
6842 (iter.size_hint().0 + 1) / 2
6843 };
6844
6845 self.try_reserve(reserve)?;
6846
6847 for (k, v) in iter {
6848 self.try_insert(k, v)?;
6849 }
6850
6851 Ok(())
6852 }
6853}
6854
6855#[cfg(test)]
6856impl<K, V, S, A> Extend<(K, V)> for HashMap<K, V, S, A>
6857where
6858 K: Eq + Hash,
6859 S: BuildHasher,
6860 A: Allocator,
6861{
6862 fn extend<T: IntoIterator<Item = (K, V)>>(&mut self, iter: T) {
6863 self.try_extend(iter).abort()
6864 }
6865}
6866
6867/// Inserts all new key-values from the iterator and replaces values with existing
6868/// keys with new values returned from the iterator.
6869impl<'a, K, V, S, A> TryExtend<(&'a K, &'a V)> for HashMap<K, V, S, A>
6870where
6871 K: Eq + Hash + Copy,
6872 V: Copy,
6873 S: BuildHasher,
6874 A: Allocator,
6875{
6876 /// Inserts all new key-values from the iterator to existing `HashMap<K, V, S, A>`.
6877 /// Replace values with existing keys with new values returned from the iterator.
6878 /// The keys and values must implement [`Copy`] trait.
6879 ///
6880 /// [`Copy`]: https://doc.rust-lang.org/core/marker/trait.Copy.html
6881 ///
6882 /// # Examples
6883 ///
6884 /// ```
6885 /// use rune::alloc::hash_map::HashMap;
6886 /// use rune::alloc::prelude::*;
6887 ///
6888 /// let mut map = HashMap::new();
6889 /// map.try_insert(1, 100)?;
6890 ///
6891 /// let arr = [(1, 1), (2, 2)];
6892 /// let some_iter = arr.iter().map(|(k, v)| (k, v));
6893 /// map.try_extend(some_iter)?;
6894 /// // Replace values with existing keys with new values returned from the iterator.
6895 /// // So that the map.get(&1) doesn't return Some(&100).
6896 /// assert_eq!(map.get(&1), Some(&1));
6897 ///
6898 /// let some_vec: Vec<_> = vec![(3, 3), (4, 4)];
6899 /// map.try_extend(some_vec.iter().map(|(k, v)| (k, v)))?;
6900 ///
6901 /// let some_arr = [(5, 5), (6, 6)];
6902 /// map.try_extend(some_arr.iter().map(|(k, v)| (k, v)))?;
6903 ///
6904 /// // You can also extend from another HashMap
6905 /// let mut new_map = HashMap::new();
6906 /// new_map.try_extend(&map)?;
6907 /// assert_eq!(new_map, map);
6908 ///
6909 /// let mut vec: Vec<_> = new_map.into_iter().collect();
6910 /// // The `IntoIter` iterator produces items in arbitrary order, so the
6911 /// // items must be sorted to test them against a sorted array.
6912 /// vec.sort_unstable();
6913 /// assert_eq!(vec, [(1, 1), (2, 2), (3, 3), (4, 4), (5, 5), (6, 6)]);
6914 /// # Ok::<_, rune::alloc::Error>(())
6915 /// ```
6916 #[cfg_attr(feature = "inline-more", inline)]
6917 fn try_extend<T: IntoIterator<Item = (&'a K, &'a V)>>(&mut self, iter: T) -> Result<(), Error> {
6918 self.try_extend(iter.into_iter().map(|(&key, &value)| (key, value)))
6919 }
6920}
6921
6922#[cfg(test)]
6923impl<'a, K, V, S, A> Extend<(&'a K, &'a V)> for HashMap<K, V, S, A>
6924where
6925 K: Eq + Hash + Copy,
6926 V: Copy,
6927 S: BuildHasher,
6928 A: Allocator,
6929{
6930 fn extend<T: IntoIterator<Item = (&'a K, &'a V)>>(&mut self, iter: T) {
6931 self.try_extend(iter).abort()
6932 }
6933}
6934
6935/// Inserts all new key-values from the iterator and replaces values with existing
6936/// keys with new values returned from the iterator.
6937impl<'a, K, V, S, A> TryExtend<&'a (K, V)> for HashMap<K, V, S, A>
6938where
6939 K: Eq + Hash + Copy,
6940 V: Copy,
6941 S: BuildHasher,
6942 A: Allocator,
6943{
6944 /// Inserts all new key-values from the iterator to existing `HashMap<K, V, S, A>`.
6945 /// Replace values with existing keys with new values returned from the iterator.
6946 /// The keys and values must implement [`Copy`] trait.
6947 ///
6948 /// [`Copy`]: https://doc.rust-lang.org/core/marker/trait.Copy.html
6949 ///
6950 /// # Examples
6951 ///
6952 /// ```
6953 /// use rune::alloc::hash_map::HashMap;
6954 /// use rune::alloc::prelude::*;
6955 ///
6956 /// let mut map = HashMap::new();
6957 /// map.try_insert(1, 100)?;
6958 ///
6959 /// let arr = [(1, 1), (2, 2)];
6960 /// let some_iter = arr.iter();
6961 /// map.try_extend(some_iter)?;
6962 /// // Replace values with existing keys with new values returned from the iterator.
6963 /// // So that the map.get(&1) doesn't return Some(&100).
6964 /// assert_eq!(map.get(&1), Some(&1));
6965 ///
6966 /// let some_vec: Vec<_> = vec![(3, 3), (4, 4)];
6967 /// map.try_extend(&some_vec)?;
6968 ///
6969 /// let some_arr = [(5, 5), (6, 6)];
6970 /// map.try_extend(&some_arr)?;
6971 ///
6972 /// let mut vec: Vec<_> = map.into_iter().collect();
6973 /// // The `IntoIter` iterator produces items in arbitrary order, so the
6974 /// // items must be sorted to test them against a sorted array.
6975 /// vec.sort_unstable();
6976 /// assert_eq!(vec, [(1, 1), (2, 2), (3, 3), (4, 4), (5, 5), (6, 6)]);
6977 /// # Ok::<_, rune::alloc::Error>(())
6978 /// ```
6979 #[cfg_attr(feature = "inline-more", inline)]
6980 fn try_extend<T: IntoIterator<Item = &'a (K, V)>>(&mut self, iter: T) -> Result<(), Error> {
6981 self.try_extend(iter.into_iter().map(|&(key, value)| (key, value)))
6982 }
6983}
6984
6985#[allow(dead_code)]
6986fn assert_covariance() {
6987 fn map_key<'new>(v: HashMap<&'static str, u8>) -> HashMap<&'new str, u8> {
6988 v
6989 }
6990 fn map_val<'new>(v: HashMap<u8, &'static str>) -> HashMap<u8, &'new str> {
6991 v
6992 }
6993 fn iter_key<'a, 'new>(v: Iter<'a, &'static str, u8>) -> Iter<'a, &'new str, u8> {
6994 v
6995 }
6996 fn iter_val<'a, 'new>(v: Iter<'a, u8, &'static str>) -> Iter<'a, u8, &'new str> {
6997 v
6998 }
6999 fn into_iter_key<'new, A: Allocator>(
7000 v: IntoIter<&'static str, u8, A>,
7001 ) -> IntoIter<&'new str, u8, A> {
7002 v
7003 }
7004 fn into_iter_val<'new, A: Allocator>(
7005 v: IntoIter<u8, &'static str, A>,
7006 ) -> IntoIter<u8, &'new str, A> {
7007 v
7008 }
7009 fn keys_key<'a, 'new>(v: Keys<'a, &'static str, u8>) -> Keys<'a, &'new str, u8> {
7010 v
7011 }
7012 fn keys_val<'a, 'new>(v: Keys<'a, u8, &'static str>) -> Keys<'a, u8, &'new str> {
7013 v
7014 }
7015 fn values_key<'a, 'new>(v: Values<'a, &'static str, u8>) -> Values<'a, &'new str, u8> {
7016 v
7017 }
7018 fn values_val<'a, 'new>(v: Values<'a, u8, &'static str>) -> Values<'a, u8, &'new str> {
7019 v
7020 }
7021 fn drain<'new>(
7022 d: Drain<'static, &'static str, &'static str>,
7023 ) -> Drain<'new, &'new str, &'new str> {
7024 d
7025 }
7026}
7027
7028#[cfg(test)]
7029mod test_map {
7030 use core::alloc::Layout;
7031 use core::hash::BuildHasher;
7032 use core::ptr::NonNull;
7033 use core::sync::atomic::{AtomicI8, Ordering};
7034
7035 use std::borrow::ToOwned;
7036 use std::cell::RefCell;
7037 use std::collections::hash_map::DefaultHasher;
7038 use std::ops::AddAssign;
7039 use std::thread;
7040 use std::usize;
7041 use std::vec::Vec;
7042 use std::{format, println};
7043
7044 use ::rust_alloc::string::{String, ToString};
7045 use ::rust_alloc::sync::Arc;
7046
7047 use rand::{rngs::SmallRng, Rng, SeedableRng};
7048
7049 use super::DefaultHashBuilder;
7050 use super::Entry::{Occupied, Vacant};
7051 use super::{EntryRef, HashMap, RawEntryMut};
7052
7053 use crate::alloc::{into_ok, into_ok_try};
7054 use crate::alloc::{AllocError, Allocator, Global};
7055 use crate::clone::TryClone;
7056 use crate::error::Error;
7057 use crate::iter::TryExtend;
7058 use crate::testing::*;
7059
7060 std::thread_local!(static DROP_VECTOR: RefCell<Vec<i32>> = RefCell::new(Vec::new()));
7061
7062 #[test]
7063 fn test_zero_capacities() {
7064 type HM = HashMap<i32, i32>;
7065
7066 let m = HM::new();
7067 assert_eq!(m.capacity(), 0);
7068
7069 let m = HM::default();
7070 assert_eq!(m.capacity(), 0);
7071
7072 let m = HM::with_hasher(DefaultHashBuilder::default());
7073 assert_eq!(m.capacity(), 0);
7074
7075 let m = HM::with_capacity(0);
7076 assert_eq!(m.capacity(), 0);
7077
7078 let m = HM::with_capacity_and_hasher(0, DefaultHashBuilder::default());
7079 assert_eq!(m.capacity(), 0);
7080
7081 let mut m = HM::new();
7082 m.insert(1, 1);
7083 m.insert(2, 2);
7084 m.remove(&1);
7085 m.remove(&2);
7086 m.shrink_to_fit();
7087 assert_eq!(m.capacity(), 0);
7088
7089 let mut m = HM::new();
7090 m.reserve(0);
7091 assert_eq!(m.capacity(), 0);
7092 }
7093
7094 #[test]
7095 fn test_create_capacity_zero() {
7096 let mut m = HashMap::with_capacity(0);
7097
7098 assert!(m.insert(1, 1).is_none());
7099
7100 assert!(m.contains_key(&1));
7101 assert!(!m.contains_key(&0));
7102 }
7103
7104 #[test]
7105 fn test_insert() {
7106 let mut m = HashMap::new();
7107 assert_eq!(m.len(), 0);
7108 assert!(m.insert(1, 2).is_none());
7109 assert_eq!(m.len(), 1);
7110 assert!(m.insert(2, 4).is_none());
7111 assert_eq!(m.len(), 2);
7112 assert_eq!(*m.get(&1).unwrap(), 2);
7113 assert_eq!(*m.get(&2).unwrap(), 4);
7114 }
7115
7116 #[test]
7117 fn test_clone() {
7118 let mut m = HashMap::new();
7119 assert_eq!(m.len(), 0);
7120 assert!(m.insert(1, 2).is_none());
7121 assert_eq!(m.len(), 1);
7122 assert!(m.insert(2, 4).is_none());
7123 assert_eq!(m.len(), 2);
7124 #[allow(clippy::redundant_clone)]
7125 let m2 = m.clone();
7126 assert_eq!(*m2.get(&1).unwrap(), 2);
7127 assert_eq!(*m2.get(&2).unwrap(), 4);
7128 assert_eq!(m2.len(), 2);
7129 }
7130
7131 #[test]
7132 fn test_clone_from() {
7133 let mut m = HashMap::new();
7134 let mut m2 = HashMap::new();
7135 assert_eq!(m.len(), 0);
7136 assert!(m.insert(1, 2).is_none());
7137 assert_eq!(m.len(), 1);
7138 assert!(m.insert(2, 4).is_none());
7139 assert_eq!(m.len(), 2);
7140 m2.try_clone_from(&m).unwrap();
7141 assert_eq!(*m2.get(&1).unwrap(), 2);
7142 assert_eq!(*m2.get(&2).unwrap(), 4);
7143 assert_eq!(m2.len(), 2);
7144 }
7145
7146 #[derive(Hash, PartialEq, Eq)]
7147 struct Droppable {
7148 k: usize,
7149 }
7150
7151 impl Droppable {
7152 fn new(k: usize) -> Droppable {
7153 DROP_VECTOR.with(|slot| {
7154 slot.borrow_mut()[k] += 1;
7155 });
7156
7157 Droppable { k }
7158 }
7159 }
7160
7161 impl Drop for Droppable {
7162 fn drop(&mut self) {
7163 DROP_VECTOR.with(|slot| {
7164 slot.borrow_mut()[self.k] -= 1;
7165 });
7166 }
7167 }
7168
7169 impl TryClone for Droppable {
7170 fn try_clone(&self) -> Result<Self, Error> {
7171 Ok(Droppable::new(self.k))
7172 }
7173 }
7174
7175 #[test]
7176 fn test_drops() {
7177 DROP_VECTOR.with(|slot| {
7178 *slot.borrow_mut() = ::rust_alloc::vec![0; 200];
7179 });
7180
7181 {
7182 let mut m = HashMap::new();
7183
7184 DROP_VECTOR.with(|v| {
7185 for i in 0..200 {
7186 assert_eq!(v.borrow()[i], 0);
7187 }
7188 });
7189
7190 for i in 0..100 {
7191 let d1 = Droppable::new(i);
7192 let d2 = Droppable::new(i + 100);
7193 m.insert(d1, d2);
7194 }
7195
7196 DROP_VECTOR.with(|v| {
7197 for i in 0..200 {
7198 assert_eq!(v.borrow()[i], 1);
7199 }
7200 });
7201
7202 for i in 0..50 {
7203 let k = Droppable::new(i);
7204 let v = m.remove(&k);
7205
7206 assert!(v.is_some());
7207
7208 DROP_VECTOR.with(|v| {
7209 assert_eq!(v.borrow()[i], 1);
7210 assert_eq!(v.borrow()[i + 100], 1);
7211 });
7212 }
7213
7214 DROP_VECTOR.with(|v| {
7215 for i in 0..50 {
7216 assert_eq!(v.borrow()[i], 0);
7217 assert_eq!(v.borrow()[i + 100], 0);
7218 }
7219
7220 for i in 50..100 {
7221 assert_eq!(v.borrow()[i], 1);
7222 assert_eq!(v.borrow()[i + 100], 1);
7223 }
7224 });
7225 }
7226
7227 DROP_VECTOR.with(|v| {
7228 for i in 0..200 {
7229 assert_eq!(v.borrow()[i], 0);
7230 }
7231 });
7232 }
7233
7234 #[test]
7235 fn test_into_iter_drops() {
7236 DROP_VECTOR.with(|v| {
7237 *v.borrow_mut() = ::rust_alloc::vec![0; 200];
7238 });
7239
7240 let hm = {
7241 let mut hm = HashMap::new();
7242
7243 DROP_VECTOR.with(|v| {
7244 for i in 0..200 {
7245 assert_eq!(v.borrow()[i], 0);
7246 }
7247 });
7248
7249 for i in 0..100 {
7250 let d1 = Droppable::new(i);
7251 let d2 = Droppable::new(i + 100);
7252 hm.insert(d1, d2);
7253 }
7254
7255 DROP_VECTOR.with(|v| {
7256 for i in 0..200 {
7257 assert_eq!(v.borrow()[i], 1);
7258 }
7259 });
7260
7261 hm
7262 };
7263
7264 // By the way, ensure that cloning doesn't screw up the dropping.
7265 drop(hm.clone());
7266
7267 {
7268 let mut half = hm.into_iter().take(50);
7269
7270 DROP_VECTOR.with(|v| {
7271 for i in 0..200 {
7272 assert_eq!(v.borrow()[i], 1);
7273 }
7274 });
7275
7276 for _ in half.by_ref() {}
7277
7278 DROP_VECTOR.with(|v| {
7279 let nk = (0..100).filter(|&i| v.borrow()[i] == 1).count();
7280
7281 let nv = (0..100).filter(|&i| v.borrow()[i + 100] == 1).count();
7282
7283 assert_eq!(nk, 50);
7284 assert_eq!(nv, 50);
7285 });
7286 };
7287
7288 DROP_VECTOR.with(|v| {
7289 for i in 0..200 {
7290 assert_eq!(v.borrow()[i], 0);
7291 }
7292 });
7293 }
7294
7295 #[test]
7296 fn test_empty_remove() {
7297 let mut m: HashMap<i32, bool> = HashMap::new();
7298 assert_eq!(m.remove(&0), None);
7299 }
7300
7301 #[test]
7302 fn test_empty_entry() {
7303 let mut m: HashMap<i32, bool> = HashMap::new();
7304 match m.entry(0) {
7305 Occupied(_) => panic!(),
7306 Vacant(_) => {}
7307 }
7308 assert!(*m.entry(0).or_insert(true));
7309 assert_eq!(m.len(), 1);
7310 }
7311
7312 #[test]
7313 fn test_empty_entry_ref() {
7314 let mut m: HashMap<String, bool> = HashMap::new();
7315 match m.entry_ref("poneyland") {
7316 EntryRef::Occupied(_) => panic!(),
7317 EntryRef::Vacant(_) => {}
7318 }
7319 assert!(*m.entry_ref("poneyland").or_insert(true));
7320 assert_eq!(m.len(), 1);
7321 }
7322
7323 #[test]
7324 fn test_empty_iter() {
7325 let mut m: HashMap<i32, bool> = HashMap::new();
7326 assert_eq!(m.drain().next(), None);
7327 assert_eq!(m.keys().next(), None);
7328 assert_eq!(m.values().next(), None);
7329 assert_eq!(m.values_mut().next(), None);
7330 assert_eq!(m.iter().next(), None);
7331 assert_eq!(m.iter_mut().next(), None);
7332 assert_eq!(m.len(), 0);
7333 assert!(m.is_empty());
7334 assert_eq!(m.into_iter().next(), None);
7335 }
7336
7337 #[test]
7338 #[cfg_attr(miri, ignore)] // FIXME: takes too long
7339 fn test_lots_of_insertions() {
7340 let mut m = HashMap::new();
7341
7342 // Try this a few times to make sure we never screw up the hashmap's
7343 // internal state.
7344 for _ in 0..10 {
7345 assert!(m.is_empty());
7346
7347 for i in 1..1001 {
7348 assert!(m.insert(i, i).is_none());
7349
7350 for j in 1..=i {
7351 let r = m.get(&j);
7352 assert_eq!(r, Some(&j));
7353 }
7354
7355 for j in i + 1..1001 {
7356 let r = m.get(&j);
7357 assert_eq!(r, None);
7358 }
7359 }
7360
7361 for i in 1001..2001 {
7362 assert!(!m.contains_key(&i));
7363 }
7364
7365 // remove forwards
7366 for i in 1..1001 {
7367 assert!(m.remove(&i).is_some());
7368
7369 for j in 1..=i {
7370 assert!(!m.contains_key(&j));
7371 }
7372
7373 for j in i + 1..1001 {
7374 assert!(m.contains_key(&j));
7375 }
7376 }
7377
7378 for i in 1..1001 {
7379 assert!(!m.contains_key(&i));
7380 }
7381
7382 for i in 1..1001 {
7383 assert!(m.insert(i, i).is_none());
7384 }
7385
7386 // remove backwards
7387 for i in (1..1001).rev() {
7388 assert!(m.remove(&i).is_some());
7389
7390 for j in i..1001 {
7391 assert!(!m.contains_key(&j));
7392 }
7393
7394 for j in 1..i {
7395 assert!(m.contains_key(&j));
7396 }
7397 }
7398 }
7399 }
7400
7401 #[test]
7402 fn test_find_mut() {
7403 let mut m = HashMap::new();
7404 assert!(m.insert(1, 12).is_none());
7405 assert!(m.insert(2, 8).is_none());
7406 assert!(m.insert(5, 14).is_none());
7407 let new = 100;
7408 match m.get_mut(&5) {
7409 None => panic!(),
7410 Some(x) => *x = new,
7411 }
7412 assert_eq!(m.get(&5), Some(&new));
7413 }
7414
7415 #[test]
7416 fn test_insert_overwrite() {
7417 let mut m = HashMap::new();
7418 assert!(m.insert(1, 2).is_none());
7419 assert_eq!(*m.get(&1).unwrap(), 2);
7420 assert!(m.insert(1, 3).is_some());
7421 assert_eq!(*m.get(&1).unwrap(), 3);
7422 }
7423
7424 #[test]
7425 fn test_insert_conflicts() {
7426 let mut m = HashMap::with_capacity(4);
7427 assert!(m.insert(1, 2).is_none());
7428 assert!(m.insert(5, 3).is_none());
7429 assert!(m.insert(9, 4).is_none());
7430 assert_eq!(*m.get(&9).unwrap(), 4);
7431 assert_eq!(*m.get(&5).unwrap(), 3);
7432 assert_eq!(*m.get(&1).unwrap(), 2);
7433 }
7434
7435 #[test]
7436 fn test_conflict_remove() {
7437 let mut m = HashMap::with_capacity(4);
7438 assert!(m.insert(1, 2).is_none());
7439 assert_eq!(*m.get(&1).unwrap(), 2);
7440 assert!(m.insert(5, 3).is_none());
7441 assert_eq!(*m.get(&1).unwrap(), 2);
7442 assert_eq!(*m.get(&5).unwrap(), 3);
7443 assert!(m.insert(9, 4).is_none());
7444 assert_eq!(*m.get(&1).unwrap(), 2);
7445 assert_eq!(*m.get(&5).unwrap(), 3);
7446 assert_eq!(*m.get(&9).unwrap(), 4);
7447 assert!(m.remove(&1).is_some());
7448 assert_eq!(*m.get(&9).unwrap(), 4);
7449 assert_eq!(*m.get(&5).unwrap(), 3);
7450 }
7451
7452 #[test]
7453 fn test_insert_unique_unchecked() {
7454 let mut map = HashMap::new();
7455 let (k1, v1) = map.insert_unique_unchecked(10, 11);
7456 assert_eq!((&10, &mut 11), (k1, v1));
7457 let (k2, v2) = map.insert_unique_unchecked(20, 21);
7458 assert_eq!((&20, &mut 21), (k2, v2));
7459 assert_eq!(Some(&11), map.get(&10));
7460 assert_eq!(Some(&21), map.get(&20));
7461 assert_eq!(None, map.get(&30));
7462 }
7463
7464 #[test]
7465 fn test_is_empty() {
7466 let mut m = HashMap::with_capacity(4);
7467 assert!(m.insert(1, 2).is_none());
7468 assert!(!m.is_empty());
7469 assert!(m.remove(&1).is_some());
7470 assert!(m.is_empty());
7471 }
7472
7473 #[test]
7474 fn test_remove() {
7475 let mut m = HashMap::new();
7476 m.insert(1, 2);
7477 assert_eq!(m.remove(&1), Some(2));
7478 assert_eq!(m.remove(&1), None);
7479 }
7480
7481 #[test]
7482 fn test_remove_entry() {
7483 let mut m = HashMap::new();
7484 m.insert(1, 2);
7485 assert_eq!(m.remove_entry(&1), Some((1, 2)));
7486 assert_eq!(m.remove(&1), None);
7487 }
7488
7489 #[test]
7490 fn test_iterate() {
7491 let mut m = HashMap::with_capacity(4);
7492 for i in 0..32 {
7493 assert!(m.insert(i, i * 2).is_none());
7494 }
7495 assert_eq!(m.len(), 32);
7496
7497 let mut observed: u32 = 0;
7498
7499 for (k, v) in &m {
7500 assert_eq!(*v, *k * 2);
7501 observed |= 1 << *k;
7502 }
7503 assert_eq!(observed, 0xFFFF_FFFF);
7504 }
7505
7506 #[test]
7507 fn test_keys() {
7508 let vec = ::rust_alloc::vec![(1, 'a'), (2, 'b'), (3, 'c')];
7509 let map: HashMap<_, _> = vec.into_iter().collect();
7510 let keys: Vec<_> = map.keys().copied().collect();
7511 assert_eq!(keys.len(), 3);
7512 assert!(keys.contains(&1));
7513 assert!(keys.contains(&2));
7514 assert!(keys.contains(&3));
7515 }
7516
7517 #[test]
7518 fn test_values() {
7519 let vec = ::rust_alloc::vec![(1, 'a'), (2, 'b'), (3, 'c')];
7520 let map: HashMap<_, _> = vec.into_iter().collect();
7521 let values: Vec<_> = map.values().copied().collect();
7522 assert_eq!(values.len(), 3);
7523 assert!(values.contains(&'a'));
7524 assert!(values.contains(&'b'));
7525 assert!(values.contains(&'c'));
7526 }
7527
7528 #[test]
7529 fn test_values_mut() {
7530 let vec = ::rust_alloc::vec![(1, 1), (2, 2), (3, 3)];
7531 let mut map: HashMap<_, _> = vec.into_iter().collect();
7532 for value in map.values_mut() {
7533 *value *= 2;
7534 }
7535 let values: Vec<_> = map.values().copied().collect();
7536 assert_eq!(values.len(), 3);
7537 assert!(values.contains(&2));
7538 assert!(values.contains(&4));
7539 assert!(values.contains(&6));
7540 }
7541
7542 #[test]
7543 fn test_into_keys() {
7544 let vec = ::rust_alloc::vec![(1, 'a'), (2, 'b'), (3, 'c')];
7545 let map: HashMap<_, _> = vec.into_iter().collect();
7546 let keys: Vec<_> = map.into_keys().collect();
7547
7548 assert_eq!(keys.len(), 3);
7549 assert!(keys.contains(&1));
7550 assert!(keys.contains(&2));
7551 assert!(keys.contains(&3));
7552 }
7553
7554 #[test]
7555 fn test_into_values() {
7556 let vec = ::rust_alloc::vec![(1, 'a'), (2, 'b'), (3, 'c')];
7557 let map: HashMap<_, _> = vec.into_iter().collect();
7558 let values: Vec<_> = map.into_values().collect();
7559
7560 assert_eq!(values.len(), 3);
7561 assert!(values.contains(&'a'));
7562 assert!(values.contains(&'b'));
7563 assert!(values.contains(&'c'));
7564 }
7565
7566 #[test]
7567 fn test_find() {
7568 let mut m = HashMap::new();
7569 assert!(m.get(&1).is_none());
7570 m.insert(1, 2);
7571 match m.get(&1) {
7572 None => panic!(),
7573 Some(v) => assert_eq!(*v, 2),
7574 }
7575 }
7576
7577 #[test]
7578 fn test_eq() {
7579 let mut m1 = HashMap::new();
7580 m1.insert(1, 2);
7581 m1.insert(2, 3);
7582 m1.insert(3, 4);
7583
7584 let mut m2 = HashMap::new();
7585 m2.insert(1, 2);
7586 m2.insert(2, 3);
7587
7588 assert!(m1 != m2);
7589
7590 m2.insert(3, 4);
7591
7592 assert_eq!(m1, m2);
7593 }
7594
7595 #[test]
7596 fn test_show() {
7597 let mut map = HashMap::new();
7598 let empty: HashMap<i32, i32> = HashMap::new();
7599
7600 map.insert(1, 2);
7601 map.insert(3, 4);
7602
7603 let map_str = format!("{map:?}");
7604
7605 assert!(map_str == "{1: 2, 3: 4}" || map_str == "{3: 4, 1: 2}");
7606 assert_eq!(format!("{empty:?}"), "{}");
7607 }
7608
7609 #[test]
7610 fn test_expand() {
7611 let mut m = HashMap::new();
7612
7613 assert_eq!(m.len(), 0);
7614 assert!(m.is_empty());
7615
7616 let mut i = 0;
7617 let old_raw_cap = m.raw_capacity();
7618 while old_raw_cap == m.raw_capacity() {
7619 m.insert(i, i);
7620 i += 1;
7621 }
7622
7623 assert_eq!(m.len(), i);
7624 assert!(!m.is_empty());
7625 }
7626
7627 #[test]
7628 fn test_behavior_resize_policy() {
7629 let mut m = HashMap::new();
7630
7631 assert_eq!(m.len(), 0);
7632 assert_eq!(m.raw_capacity(), 1);
7633 assert!(m.is_empty());
7634
7635 m.insert(0, 0);
7636 m.remove(&0);
7637 assert!(m.is_empty());
7638 let initial_raw_cap = m.raw_capacity();
7639 m.reserve(initial_raw_cap);
7640 let raw_cap = m.raw_capacity();
7641
7642 assert_eq!(raw_cap, initial_raw_cap * 2);
7643
7644 let mut i = 0;
7645 for _ in 0..raw_cap * 3 / 4 {
7646 m.insert(i, i);
7647 i += 1;
7648 }
7649 // three quarters full
7650
7651 assert_eq!(m.len(), i);
7652 assert_eq!(m.raw_capacity(), raw_cap);
7653
7654 for _ in 0..raw_cap / 4 {
7655 m.insert(i, i);
7656 i += 1;
7657 }
7658 // half full
7659
7660 let new_raw_cap = m.raw_capacity();
7661 assert_eq!(new_raw_cap, raw_cap * 2);
7662
7663 for _ in 0..raw_cap / 2 - 1 {
7664 i -= 1;
7665 m.remove(&i);
7666 assert_eq!(m.raw_capacity(), new_raw_cap);
7667 }
7668 // A little more than one quarter full.
7669 m.shrink_to_fit();
7670 assert_eq!(m.raw_capacity(), raw_cap);
7671 // again, a little more than half full
7672 for _ in 0..raw_cap / 2 {
7673 i -= 1;
7674 m.remove(&i);
7675 }
7676 m.shrink_to_fit();
7677
7678 assert_eq!(m.len(), i);
7679 assert!(!m.is_empty());
7680 assert_eq!(m.raw_capacity(), initial_raw_cap);
7681 }
7682
7683 #[test]
7684 fn test_reserve_shrink_to_fit() {
7685 let mut m = HashMap::new();
7686 m.insert(0, 0);
7687 m.remove(&0);
7688 assert!(m.capacity() >= m.len());
7689 for i in 0..128 {
7690 m.insert(i, i);
7691 }
7692 m.reserve(256);
7693
7694 let usable_cap = m.capacity();
7695 for i in 128..(128 + 256) {
7696 m.insert(i, i);
7697 assert_eq!(m.capacity(), usable_cap);
7698 }
7699
7700 for i in 100..(128 + 256) {
7701 assert_eq!(m.remove(&i), Some(i));
7702 }
7703 m.shrink_to_fit();
7704
7705 assert_eq!(m.len(), 100);
7706 assert!(!m.is_empty());
7707 assert!(m.capacity() >= m.len());
7708
7709 for i in 0..100 {
7710 assert_eq!(m.remove(&i), Some(i));
7711 }
7712 m.shrink_to_fit();
7713 m.insert(0, 0);
7714
7715 assert_eq!(m.len(), 1);
7716 assert!(m.capacity() >= m.len());
7717 assert_eq!(m.remove(&0), Some(0));
7718 }
7719
7720 #[test]
7721 fn test_from_iter() {
7722 let xs = [(1, 1), (2, 2), (2, 2), (3, 3), (4, 4), (5, 5), (6, 6)];
7723
7724 let map: HashMap<_, _> = xs.iter().copied().collect();
7725
7726 for &(k, v) in &xs {
7727 assert_eq!(map.get(&k), Some(&v));
7728 }
7729
7730 assert_eq!(map.iter().len(), xs.len() - 1);
7731 }
7732
7733 #[test]
7734 fn test_size_hint() {
7735 let xs = [(1, 1), (2, 2), (3, 3), (4, 4), (5, 5), (6, 6)];
7736
7737 let map: HashMap<_, _> = xs.iter().copied().collect();
7738
7739 let mut iter = map.iter();
7740
7741 for _ in iter.by_ref().take(3) {}
7742
7743 assert_eq!(iter.size_hint(), (3, Some(3)));
7744 }
7745
7746 #[test]
7747 fn test_iter_len() {
7748 let xs = [(1, 1), (2, 2), (3, 3), (4, 4), (5, 5), (6, 6)];
7749
7750 let map: HashMap<_, _> = xs.iter().copied().collect();
7751
7752 let mut iter = map.iter();
7753
7754 for _ in iter.by_ref().take(3) {}
7755
7756 assert_eq!(iter.len(), 3);
7757 }
7758
7759 #[test]
7760 fn test_mut_size_hint() {
7761 let xs = [(1, 1), (2, 2), (3, 3), (4, 4), (5, 5), (6, 6)];
7762
7763 let mut map: HashMap<_, _> = xs.iter().copied().collect();
7764
7765 let mut iter = map.iter_mut();
7766
7767 for _ in iter.by_ref().take(3) {}
7768
7769 assert_eq!(iter.size_hint(), (3, Some(3)));
7770 }
7771
7772 #[test]
7773 fn test_iter_mut_len() {
7774 let xs = [(1, 1), (2, 2), (3, 3), (4, 4), (5, 5), (6, 6)];
7775
7776 let mut map: HashMap<_, _> = xs.iter().copied().collect();
7777
7778 let mut iter = map.iter_mut();
7779
7780 for _ in iter.by_ref().take(3) {}
7781
7782 assert_eq!(iter.len(), 3);
7783 }
7784
7785 #[test]
7786 fn test_index() {
7787 let mut map = HashMap::new();
7788
7789 map.insert(1, 2);
7790 map.insert(2, 1);
7791 map.insert(3, 4);
7792
7793 assert_eq!(map[&2], 1);
7794 }
7795
7796 #[test]
7797 #[should_panic]
7798 fn test_index_nonexistent() {
7799 let mut map = HashMap::new();
7800
7801 map.insert(1, 2);
7802 map.insert(2, 1);
7803 map.insert(3, 4);
7804
7805 #[allow(clippy::no_effect)] // false positive lint
7806 map[&4];
7807 }
7808
7809 #[test]
7810 fn test_entry() {
7811 let xs = [(1, 10), (2, 20), (3, 30), (4, 40), (5, 50), (6, 60)];
7812
7813 let mut map: HashMap<_, _> = xs.iter().copied().collect();
7814
7815 // Existing key (insert)
7816 match map.entry(1) {
7817 Vacant(_) => unreachable!(),
7818 Occupied(mut view) => {
7819 assert_eq!(view.get(), &10);
7820 assert_eq!(view.insert(100), 10);
7821 }
7822 }
7823 assert_eq!(map.get(&1).unwrap(), &100);
7824 assert_eq!(map.len(), 6);
7825
7826 // Existing key (update)
7827 match map.entry(2) {
7828 Vacant(_) => unreachable!(),
7829 Occupied(mut view) => {
7830 let v = view.get_mut();
7831 let new_v = (*v) * 10;
7832 *v = new_v;
7833 }
7834 }
7835 assert_eq!(map.get(&2).unwrap(), &200);
7836 assert_eq!(map.len(), 6);
7837
7838 // Existing key (take)
7839 match map.entry(3) {
7840 Vacant(_) => unreachable!(),
7841 Occupied(view) => {
7842 assert_eq!(view.remove(), 30);
7843 }
7844 }
7845 assert_eq!(map.get(&3), None);
7846 assert_eq!(map.len(), 5);
7847
7848 // Inexistent key (insert)
7849 match map.entry(10) {
7850 Occupied(_) => unreachable!(),
7851 Vacant(view) => {
7852 assert_eq!(*view.insert(1000), 1000);
7853 }
7854 }
7855 assert_eq!(map.get(&10).unwrap(), &1000);
7856 assert_eq!(map.len(), 6);
7857 }
7858
7859 #[test]
7860 fn test_entry_ref() {
7861 let xs = [
7862 ("One".to_owned(), 10),
7863 ("Two".to_owned(), 20),
7864 ("Three".to_owned(), 30),
7865 ("Four".to_owned(), 40),
7866 ("Five".to_owned(), 50),
7867 ("Six".to_owned(), 60),
7868 ];
7869
7870 let mut map: HashMap<_, _> = xs.iter().cloned().collect();
7871
7872 // Existing key (insert)
7873 match map.entry_ref("One") {
7874 EntryRef::Vacant(_) => unreachable!(),
7875 EntryRef::Occupied(mut view) => {
7876 assert_eq!(view.get(), &10);
7877 assert_eq!(view.insert(100), 10);
7878 }
7879 }
7880 assert_eq!(map.get("One").unwrap(), &100);
7881 assert_eq!(map.len(), 6);
7882
7883 // Existing key (update)
7884 match map.entry_ref("Two") {
7885 EntryRef::Vacant(_) => unreachable!(),
7886 EntryRef::Occupied(mut view) => {
7887 let v = view.get_mut();
7888 let new_v = (*v) * 10;
7889 *v = new_v;
7890 }
7891 }
7892 assert_eq!(map.get("Two").unwrap(), &200);
7893 assert_eq!(map.len(), 6);
7894
7895 // Existing key (take)
7896 match map.entry_ref("Three") {
7897 EntryRef::Vacant(_) => unreachable!(),
7898 EntryRef::Occupied(view) => {
7899 assert_eq!(view.remove(), 30);
7900 }
7901 }
7902 assert_eq!(map.get("Three"), None);
7903 assert_eq!(map.len(), 5);
7904
7905 // Inexistent key (insert)
7906 match map.entry_ref("Ten") {
7907 EntryRef::Occupied(_) => unreachable!(),
7908 EntryRef::Vacant(view) => {
7909 assert_eq!(*view.insert(1000), 1000);
7910 }
7911 }
7912 assert_eq!(map.get("Ten").unwrap(), &1000);
7913 assert_eq!(map.len(), 6);
7914 }
7915
7916 #[test]
7917 fn test_entry_take_doesnt_corrupt() {
7918 #![allow(deprecated)] //rand
7919 // Test for #19292
7920 fn check(m: &HashMap<i32, ()>) {
7921 for k in m.keys() {
7922 assert!(m.contains_key(k), "{k} is in keys() but not in the map?");
7923 }
7924 }
7925
7926 let mut m = HashMap::new();
7927
7928 let mut rng = {
7929 let seed = u64::from_le_bytes(*b"testseed");
7930 SmallRng::seed_from_u64(seed)
7931 };
7932
7933 // Populate the map with some items.
7934 for _ in 0..50 {
7935 let x = rng.gen_range(-10..10);
7936 m.insert(x, ());
7937 }
7938
7939 for _ in 0..1000 {
7940 let x = rng.gen_range(-10..10);
7941 match m.entry(x) {
7942 Vacant(_) => {}
7943 Occupied(e) => {
7944 e.remove();
7945 }
7946 }
7947
7948 check(&m);
7949 }
7950 }
7951
7952 #[test]
7953 fn test_entry_ref_take_doesnt_corrupt() {
7954 #![allow(deprecated)] //rand
7955 // Test for #19292
7956 fn check(m: &HashMap<String, ()>) {
7957 for k in m.keys() {
7958 assert!(m.contains_key(k), "{k} is in keys() but not in the map?");
7959 }
7960 }
7961
7962 let mut m = HashMap::new();
7963
7964 let mut rng = {
7965 let seed = u64::from_le_bytes(*b"testseed");
7966 SmallRng::seed_from_u64(seed)
7967 };
7968
7969 // Populate the map with some items.
7970 for _ in 0..50 {
7971 let mut x = String::with_capacity(1);
7972 x.push(rng.gen_range('a'..='z'));
7973 m.insert(x, ());
7974 }
7975
7976 for _ in 0..1000 {
7977 let mut x = String::with_capacity(1);
7978 x.push(rng.gen_range('a'..='z'));
7979 match m.entry_ref(x.as_str()) {
7980 EntryRef::Vacant(_) => {}
7981 EntryRef::Occupied(e) => {
7982 e.remove();
7983 }
7984 }
7985
7986 check(&m);
7987 }
7988 }
7989
7990 #[test]
7991 fn test_extend_ref_k_ref_v() {
7992 let mut a = HashMap::new();
7993 a.insert(1, "one");
7994 let mut b = HashMap::new();
7995 b.insert(2, "two");
7996 b.insert(3, "three");
7997
7998 a.extend(&b);
7999
8000 assert_eq!(a.len(), 3);
8001 assert_eq!(a[&1], "one");
8002 assert_eq!(a[&2], "two");
8003 assert_eq!(a[&3], "three");
8004 }
8005
8006 #[test]
8007 #[allow(clippy::needless_borrow)]
8008 fn test_extend_ref_kv_tuple() {
8009 let mut a = HashMap::new();
8010 a.insert(0, 0);
8011
8012 fn create_arr<T: AddAssign<T> + Copy, const N: usize>(start: T, step: T) -> [(T, T); N] {
8013 let mut outs: [(T, T); N] = [(start, start); N];
8014 let mut element = step;
8015 outs.iter_mut().skip(1).for_each(|(k, v)| {
8016 *k += element;
8017 *v += element;
8018 element += step;
8019 });
8020 outs
8021 }
8022
8023 let for_iter: Vec<_> = (0..100).map(|i| (i, i)).collect();
8024 let iter = for_iter.iter();
8025 let vec: Vec<_> = (100..200).map(|i| (i, i)).collect();
8026 a.try_extend(iter).abort();
8027 a.try_extend(&vec).abort();
8028 a.try_extend(create_arr::<i32, 100>(200, 1)).abort();
8029
8030 assert_eq!(a.len(), 300);
8031
8032 for item in 0..300 {
8033 assert_eq!(a[&item], item);
8034 }
8035 }
8036
8037 #[test]
8038 fn test_capacity_not_less_than_len() {
8039 let mut a = HashMap::new();
8040 let mut item = 0;
8041
8042 for _ in 0..116 {
8043 a.insert(item, 0);
8044 item += 1;
8045 }
8046
8047 assert!(a.capacity() > a.len());
8048
8049 let free = a.capacity() - a.len();
8050 for _ in 0..free {
8051 a.insert(item, 0);
8052 item += 1;
8053 }
8054
8055 assert_eq!(a.len(), a.capacity());
8056
8057 // Insert at capacity should cause allocation.
8058 a.insert(item, 0);
8059 assert!(a.capacity() > a.len());
8060 }
8061
8062 #[test]
8063 fn test_occupied_entry_key() {
8064 let mut a = HashMap::new();
8065 let key = "hello there";
8066 let value = "value goes here";
8067 assert!(a.is_empty());
8068 a.insert(key, value);
8069 assert_eq!(a.len(), 1);
8070 assert_eq!(a[key], value);
8071
8072 match a.entry(key) {
8073 Vacant(_) => panic!(),
8074 Occupied(e) => assert_eq!(key, *e.key()),
8075 }
8076 assert_eq!(a.len(), 1);
8077 assert_eq!(a[key], value);
8078 }
8079
8080 #[test]
8081 fn test_occupied_entry_ref_key() {
8082 let mut a = HashMap::new();
8083 let key = "hello there";
8084 let value = "value goes here";
8085 assert!(a.is_empty());
8086 a.insert(key.to_owned(), value);
8087 assert_eq!(a.len(), 1);
8088 assert_eq!(a[key], value);
8089
8090 match a.entry_ref(key) {
8091 EntryRef::Vacant(_) => panic!(),
8092 EntryRef::Occupied(e) => assert_eq!(key, e.key()),
8093 }
8094 assert_eq!(a.len(), 1);
8095 assert_eq!(a[key], value);
8096 }
8097
8098 #[test]
8099 fn test_vacant_entry_key() {
8100 let mut a = HashMap::new();
8101 let key = "hello there";
8102 let value = "value goes here";
8103
8104 assert!(a.is_empty());
8105 match a.entry(key) {
8106 Occupied(_) => panic!(),
8107 Vacant(e) => {
8108 assert_eq!(key, *e.key());
8109 e.insert(value);
8110 }
8111 }
8112 assert_eq!(a.len(), 1);
8113 assert_eq!(a[key], value);
8114 }
8115
8116 #[test]
8117 fn test_vacant_entry_ref_key() {
8118 let mut a: HashMap<String, &str> = HashMap::new();
8119 let key = "hello there";
8120 let value = "value goes here";
8121
8122 assert!(a.is_empty());
8123 match a.entry_ref(key) {
8124 EntryRef::Occupied(_) => panic!(),
8125 EntryRef::Vacant(e) => {
8126 assert_eq!(key, e.key());
8127 e.insert(value);
8128 }
8129 }
8130 assert_eq!(a.len(), 1);
8131 assert_eq!(a[key], value);
8132 }
8133
8134 #[test]
8135 fn test_occupied_entry_replace_entry_with() {
8136 let mut a = HashMap::new();
8137
8138 let key = "a key";
8139 let value = "an initial value";
8140 let new_value = "a new value";
8141
8142 let entry = a.entry(key).insert(value).replace_entry_with(|k, v| {
8143 assert_eq!(k, &key);
8144 assert_eq!(v, value);
8145 Some(new_value)
8146 });
8147
8148 match entry {
8149 Occupied(e) => {
8150 assert_eq!(e.key(), &key);
8151 assert_eq!(e.get(), &new_value);
8152 }
8153 Vacant(_) => panic!(),
8154 }
8155
8156 assert_eq!(a[key], new_value);
8157 assert_eq!(a.len(), 1);
8158
8159 let entry = match a.entry(key) {
8160 Occupied(e) => e.replace_entry_with(|k, v| {
8161 assert_eq!(k, &key);
8162 assert_eq!(v, new_value);
8163 None
8164 }),
8165 Vacant(_) => panic!(),
8166 };
8167
8168 match entry {
8169 Vacant(e) => assert_eq!(e.key(), &key),
8170 Occupied(_) => panic!(),
8171 }
8172
8173 assert!(!a.contains_key(key));
8174 assert_eq!(a.len(), 0);
8175 }
8176
8177 #[test]
8178 fn test_occupied_entry_ref_replace_entry_with() {
8179 let mut a: HashMap<String, &str> = HashMap::new();
8180
8181 let key = "a key";
8182 let value = "an initial value";
8183 let new_value = "a new value";
8184
8185 let entry = a.entry_ref(key).insert(value).replace_entry_with(|k, v| {
8186 assert_eq!(k, key);
8187 assert_eq!(v, value);
8188 Some(new_value)
8189 });
8190
8191 match entry {
8192 EntryRef::Occupied(e) => {
8193 assert_eq!(e.key(), key);
8194 assert_eq!(e.get(), &new_value);
8195 }
8196 EntryRef::Vacant(_) => panic!(),
8197 }
8198
8199 assert_eq!(a[key], new_value);
8200 assert_eq!(a.len(), 1);
8201
8202 let entry = match a.entry_ref(key) {
8203 EntryRef::Occupied(e) => e.replace_entry_with(|k, v| {
8204 assert_eq!(k, key);
8205 assert_eq!(v, new_value);
8206 None
8207 }),
8208 EntryRef::Vacant(_) => panic!(),
8209 };
8210
8211 match entry {
8212 EntryRef::Vacant(e) => assert_eq!(e.key(), key),
8213 EntryRef::Occupied(_) => panic!(),
8214 }
8215
8216 assert!(!a.contains_key(key));
8217 assert_eq!(a.len(), 0);
8218 }
8219
8220 #[test]
8221 fn test_entry_and_replace_entry_with() {
8222 let mut a = HashMap::new();
8223
8224 let key = "a key";
8225 let value = "an initial value";
8226 let new_value = "a new value";
8227
8228 let entry = a.entry(key).and_replace_entry_with(|_, _| panic!());
8229
8230 match entry {
8231 Vacant(e) => assert_eq!(e.key(), &key),
8232 Occupied(_) => panic!(),
8233 }
8234
8235 a.insert(key, value);
8236
8237 let entry = a.entry(key).and_replace_entry_with(|k, v| {
8238 assert_eq!(k, &key);
8239 assert_eq!(v, value);
8240 Some(new_value)
8241 });
8242
8243 match entry {
8244 Occupied(e) => {
8245 assert_eq!(e.key(), &key);
8246 assert_eq!(e.get(), &new_value);
8247 }
8248 Vacant(_) => panic!(),
8249 }
8250
8251 assert_eq!(a[key], new_value);
8252 assert_eq!(a.len(), 1);
8253
8254 let entry = a.entry(key).and_replace_entry_with(|k, v| {
8255 assert_eq!(k, &key);
8256 assert_eq!(v, new_value);
8257 None
8258 });
8259
8260 match entry {
8261 Vacant(e) => assert_eq!(e.key(), &key),
8262 Occupied(_) => panic!(),
8263 }
8264
8265 assert!(!a.contains_key(key));
8266 assert_eq!(a.len(), 0);
8267 }
8268
8269 #[test]
8270 fn test_entry_ref_and_replace_entry_with() {
8271 let mut a = HashMap::new();
8272
8273 let key = "a key";
8274 let value = "an initial value";
8275 let new_value = "a new value";
8276
8277 let entry = a.entry_ref(key).and_replace_entry_with(|_, _| panic!());
8278
8279 match entry {
8280 EntryRef::Vacant(e) => assert_eq!(e.key(), key),
8281 EntryRef::Occupied(_) => panic!(),
8282 }
8283
8284 a.insert(key.to_owned(), value);
8285
8286 let entry = a.entry_ref(key).and_replace_entry_with(|k, v| {
8287 assert_eq!(k, key);
8288 assert_eq!(v, value);
8289 Some(new_value)
8290 });
8291
8292 match entry {
8293 EntryRef::Occupied(e) => {
8294 assert_eq!(e.key(), key);
8295 assert_eq!(e.get(), &new_value);
8296 }
8297 EntryRef::Vacant(_) => panic!(),
8298 }
8299
8300 assert_eq!(a[key], new_value);
8301 assert_eq!(a.len(), 1);
8302
8303 let entry = a.entry_ref(key).and_replace_entry_with(|k, v| {
8304 assert_eq!(k, key);
8305 assert_eq!(v, new_value);
8306 None
8307 });
8308
8309 match entry {
8310 EntryRef::Vacant(e) => assert_eq!(e.key(), key),
8311 EntryRef::Occupied(_) => panic!(),
8312 }
8313
8314 assert!(!a.contains_key(key));
8315 assert_eq!(a.len(), 0);
8316 }
8317
8318 #[test]
8319 fn test_raw_occupied_entry_replace_entry_with() {
8320 let mut a = HashMap::new();
8321
8322 let key = "a key";
8323 let value = "an initial value";
8324 let new_value = "a new value";
8325
8326 let entry = a
8327 .raw_entry_mut()
8328 .from_key(&key)
8329 .insert(key, value)
8330 .replace_entry_with(|k, v| {
8331 assert_eq!(k, &key);
8332 assert_eq!(v, value);
8333 Some(new_value)
8334 });
8335
8336 match entry {
8337 RawEntryMut::Occupied(e) => {
8338 assert_eq!(e.key(), &key);
8339 assert_eq!(e.get(), &new_value);
8340 }
8341 RawEntryMut::Vacant(_) => panic!(),
8342 }
8343
8344 assert_eq!(a[key], new_value);
8345 assert_eq!(a.len(), 1);
8346
8347 let entry = match a.raw_entry_mut().from_key(&key) {
8348 RawEntryMut::Occupied(e) => e.replace_entry_with(|k, v| {
8349 assert_eq!(k, &key);
8350 assert_eq!(v, new_value);
8351 None
8352 }),
8353 RawEntryMut::Vacant(_) => panic!(),
8354 };
8355
8356 match entry {
8357 RawEntryMut::Vacant(_) => {}
8358 RawEntryMut::Occupied(_) => panic!(),
8359 }
8360
8361 assert!(!a.contains_key(key));
8362 assert_eq!(a.len(), 0);
8363 }
8364
8365 #[test]
8366 fn test_raw_entry_and_replace_entry_with() {
8367 let mut a = HashMap::new();
8368
8369 let key = "a key";
8370 let value = "an initial value";
8371 let new_value = "a new value";
8372
8373 let entry = a
8374 .raw_entry_mut()
8375 .from_key(&key)
8376 .and_replace_entry_with(|_, _| panic!());
8377
8378 match entry {
8379 RawEntryMut::Vacant(_) => {}
8380 RawEntryMut::Occupied(_) => panic!(),
8381 }
8382
8383 a.insert(key, value);
8384
8385 let entry = a
8386 .raw_entry_mut()
8387 .from_key(&key)
8388 .and_replace_entry_with(|k, v| {
8389 assert_eq!(k, &key);
8390 assert_eq!(v, value);
8391 Some(new_value)
8392 });
8393
8394 match entry {
8395 RawEntryMut::Occupied(e) => {
8396 assert_eq!(e.key(), &key);
8397 assert_eq!(e.get(), &new_value);
8398 }
8399 RawEntryMut::Vacant(_) => panic!(),
8400 }
8401
8402 assert_eq!(a[key], new_value);
8403 assert_eq!(a.len(), 1);
8404
8405 let entry = a
8406 .raw_entry_mut()
8407 .from_key(&key)
8408 .and_replace_entry_with(|k, v| {
8409 assert_eq!(k, &key);
8410 assert_eq!(v, new_value);
8411 None
8412 });
8413
8414 match entry {
8415 RawEntryMut::Vacant(_) => {}
8416 RawEntryMut::Occupied(_) => panic!(),
8417 }
8418
8419 assert!(!a.contains_key(key));
8420 assert_eq!(a.len(), 0);
8421 }
8422
8423 #[test]
8424 fn test_replace_entry_with_doesnt_corrupt() {
8425 #![allow(deprecated)] //rand
8426 // Test for #19292
8427 fn check(m: &HashMap<i32, ()>) {
8428 for k in m.keys() {
8429 assert!(m.contains_key(k), "{k} is in keys() but not in the map?");
8430 }
8431 }
8432
8433 let mut m = HashMap::new();
8434
8435 let mut rng = {
8436 let seed = u64::from_le_bytes(*b"testseed");
8437 SmallRng::seed_from_u64(seed)
8438 };
8439
8440 // Populate the map with some items.
8441 for _ in 0..50 {
8442 let x = rng.gen_range(-10..10);
8443 m.insert(x, ());
8444 }
8445
8446 for _ in 0..1000 {
8447 let x = rng.gen_range(-10..10);
8448 m.entry(x).and_replace_entry_with(|_, _| None);
8449 check(&m);
8450 }
8451 }
8452
8453 #[test]
8454 fn test_replace_entry_ref_with_doesnt_corrupt() {
8455 #![allow(deprecated)] //rand
8456 // Test for #19292
8457 fn check(m: &HashMap<String, ()>) {
8458 for k in m.keys() {
8459 assert!(m.contains_key(k), "{k} is in keys() but not in the map?");
8460 }
8461 }
8462
8463 let mut m = HashMap::new();
8464
8465 let mut rng = {
8466 let seed = u64::from_le_bytes(*b"testseed");
8467 SmallRng::seed_from_u64(seed)
8468 };
8469
8470 // Populate the map with some items.
8471 for _ in 0..50 {
8472 let mut x = String::with_capacity(1);
8473 x.push(rng.gen_range('a'..='z'));
8474 m.insert(x, ());
8475 }
8476
8477 for _ in 0..1000 {
8478 let mut x = String::with_capacity(1);
8479 x.push(rng.gen_range('a'..='z'));
8480 m.entry_ref(x.as_str()).and_replace_entry_with(|_, _| None);
8481 check(&m);
8482 }
8483 }
8484
8485 #[test]
8486 fn test_retain() {
8487 let mut map: HashMap<i32, i32> = (0..100).map(|x| (x, x * 10)).collect();
8488
8489 map.retain(|&k, _| k % 2 == 0);
8490 assert_eq!(map.len(), 50);
8491 assert_eq!(map[&2], 20);
8492 assert_eq!(map[&4], 40);
8493 assert_eq!(map[&6], 60);
8494 }
8495
8496 #[test]
8497 fn test_extract_if() {
8498 {
8499 let mut map: HashMap<i32, i32> = (0..8).map(|x| (x, x * 10)).collect();
8500 let drained = map.extract_if(|&k, _| k % 2 == 0);
8501 let mut out = drained.collect::<Vec<_>>();
8502 out.sort_unstable();
8503 assert_eq!(::rust_alloc::vec![(0, 0), (2, 20), (4, 40), (6, 60)], out);
8504 assert_eq!(map.len(), 4);
8505 }
8506 {
8507 let mut map: HashMap<i32, i32> = (0..8).map(|x| (x, x * 10)).collect();
8508 map.extract_if(|&k, _| k % 2 == 0).for_each(drop);
8509 assert_eq!(map.len(), 4);
8510 }
8511 }
8512
8513 #[test]
8514 #[cfg_attr(miri, ignore)] // FIXME: no OOM signalling (https://github.com/rust-lang/miri/issues/613)
8515 fn test_try_reserve() {
8516 use crate::error::Error::{AllocError, CapacityOverflow};
8517
8518 const MAX_ISIZE: usize = isize::MAX as usize;
8519
8520 let mut empty_bytes: HashMap<u8, u8> = HashMap::new();
8521
8522 if let Err(CapacityOverflow) = empty_bytes.try_reserve(usize::MAX) {
8523 } else {
8524 panic!("usize::MAX should trigger an overflow!");
8525 }
8526
8527 if let Err(CapacityOverflow) = empty_bytes.try_reserve(MAX_ISIZE) {
8528 } else {
8529 panic!("isize::MAX should trigger an overflow!");
8530 }
8531
8532 if let Err(AllocError { .. }) = empty_bytes.try_reserve(MAX_ISIZE / 5) {
8533 } else {
8534 // This may succeed if there is enough free memory. Attempt to
8535 // allocate a few more hashmaps to ensure the allocation will fail.
8536 let mut empty_bytes2: HashMap<u8, u8> = HashMap::new();
8537 let _ = empty_bytes2.try_reserve(MAX_ISIZE / 5);
8538 let mut empty_bytes3: HashMap<u8, u8> = HashMap::new();
8539 let _ = empty_bytes3.try_reserve(MAX_ISIZE / 5);
8540 let mut empty_bytes4: HashMap<u8, u8> = HashMap::new();
8541 if let Err(AllocError { .. }) = empty_bytes4.try_reserve(MAX_ISIZE / 5) {
8542 } else {
8543 panic!("isize::MAX / 5 should trigger an OOM!");
8544 }
8545 }
8546 }
8547
8548 #[test]
8549 fn test_raw_entry() {
8550 use super::RawEntryMut::{Occupied, Vacant};
8551
8552 let xs = [(1_i32, 10_i32), (2, 20), (3, 30), (4, 40), (5, 50), (6, 60)];
8553
8554 let mut map: HashMap<_, _> = xs.iter().copied().collect();
8555
8556 let compute_hash = |map: &HashMap<i32, i32>, k: i32| -> u64 {
8557 super::make_hash::<i32, _>(map.hasher(), &k)
8558 };
8559
8560 // Existing key (insert)
8561 match map.raw_entry_mut().from_key(&1) {
8562 Vacant(_) => unreachable!(),
8563 Occupied(mut view) => {
8564 assert_eq!(view.get(), &10);
8565 assert_eq!(view.insert(100), 10);
8566 }
8567 }
8568 let hash1 = compute_hash(&map, 1);
8569 assert_eq!(map.raw_entry().from_key(&1).unwrap(), (&1, &100));
8570 assert_eq!(
8571 map.raw_entry().from_hash(hash1, |k| *k == 1).unwrap(),
8572 (&1, &100)
8573 );
8574 assert_eq!(
8575 map.raw_entry().from_key_hashed_nocheck(hash1, &1).unwrap(),
8576 (&1, &100)
8577 );
8578 assert_eq!(map.len(), 6);
8579
8580 // Existing key (update)
8581 match map.raw_entry_mut().from_key(&2) {
8582 Vacant(_) => unreachable!(),
8583 Occupied(mut view) => {
8584 let v = view.get_mut();
8585 let new_v = (*v) * 10;
8586 *v = new_v;
8587 }
8588 }
8589 let hash2 = compute_hash(&map, 2);
8590 assert_eq!(map.raw_entry().from_key(&2).unwrap(), (&2, &200));
8591 assert_eq!(
8592 map.raw_entry().from_hash(hash2, |k| *k == 2).unwrap(),
8593 (&2, &200)
8594 );
8595 assert_eq!(
8596 map.raw_entry().from_key_hashed_nocheck(hash2, &2).unwrap(),
8597 (&2, &200)
8598 );
8599 assert_eq!(map.len(), 6);
8600
8601 // Existing key (take)
8602 let hash3 = compute_hash(&map, 3);
8603 match map.raw_entry_mut().from_key_hashed_nocheck(hash3, &3) {
8604 Vacant(_) => unreachable!(),
8605 Occupied(view) => {
8606 assert_eq!(view.remove_entry(), (3, 30));
8607 }
8608 }
8609 assert_eq!(map.raw_entry().from_key(&3), None);
8610 assert_eq!(map.raw_entry().from_hash(hash3, |k| *k == 3), None);
8611 assert_eq!(map.raw_entry().from_key_hashed_nocheck(hash3, &3), None);
8612 assert_eq!(map.len(), 5);
8613
8614 // Nonexistent key (insert)
8615 match map.raw_entry_mut().from_key(&10) {
8616 Occupied(_) => unreachable!(),
8617 Vacant(view) => {
8618 assert_eq!(view.insert(10, 1000), (&mut 10, &mut 1000));
8619 }
8620 }
8621 assert_eq!(map.raw_entry().from_key(&10).unwrap(), (&10, &1000));
8622 assert_eq!(map.len(), 6);
8623
8624 // Ensure all lookup methods produce equivalent results.
8625 for k in 0..12 {
8626 let hash = compute_hash(&map, k);
8627 let v = map.get(&k).copied();
8628 let kv = v.as_ref().map(|v| (&k, v));
8629
8630 assert_eq!(map.raw_entry().from_key(&k), kv);
8631 assert_eq!(map.raw_entry().from_hash(hash, |q| *q == k), kv);
8632 assert_eq!(map.raw_entry().from_key_hashed_nocheck(hash, &k), kv);
8633
8634 match map.raw_entry_mut().from_key(&k) {
8635 Occupied(o) => assert_eq!(Some(o.get_key_value()), kv),
8636 Vacant(_) => assert_eq!(v, None),
8637 }
8638 match map.raw_entry_mut().from_key_hashed_nocheck(hash, &k) {
8639 Occupied(o) => assert_eq!(Some(o.get_key_value()), kv),
8640 Vacant(_) => assert_eq!(v, None),
8641 }
8642 match map.raw_entry_mut().from_hash(hash, |q| *q == k) {
8643 Occupied(o) => assert_eq!(Some(o.get_key_value()), kv),
8644 Vacant(_) => assert_eq!(v, None),
8645 }
8646 }
8647 }
8648
8649 #[test]
8650 fn test_key_without_hash_impl() {
8651 #[derive(Debug)]
8652 struct IntWrapper(u64);
8653
8654 let mut m: HashMap<IntWrapper, (), ()> = HashMap::default();
8655 {
8656 assert!(m.raw_entry().from_hash(0, |k| k.0 == 0).is_none());
8657 }
8658 {
8659 let vacant_entry = match m.raw_entry_mut().from_hash(0, |k| k.0 == 0) {
8660 RawEntryMut::Occupied(..) => panic!("Found entry for key 0"),
8661 RawEntryMut::Vacant(e) => e,
8662 };
8663 vacant_entry.insert_with_hasher(0, IntWrapper(0), (), |k| k.0);
8664 }
8665 {
8666 assert!(m.raw_entry().from_hash(0, |k| k.0 == 0).is_some());
8667 assert!(m.raw_entry().from_hash(1, |k| k.0 == 1).is_none());
8668 assert!(m.raw_entry().from_hash(2, |k| k.0 == 2).is_none());
8669 }
8670 {
8671 let vacant_entry = match m.raw_entry_mut().from_hash(1, |k| k.0 == 1) {
8672 RawEntryMut::Occupied(..) => panic!("Found entry for key 1"),
8673 RawEntryMut::Vacant(e) => e,
8674 };
8675 vacant_entry.insert_with_hasher(1, IntWrapper(1), (), |k| k.0);
8676 }
8677 {
8678 assert!(m.raw_entry().from_hash(0, |k| k.0 == 0).is_some());
8679 assert!(m.raw_entry().from_hash(1, |k| k.0 == 1).is_some());
8680 assert!(m.raw_entry().from_hash(2, |k| k.0 == 2).is_none());
8681 }
8682 {
8683 let occupied_entry = match m.raw_entry_mut().from_hash(0, |k| k.0 == 0) {
8684 RawEntryMut::Occupied(e) => e,
8685 RawEntryMut::Vacant(..) => panic!("Couldn't find entry for key 0"),
8686 };
8687 occupied_entry.remove();
8688 }
8689 assert!(m.raw_entry().from_hash(0, |k| k.0 == 0).is_none());
8690 assert!(m.raw_entry().from_hash(1, |k| k.0 == 1).is_some());
8691 assert!(m.raw_entry().from_hash(2, |k| k.0 == 2).is_none());
8692 }
8693
8694 #[test]
8695 fn test_into_iter_refresh() {
8696 #[cfg(miri)]
8697 const N: usize = 32;
8698 #[cfg(not(miri))]
8699 const N: usize = 128;
8700
8701 let mut rng = rand::thread_rng();
8702 for n in 0..N {
8703 let mut map = HashMap::new();
8704 for i in 0..n {
8705 assert!(map.try_insert(i, 2 * i).unwrap().is_none());
8706 }
8707 let hash_builder = map.hasher().clone();
8708
8709 let mut it = unsafe { map.table.iter() };
8710 assert_eq!(it.len(), n);
8711
8712 let mut i = 0;
8713 let mut left = n;
8714 let mut removed = Vec::new();
8715 loop {
8716 // occasionally remove some elements
8717 if i < n && rng.gen_bool(0.1) {
8718 let hash_value = super::make_hash(&hash_builder, &i);
8719
8720 unsafe {
8721 let e = into_ok(map.table.find(
8722 &mut (),
8723 hash_value,
8724 |_: &mut (), q: &(usize, _)| Ok(q.0.eq(&i)),
8725 ));
8726 if let Some(e) = e {
8727 it.reflect_remove(&e);
8728 let t = map.table.remove(e).0;
8729 removed.push(t);
8730 left -= 1;
8731 } else {
8732 assert!(removed.contains(&(i, 2 * i)), "{i} not in {removed:?}");
8733 let e = into_ok_try(map.table.insert(
8734 &mut (),
8735 hash_value,
8736 (i, 2 * i),
8737 super::make_hasher(&hash_builder),
8738 ))
8739 .unwrap();
8740 it.reflect_insert(&e);
8741 if let Some(p) = removed.iter().position(|e| e == &(i, 2 * i)) {
8742 removed.swap_remove(p);
8743 }
8744 left += 1;
8745 }
8746 }
8747 }
8748
8749 let e = it.next();
8750 if e.is_none() {
8751 break;
8752 }
8753 assert!(i < n);
8754 let t = unsafe { e.unwrap().as_ref() };
8755 assert!(!removed.contains(t));
8756 let (key, value) = t;
8757 assert_eq!(*value, 2 * key);
8758 i += 1;
8759 }
8760 assert!(i <= n);
8761
8762 // just for safety:
8763 assert_eq!(map.table.len(), left);
8764 }
8765 }
8766
8767 #[test]
8768 fn test_const_with_hasher() {
8769 #[derive(Clone)]
8770 struct MyHasher;
8771 impl BuildHasher for MyHasher {
8772 type Hasher = DefaultHasher;
8773
8774 fn build_hasher(&self) -> DefaultHasher {
8775 DefaultHasher::new()
8776 }
8777 }
8778
8779 const EMPTY_MAP: HashMap<u32, String, MyHasher> = HashMap::with_hasher(MyHasher);
8780
8781 let mut map = EMPTY_MAP;
8782 map.try_insert(17, "seventeen".to_owned()).unwrap();
8783 assert_eq!("seventeen", map[&17]);
8784 }
8785
8786 #[test]
8787 fn test_get_each_mut() {
8788 let mut map = HashMap::new();
8789 map.try_insert("foo".to_owned(), 0).unwrap();
8790 map.try_insert("bar".to_owned(), 10).unwrap();
8791 map.try_insert("baz".to_owned(), 20).unwrap();
8792 map.try_insert("qux".to_owned(), 30).unwrap();
8793
8794 let xs = map.get_many_mut(["foo", "qux"]);
8795 assert_eq!(xs, Some([&mut 0, &mut 30]));
8796
8797 let xs = map.get_many_mut(["foo", "dud"]);
8798 assert_eq!(xs, None);
8799
8800 let xs = map.get_many_mut(["foo", "foo"]);
8801 assert_eq!(xs, None);
8802
8803 let ys = map.get_many_key_value_mut(["bar", "baz"]);
8804 assert_eq!(
8805 ys,
8806 Some([(&"bar".to_owned(), &mut 10), (&"baz".to_owned(), &mut 20),]),
8807 );
8808
8809 let ys = map.get_many_key_value_mut(["bar", "dip"]);
8810 assert_eq!(ys, None);
8811
8812 let ys = map.get_many_key_value_mut(["baz", "baz"]);
8813 assert_eq!(ys, None);
8814 }
8815
8816 #[test]
8817 #[should_panic = "panic in drop"]
8818 fn test_clone_from_double_drop() {
8819 struct CheckedDrop {
8820 panic_in_drop: bool,
8821 dropped: bool,
8822 }
8823 impl Drop for CheckedDrop {
8824 fn drop(&mut self) {
8825 if self.panic_in_drop {
8826 self.dropped = true;
8827 panic!("panic in drop");
8828 }
8829 if self.dropped {
8830 panic!("double drop");
8831 }
8832 self.dropped = true;
8833 }
8834 }
8835 impl TryClone for CheckedDrop {
8836 fn try_clone(&self) -> Result<Self, crate::error::Error> {
8837 Ok(Self {
8838 panic_in_drop: self.panic_in_drop,
8839 dropped: self.dropped,
8840 })
8841 }
8842 }
8843 const DISARMED: CheckedDrop = CheckedDrop {
8844 panic_in_drop: false,
8845 dropped: false,
8846 };
8847 const ARMED: CheckedDrop = CheckedDrop {
8848 panic_in_drop: true,
8849 dropped: false,
8850 };
8851
8852 let mut map1 = HashMap::new();
8853 map1.try_insert(1, DISARMED).unwrap();
8854 map1.try_insert(2, DISARMED).unwrap();
8855 map1.try_insert(3, DISARMED).unwrap();
8856 map1.try_insert(4, DISARMED).unwrap();
8857
8858 let mut map2 = HashMap::new();
8859 map2.try_insert(1, DISARMED).unwrap();
8860 map2.try_insert(2, ARMED).unwrap();
8861 map2.try_insert(3, DISARMED).unwrap();
8862 map2.try_insert(4, DISARMED).unwrap();
8863
8864 map2.try_clone_from(&map1).unwrap();
8865 }
8866
8867 #[test]
8868 #[should_panic = "panic in clone"]
8869 fn test_clone_from_memory_leaks() {
8870 use ::rust_alloc::vec::Vec;
8871
8872 struct CheckedClone {
8873 panic_in_clone: bool,
8874 need_drop: Vec<i32>,
8875 }
8876 impl TryClone for CheckedClone {
8877 fn try_clone(&self) -> Result<Self, Error> {
8878 if self.panic_in_clone {
8879 panic!("panic in clone")
8880 }
8881 Ok(Self {
8882 panic_in_clone: self.panic_in_clone,
8883 need_drop: self.need_drop.clone(),
8884 })
8885 }
8886 }
8887 let mut map1 = HashMap::new();
8888 map1.try_insert(
8889 1,
8890 CheckedClone {
8891 panic_in_clone: false,
8892 need_drop: ::rust_alloc::vec![0, 1, 2],
8893 },
8894 )
8895 .unwrap();
8896 map1.try_insert(
8897 2,
8898 CheckedClone {
8899 panic_in_clone: false,
8900 need_drop: ::rust_alloc::vec![3, 4, 5],
8901 },
8902 )
8903 .unwrap();
8904 map1.try_insert(
8905 3,
8906 CheckedClone {
8907 panic_in_clone: true,
8908 need_drop: ::rust_alloc::vec![6, 7, 8],
8909 },
8910 )
8911 .unwrap();
8912 let _map2 = map1.try_clone().unwrap();
8913 }
8914
8915 struct MyAllocInner {
8916 drop_count: Arc<AtomicI8>,
8917 }
8918
8919 #[derive(Clone)]
8920 struct MyAlloc {
8921 _inner: Arc<MyAllocInner>,
8922 }
8923
8924 impl MyAlloc {
8925 fn new(drop_count: Arc<AtomicI8>) -> Self {
8926 MyAlloc {
8927 _inner: Arc::new(MyAllocInner { drop_count }),
8928 }
8929 }
8930 }
8931
8932 impl Drop for MyAllocInner {
8933 fn drop(&mut self) {
8934 println!("MyAlloc freed.");
8935 self.drop_count.fetch_sub(1, Ordering::SeqCst);
8936 }
8937 }
8938
8939 unsafe impl Allocator for MyAlloc {
8940 fn allocate(&self, layout: Layout) -> Result<NonNull<[u8]>, AllocError> {
8941 let g = Global;
8942 g.allocate(layout)
8943 }
8944
8945 unsafe fn deallocate(&self, ptr: NonNull<u8>, layout: Layout) {
8946 let g = Global;
8947 g.deallocate(ptr, layout)
8948 }
8949 }
8950
8951 #[test]
8952 fn test_hashmap_into_iter_bug() {
8953 let dropped: Arc<AtomicI8> = Arc::new(AtomicI8::new(1));
8954
8955 {
8956 let mut map = HashMap::try_with_capacity_in(10, MyAlloc::new(dropped.clone())).unwrap();
8957 for i in 0..10 {
8958 map.entry(i).or_try_insert_with(|| "i".to_string()).unwrap();
8959 }
8960
8961 for (k, v) in map {
8962 println!("{}, {}", k, v);
8963 }
8964 }
8965
8966 // All allocator clones should already be dropped.
8967 assert_eq!(dropped.load(Ordering::SeqCst), 0);
8968 }
8969
8970 #[derive(Debug)]
8971 struct CheckedCloneDrop<T> {
8972 panic_in_clone: bool,
8973 panic_in_drop: bool,
8974 dropped: bool,
8975 data: T,
8976 }
8977
8978 impl<T> CheckedCloneDrop<T> {
8979 fn new(panic_in_clone: bool, panic_in_drop: bool, data: T) -> Self {
8980 CheckedCloneDrop {
8981 panic_in_clone,
8982 panic_in_drop,
8983 dropped: false,
8984 data,
8985 }
8986 }
8987 }
8988
8989 impl<T> TryClone for CheckedCloneDrop<T>
8990 where
8991 T: TryClone,
8992 {
8993 fn try_clone(&self) -> Result<Self, Error> {
8994 if self.panic_in_clone {
8995 panic!("panic in clone")
8996 }
8997 Ok(Self {
8998 panic_in_clone: self.panic_in_clone,
8999 panic_in_drop: self.panic_in_drop,
9000 dropped: self.dropped,
9001 data: self.data.try_clone()?,
9002 })
9003 }
9004 }
9005
9006 impl<T> Drop for CheckedCloneDrop<T> {
9007 fn drop(&mut self) {
9008 if self.panic_in_drop {
9009 self.dropped = true;
9010 panic!("panic in drop");
9011 }
9012 if self.dropped {
9013 panic!("double drop");
9014 }
9015 self.dropped = true;
9016 }
9017 }
9018
9019 /// Return hashmap with predefined distribution of elements.
9020 /// All elements will be located in the same order as elements
9021 /// returned by iterator.
9022 ///
9023 /// This function does not panic, but returns an error as a `String`
9024 /// to distinguish between a test panic and an error in the input data.
9025 fn get_test_map<I, T, A>(
9026 iter: I,
9027 mut fun: impl FnMut(u64) -> T,
9028 alloc: A,
9029 ) -> Result<HashMap<u64, CheckedCloneDrop<T>, DefaultHashBuilder, A>, String>
9030 where
9031 I: Iterator<Item = (bool, bool)> + Clone + ExactSizeIterator,
9032 A: Allocator,
9033 T: PartialEq + core::fmt::Debug,
9034 {
9035 use crate::hashbrown::scopeguard::guard;
9036
9037 let mut map: HashMap<u64, CheckedCloneDrop<T>, _, A> =
9038 HashMap::try_with_capacity_in(iter.size_hint().0, alloc).unwrap();
9039 {
9040 let mut guard = guard(&mut map, |map| {
9041 for (_, value) in map.iter_mut() {
9042 value.panic_in_drop = false
9043 }
9044 });
9045
9046 let mut count = 0;
9047 // Hash and Key must be equal to each other for controlling the elements placement.
9048 for (panic_in_clone, panic_in_drop) in iter.clone() {
9049 if core::mem::needs_drop::<T>() && panic_in_drop {
9050 return Err(String::from(
9051 "panic_in_drop can be set with a type that doesn't need to be dropped",
9052 ));
9053 }
9054 into_ok_try(guard.table.insert(
9055 &mut (),
9056 count,
9057 (
9058 count,
9059 CheckedCloneDrop::new(panic_in_clone, panic_in_drop, fun(count)),
9060 ),
9061 |_: &mut (), (k, _): &(u64, _)| Ok(*k),
9062 ))
9063 .unwrap();
9064 count += 1;
9065 }
9066
9067 // Let's check that all elements are located as we wanted
9068 let mut check_count = 0;
9069 for ((key, value), (panic_in_clone, panic_in_drop)) in guard.iter().zip(iter) {
9070 if *key != check_count {
9071 return Err(format!(
9072 "key != check_count,\nkey: `{}`,\ncheck_count: `{}`",
9073 key, check_count
9074 ));
9075 }
9076 if value.dropped
9077 || value.panic_in_clone != panic_in_clone
9078 || value.panic_in_drop != panic_in_drop
9079 || value.data != fun(check_count)
9080 {
9081 return Err(format!(
9082 "Value is not equal to expected,\nvalue: `{:?}`,\nexpected: \
9083 `CheckedCloneDrop {{ panic_in_clone: {}, panic_in_drop: {}, dropped: {}, data: {:?} }}`",
9084 value, panic_in_clone, panic_in_drop, false, fun(check_count)
9085 ));
9086 }
9087 check_count += 1;
9088 }
9089
9090 if guard.len() != check_count as usize {
9091 return Err(format!(
9092 "map.len() != check_count,\nmap.len(): `{}`,\ncheck_count: `{}`",
9093 guard.len(),
9094 check_count
9095 ));
9096 }
9097
9098 if count != check_count {
9099 return Err(format!(
9100 "count != check_count,\ncount: `{}`,\ncheck_count: `{}`",
9101 count, check_count
9102 ));
9103 }
9104 core::mem::forget(guard);
9105 }
9106 Ok(map)
9107 }
9108
9109 const DISARMED: bool = false;
9110 const ARMED: bool = true;
9111
9112 const ARMED_FLAGS: [bool; 8] = [
9113 DISARMED, DISARMED, DISARMED, ARMED, DISARMED, DISARMED, DISARMED, DISARMED,
9114 ];
9115
9116 const DISARMED_FLAGS: [bool; 8] = [
9117 DISARMED, DISARMED, DISARMED, DISARMED, DISARMED, DISARMED, DISARMED, DISARMED,
9118 ];
9119
9120 #[test]
9121 #[should_panic = "panic in clone"]
9122 fn test_clone_memory_leaks_and_double_drop_one() {
9123 let dropped: Arc<AtomicI8> = Arc::new(AtomicI8::new(2));
9124
9125 {
9126 assert_eq!(ARMED_FLAGS.len(), DISARMED_FLAGS.len());
9127
9128 let map: HashMap<u64, CheckedCloneDrop<Vec<u64>>, DefaultHashBuilder, MyAlloc> =
9129 match get_test_map(
9130 ARMED_FLAGS.into_iter().zip(DISARMED_FLAGS),
9131 |n| ::rust_alloc::vec![n],
9132 MyAlloc::new(dropped.clone()),
9133 ) {
9134 Ok(map) => map,
9135 Err(msg) => panic!("{msg}"),
9136 };
9137
9138 // Clone should normally clone a few elements, and then (when the
9139 // clone function panics), deallocate both its own memory, memory
9140 // of `dropped: Arc<AtomicI8>` and the memory of already cloned
9141 // elements (Vec<i32> memory inside CheckedCloneDrop).
9142 let _map2 = map.try_clone().unwrap();
9143 }
9144 }
9145
9146 #[test]
9147 #[should_panic = "panic in drop"]
9148 fn test_clone_memory_leaks_and_double_drop_two() {
9149 let dropped: Arc<AtomicI8> = Arc::new(AtomicI8::new(2));
9150
9151 {
9152 assert_eq!(ARMED_FLAGS.len(), DISARMED_FLAGS.len());
9153
9154 let map: HashMap<u64, CheckedCloneDrop<u64>, DefaultHashBuilder, _> = match get_test_map(
9155 DISARMED_FLAGS.into_iter().zip(DISARMED_FLAGS),
9156 |n| n,
9157 MyAlloc::new(dropped.clone()),
9158 ) {
9159 Ok(map) => map,
9160 Err(msg) => panic!("{msg}"),
9161 };
9162
9163 let mut map2 = match get_test_map(
9164 DISARMED_FLAGS.into_iter().zip(ARMED_FLAGS),
9165 |n| n,
9166 MyAlloc::new(dropped.clone()),
9167 ) {
9168 Ok(map) => map,
9169 Err(msg) => panic!("{msg}"),
9170 };
9171
9172 // The `clone_from` should try to drop the elements of `map2` without
9173 // double drop and leaking the allocator. Elements that have not been
9174 // dropped leak their memory.
9175 map2.try_clone_from(&map).unwrap();
9176 }
9177 }
9178
9179 /// We check that we have a working table if the clone operation from another
9180 /// thread ended in a panic (when buckets of maps are equal to each other).
9181 #[test]
9182 fn test_catch_panic_clone_from_when_len_is_equal() {
9183 let dropped: Arc<AtomicI8> = Arc::new(AtomicI8::new(2));
9184
9185 {
9186 assert_eq!(ARMED_FLAGS.len(), DISARMED_FLAGS.len());
9187
9188 let mut map = match get_test_map(
9189 DISARMED_FLAGS.into_iter().zip(DISARMED_FLAGS),
9190 |n| ::rust_alloc::vec![n],
9191 MyAlloc::new(dropped.clone()),
9192 ) {
9193 Ok(map) => map,
9194 Err(msg) => panic!("{msg}"),
9195 };
9196
9197 thread::scope(|s| {
9198 let result: thread::ScopedJoinHandle<'_, String> = s.spawn(|| {
9199 let scope_map =
9200 match get_test_map(ARMED_FLAGS.into_iter().zip(DISARMED_FLAGS), |n| ::rust_alloc::vec![n * 2], MyAlloc::new(dropped.clone())) {
9201 Ok(map) => map,
9202 Err(msg) => return msg,
9203 };
9204 if map.table.buckets() != scope_map.table.buckets() {
9205 return format!(
9206 "map.table.buckets() != scope_map.table.buckets(),\nleft: `{}`,\nright: `{}`",
9207 map.table.buckets(), scope_map.table.buckets()
9208 );
9209 }
9210 map.try_clone_from(&scope_map).unwrap();
9211 "We must fail the cloning!!!".to_owned()
9212 });
9213 if let Ok(msg) = result.join() {
9214 panic!("{msg}")
9215 }
9216 });
9217
9218 // Let's check that all iterators work fine and do not return elements
9219 // (especially `RawIterRange`, which does not depend on the number of
9220 // elements in the table, but looks directly at the control bytes)
9221 //
9222 // SAFETY: We know for sure that `RawTable` will outlive
9223 // the returned `RawIter / RawIterRange` iterator.
9224 assert_eq!(map.len(), 0);
9225 assert_eq!(map.iter().count(), 0);
9226 assert_eq!(unsafe { map.table.iter().count() }, 0);
9227 assert_eq!(unsafe { map.table.iter().iter.count() }, 0);
9228
9229 for idx in 0..map.table.buckets() {
9230 let idx = idx as u64;
9231 assert!(
9232 into_ok(
9233 map.table
9234 .find(&mut (), idx, |_: &mut (), (k, _): &(u64, _)| Ok(*k == idx))
9235 )
9236 .is_none(),
9237 "Index: {idx}"
9238 );
9239 }
9240 }
9241
9242 // All allocator clones should already be dropped.
9243 assert_eq!(dropped.load(Ordering::SeqCst), 0);
9244 }
9245
9246 /// We check that we have a working table if the clone operation from another
9247 /// thread ended in a panic (when buckets of maps are not equal to each other).
9248 #[test]
9249 fn test_catch_panic_clone_from_when_len_is_not_equal() {
9250 let dropped: Arc<AtomicI8> = Arc::new(AtomicI8::new(2));
9251
9252 {
9253 assert_eq!(ARMED_FLAGS.len(), DISARMED_FLAGS.len());
9254
9255 let mut map = match get_test_map(
9256 [DISARMED].into_iter().zip([DISARMED]),
9257 |n| ::rust_alloc::vec![n],
9258 MyAlloc::new(dropped.clone()),
9259 ) {
9260 Ok(map) => map,
9261 Err(msg) => panic!("{msg}"),
9262 };
9263
9264 thread::scope(|s| {
9265 let result: thread::ScopedJoinHandle<'_, String> = s.spawn(|| {
9266 let scope_map = match get_test_map(
9267 ARMED_FLAGS.into_iter().zip(DISARMED_FLAGS),
9268 |n| ::rust_alloc::vec![n * 2],
9269 MyAlloc::new(dropped.clone()),
9270 ) {
9271 Ok(map) => map,
9272 Err(msg) => return msg,
9273 };
9274 if map.table.buckets() == scope_map.table.buckets() {
9275 return format!(
9276 "map.table.buckets() == scope_map.table.buckets(): `{}`",
9277 map.table.buckets()
9278 );
9279 }
9280 map.try_clone_from(&scope_map).unwrap();
9281 "We must fail the cloning!!!".to_owned()
9282 });
9283 if let Ok(msg) = result.join() {
9284 panic!("{msg}")
9285 }
9286 });
9287
9288 // Let's check that all iterators work fine and do not return elements
9289 // (especially `RawIterRange`, which does not depend on the number of
9290 // elements in the table, but looks directly at the control bytes)
9291 //
9292 // SAFETY: We know for sure that `RawTable` will outlive
9293 // the returned `RawIter / RawIterRange` iterator.
9294 assert_eq!(map.len(), 0);
9295 assert_eq!(map.iter().count(), 0);
9296 assert_eq!(unsafe { map.table.iter().count() }, 0);
9297 assert_eq!(unsafe { map.table.iter().iter.count() }, 0);
9298
9299 for idx in 0..map.table.buckets() {
9300 let idx = idx as u64;
9301 assert!(
9302 into_ok(
9303 map.table
9304 .find(&mut (), idx, |_: &mut (), (k, _): &(u64, _)| Ok(*k == idx))
9305 )
9306 .is_none(),
9307 "Index: {idx}"
9308 );
9309 }
9310 }
9311
9312 // All allocator clones should already be dropped.
9313 assert_eq!(dropped.load(Ordering::SeqCst), 0);
9314 }
9315}