cow_hashmap/lib.rs
1#[cfg(test)]
2mod tests;
3
4use self::Entry::*;
5use cow_hashbrown::{self as base, Equivalent};
6
7use std::borrow::Borrow;
8use std::collections::hash_map::RandomState;
9use std::error::Error;
10use std::fmt::{self, Debug};
11use std::hash::{BuildHasher, Hash, Hasher};
12use std::iter::FusedIterator;
13use std::sync::{Arc, Mutex, MutexGuard};
14
15pub use cow_hashbrown::hash_map::CowValueGuard;
16
17// The first shard level size will infrequently copy itself
18// after the hashmap has been populated with a decent amount of elements.
19const DEFAULT_SHARD_LEVEL1_SIZE: u64 = 256;
20// The second shard level will more frequently copy itself
21// during insert operations given a hash collision is much
22// less likely however on very large populations the copy
23// rate will drop off
24const DEFAULT_SHARD_LEVEL2_SIZE: u64 = 256;
25
26#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
27struct ShardIndex {
28 hash: u16,
29}
30
31fn key_shards<K: Hash + ?Sized, S: BuildHasher, const N1: u64, const N2: u64>(
32 key: &K,
33 hash_builder: &S,
34) -> (ShardIndex, ShardIndex) {
35 let mut state = hash_builder.build_hasher();
36 key.hash(&mut state);
37 let hash1 = state.finish();
38
39 key.hash(&mut state);
40 let hash2 = state.finish();
41
42 (
43 ShardIndex {
44 hash: (hash1 % DEFAULT_SHARD_LEVEL1_SIZE) as u16,
45 },
46 ShardIndex {
47 hash: (hash2 % DEFAULT_SHARD_LEVEL2_SIZE) as u16,
48 },
49 )
50}
51
52type ShardMap<K, V, S> = base::CowHashMap<ShardIndex, base::CowHashMap<K, V, S>, S>;
53
54/// A [hash map] implemented with quadratic probing and SIMD lookup.
55///
56/// By default, `HashMap` uses a hashing algorithm selected to provide
57/// resistance against HashDoS attacks. The algorithm is randomly seeded, and a
58/// reasonable best-effort is made to generate this seed from a high quality,
59/// secure source of randomness provided by the host without blocking the
60/// program. Because of this, the randomness of the seed depends on the output
61/// quality of the system's random number coroutine when the seed is created.
62/// In particular, seeds generated when the system's entropy pool is abnormally
63/// low such as during system boot may be of a lower quality.
64///
65/// The default hashing algorithm is currently SipHash 1-3, though this is
66/// subject to change at any point in the future. While its performance is very
67/// competitive for medium sized keys, other hashing algorithms will outperform
68/// it for small keys such as integers as well as large keys such as long
69/// strings, though those algorithms will typically *not* protect against
70/// attacks such as HashDoS.
71///
72/// The hashing algorithm can be replaced on a per-`HashMap` basis using the
73/// [`default`], [`with_hasher`], and [`with_capacity_and_hasher`] methods.
74/// There are many alternative [hashing algorithms available on crates.io].
75///
76/// It is required that the keys implement the [`Eq`] and [`Hash`] traits, although
77/// this can frequently be achieved by using `#[derive(PartialEq, Eq, Hash)]`.
78/// If you implement these yourself, it is important that the following
79/// property holds:
80///
81/// ```text
82/// k1 == k2 -> hash(k1) == hash(k2)
83/// ```
84///
85/// In other words, if two keys are equal, their hashes must be equal.
86/// Violating this property is a logic error.
87///
88/// It is also a logic error for a key to be modified in such a way that the key's
89/// hash, as determined by the [`Hash`] trait, or its equality, as determined by
90/// the [`Eq`] trait, changes while it is in the map. This is normally only
91/// possible through [`Cell`], [`RefCell`], global state, I/O, or unsafe code.
92///
93/// The behavior resulting from either logic error is not specified, but will
94/// be encapsulated to the `HashMap` that observed the logic error and not
95/// result in undefined behavior. This could include panics, incorrect results,
96/// aborts, memory leaks, and non-termination.
97///
98/// The hash table implementation is a Rust port of Google's [SwissTable].
99/// The original C++ version of SwissTable can be found [here], and this
100/// [CppCon talk] gives an overview of how the algorithm works.
101///
102/// [hash map]: crate::collections#use-a-hashmap-when
103/// [hashing algorithms available on crates.io]: https://crates.io/keywords/hasher
104/// [SwissTable]: https://abseil.io/blog/20180927-swisstables
105/// [here]: https://github.com/abseil/abseil-cpp/blob/master/absl/container/internal/raw_hash_set.h
106/// [CppCon talk]: https://www.youtube.com/watch?v=ncHmEUmJZf4
107///
108/// # Examples
109///
110/// ```
111/// use cow_hashmap::CowHashMap as HashMap;
112///
113/// // Type inference lets us omit an explicit type signature (which
114/// // would be `HashMap<String, String>` in this example).
115/// let mut book_reviews = HashMap::new();
116///
117/// // Review some books.
118/// book_reviews.insert(
119/// "Adventures of Huckleberry Finn".to_string(),
120/// "My favorite book.".to_string(),
121/// );
122/// book_reviews.insert(
123/// "Grimms' Fairy Tales".to_string(),
124/// "Masterpiece.".to_string(),
125/// );
126/// book_reviews.insert(
127/// "Pride and Prejudice".to_string(),
128/// "Very enjoyable.".to_string(),
129/// );
130/// book_reviews.insert(
131/// "The Adventures of Sherlock Holmes".to_string(),
132/// "Eye lyked it alot.".to_string(),
133/// );
134///
135/// // Check for a specific one.
136/// // When collections store owned values (String), they can still be
137/// // queried using references (&str).
138/// if !book_reviews.contains_key("Les Misérables") {
139/// println!("We've got {} reviews, but Les Misérables ain't one.",
140/// book_reviews.len());
141/// }
142///
143/// // oops, this review has a lot of spelling mistakes, let's delete it.
144/// book_reviews.remove("The Adventures of Sherlock Holmes");
145///
146/// // Look up the values associated with some keys.
147/// let to_find = ["Pride and Prejudice", "Alice's Adventure in Wonderland"];
148/// for &book in &to_find {
149/// match book_reviews.get(book) {
150/// Some(review) => println!("{book}: {review}"),
151/// None => println!("{book} is unreviewed.")
152/// }
153/// }
154///
155/// // Look up the value for a key (will panic if the key is not found).
156/// println!("Review for Jane: {}", book_reviews.get("Pride and Prejudice").unwrap());
157///
158/// // Iterate over everything.
159/// for (book, review) in &book_reviews {
160/// println!("{book}: \"{review}\"");
161/// }
162/// ```
163///
164/// A `HashMap` with a known list of items can be initialized from an array:
165///
166/// ```
167/// use cow_hashmap::CowHashMap as HashMap;
168///
169/// let solar_distance = HashMap::from([
170/// ("Mercury", 0.4),
171/// ("Venus", 0.7),
172/// ("Earth", 1.0),
173/// ("Mars", 1.5),
174/// ]);
175/// ```
176///
177/// `HashMap` implements an [`Entry` API](#method.entry), which allows
178/// for complex methods of getting, setting, updating and removing keys and
179/// their values:
180///
181/// ```
182/// use cow_hashmap::CowHashMap as HashMap;
183///
184/// // type inference lets us omit an explicit type signature (which
185/// // would be `HashMap<&str, u8>` in this example).
186/// let mut player_stats = HashMap::new();
187///
188/// fn random_stat_buff() -> u8 {
189/// // could actually return some random value here - let's just return
190/// // some fixed value for now
191/// 42
192/// }
193///
194/// // insert a key only if it doesn't already exist
195/// player_stats.entry("health").or_insert(100);
196///
197/// // insert a key using a function that provides a new value only if it
198/// // doesn't already exist
199/// player_stats.entry("defence").or_insert_with(random_stat_buff);
200///
201/// // update a key, guarding against the key possibly not being set
202/// let mut stat = player_stats.entry("attack").or_insert(100);
203/// *stat += random_stat_buff();
204///
205/// // modify an entry before an insert with in-place mutation
206/// player_stats.entry("mana").and_modify(|mut mana| *mana += 200).or_insert(100);
207/// ```
208///
209/// The easiest way to use `HashMap` with a custom key type is to derive [`Eq`] and [`Hash`].
210/// We must also derive [`PartialEq`].
211///
212/// [`RefCell`]: crate::cell::RefCell
213/// [`Cell`]: crate::cell::Cell
214/// [`default`]: Default::default
215/// [`with_hasher`]: Self::with_hasher
216/// [`with_capacity_and_hasher`]: Self::with_capacity_and_hasher
217///
218/// ```
219/// use cow_hashmap::CowHashMap as HashMap;
220///
221/// #[derive(Clone, Hash, Eq, PartialEq, Debug)]
222/// struct Viking {
223/// name: String,
224/// country: String,
225/// }
226///
227/// impl Viking {
228/// /// Creates a new Viking.
229/// fn new(name: &str, country: &str) -> Viking {
230/// Viking { name: name.to_string(), country: country.to_string() }
231/// }
232/// }
233///
234/// // Use a HashMap to store the vikings' health points.
235/// let vikings = HashMap::from([
236/// (Viking::new("Einar", "Norway"), 25),
237/// (Viking::new("Olaf", "Denmark"), 24),
238/// (Viking::new("Harald", "Iceland"), 12),
239/// ]);
240///
241/// // Use derived implementation to print the status of the vikings.
242/// for (viking, health) in &vikings {
243/// println!("{viking:?} has {health} hp");
244/// }
245/// ```
246
247pub struct CowHashMap<K: Clone, V, S = RandomState> {
248 base: base::CowHashMap<ShardIndex, ShardMap<K, V, S>, S>,
249 lock: Arc<Mutex<()>>,
250}
251
252impl<K: Clone, V> CowHashMap<K, V, RandomState> {
253 /// Creates an empty `HashMap`.
254 ///
255 /// The hash map is initially created with a capacity of 0, so it will not allocate until it
256 /// is first inserted into.
257 ///
258 /// # Examples
259 ///
260 /// ```
261 /// use cow_hashmap::CowHashMap as HashMap;
262 /// let mut map: HashMap<&str, i32> = HashMap::new();
263 /// ```
264 #[inline]
265 #[must_use]
266 pub fn new() -> CowHashMap<K, V, RandomState> {
267 Default::default()
268 }
269}
270
271impl<K: Clone, V, S> CowHashMap<K, V, S> {
272 /// Creates an empty `HashMap` which will use the given hash builder to hash
273 /// keys.
274 ///
275 /// The created map has the default initial capacity.
276 ///
277 /// Warning: `hash_builder` is normally randomly generated, and
278 /// is designed to allow HashMaps to be resistant to attacks that
279 /// cause many collisions and very poor performance. Setting it
280 /// manually using this function can expose a DoS attack vector.
281 ///
282 /// The `hash_builder` passed should implement the [`BuildHasher`] trait for
283 /// the HashMap to be useful, see its documentation for details.
284 ///
285 /// # Examples
286 ///
287 /// ```
288 /// use cow_hashmap::CowHashMap as HashMap;
289 /// use std::hash::RandomState;
290 ///
291 /// let s = RandomState::new();
292 /// let mut map = HashMap::with_hasher(s);
293 /// map.insert(1, 2);
294 /// ```
295 #[inline]
296 pub fn with_hasher(hash_builder: S) -> CowHashMap<K, V, S> {
297 CowHashMap {
298 base: base::CowHashMap::with_hasher(hash_builder),
299 lock: Default::default(),
300 }
301 }
302
303 /// An iterator visiting all keys in arbitrary order.
304 /// The iterator element type is `&'a K`.
305 ///
306 /// # Examples
307 ///
308 /// ```
309 /// use cow_hashmap::CowHashMap as HashMap;
310 ///
311 /// let map = HashMap::from([
312 /// ("a", 1),
313 /// ("b", 2),
314 /// ("c", 3),
315 /// ]);
316 ///
317 /// for key in map.keys() {
318 /// println!("{key}");
319 /// }
320 /// ```
321 ///
322 /// # Performance
323 ///
324 /// In the current implementation, iterating over keys takes O(capacity) time
325 /// instead of O(len) because it internally visits empty buckets too.
326 pub fn keys(&self) -> Keys<K, V, S> {
327 Keys { inner: self.iter() }
328 }
329
330 /// Creates a consuming iterator visiting all the keys in arbitrary order.
331 /// The map cannot be used after calling this.
332 /// The iterator element type is `K`.
333 ///
334 /// # Examples
335 ///
336 /// ```
337 /// use cow_hashmap::CowHashMap as HashMap;
338 ///
339 /// let map = HashMap::from([
340 /// ("a", 1),
341 /// ("b", 2),
342 /// ("c", 3),
343 /// ]);
344 ///
345 /// let mut vec: Vec<&str> = map.into_keys().collect();
346 /// // The `IntoKeys` iterator produces keys in arbitrary order, so the
347 /// // keys must be sorted to test them against a sorted array.
348 /// vec.sort_unstable();
349 /// assert_eq!(vec, ["a", "b", "c"]);
350 /// ```
351 ///
352 /// # Performance
353 ///
354 /// In the current implementation, iterating over keys takes O(capacity) time
355 /// instead of O(len) because it internally visits empty buckets too.
356 #[inline]
357 pub fn into_keys(self) -> IntoKeys<K, V, S>
358 where
359 S: Clone,
360 {
361 IntoKeys {
362 inner: self.into_iter(),
363 }
364 }
365
366 /// An iterator visiting all values in arbitrary order.
367 /// The iterator element type is `&'a V`.
368 ///
369 /// # Examples
370 ///
371 /// ```
372 /// use cow_hashmap::CowHashMap as HashMap;
373 ///
374 /// let map = HashMap::from([
375 /// ("a", 1),
376 /// ("b", 2),
377 /// ("c", 3),
378 /// ]);
379 ///
380 /// for val in map.values() {
381 /// println!("{val}");
382 /// }
383 /// ```
384 ///
385 /// # Performance
386 ///
387 /// In the current implementation, iterating over values takes O(capacity) time
388 /// instead of O(len) because it internally visits empty buckets too.
389 pub fn values(&self) -> Values<K, V, S> {
390 Values { inner: self.iter() }
391 }
392
393 /// An iterator visiting all values mutably in arbitrary order.
394 /// The iterator element type is `&'a mut V`.
395 ///
396 /// # Examples
397 ///
398 /// ```
399 /// use cow_hashmap::CowHashMap as HashMap;
400 ///
401 /// let mut map = HashMap::from([
402 /// ("a", 1),
403 /// ("b", 2),
404 /// ("c", 3),
405 /// ]);
406 ///
407 /// for mut val in map.values_mut() {
408 /// *val = *val + 10;
409 /// }
410 ///
411 /// for val in map.values() {
412 /// println!("{val}");
413 /// }
414 /// ```
415 ///
416 /// # Performance
417 ///
418 /// In the current implementation, iterating over values takes O(capacity) time
419 /// instead of O(len) because it internally visits empty buckets too.
420 pub fn values_mut(&self) -> ValuesMut<K, V, S> {
421 ValuesMut {
422 inner: self.iter_mut(),
423 }
424 }
425
426 /// Creates a consuming iterator visiting all the values in arbitrary order.
427 /// The map cannot be used after calling this.
428 /// The iterator element type is `V`.
429 ///
430 /// # Examples
431 ///
432 /// ```
433 /// use cow_hashmap::CowHashMap as HashMap;
434 /// use std::sync::Arc;
435 ///
436 /// let map = HashMap::from([
437 /// ("a", 1),
438 /// ("b", 2),
439 /// ("c", 3),
440 /// ]);
441 ///
442 /// let mut vec: Vec<Arc<i32>> = map.into_values().collect();
443 /// // The `IntoValues` iterator produces values in arbitrary order, so
444 /// // the values must be sorted to test them against a sorted array.
445 /// vec.sort_unstable();
446 /// assert_eq!(vec, [Arc::new(1), Arc::new(2), Arc::new(3)]);
447 /// ```
448 ///
449 /// # Performance
450 ///
451 /// In the current implementation, iterating over values takes O(capacity) time
452 /// instead of O(len) because it internally visits empty buckets too.
453 #[inline]
454 pub fn into_values(self) -> IntoValues<K, V, S>
455 where
456 S: Clone,
457 {
458 IntoValues {
459 inner: self.into_iter(),
460 }
461 }
462
463 /// An iterator visiting all key-value pairs in arbitrary order.
464 /// The iterator element type is `(&'a K, &'a V)`.
465 ///
466 /// # Examples
467 ///
468 /// ```
469 /// use cow_hashmap::CowHashMap as HashMap;
470 ///
471 /// let map = HashMap::from([
472 /// ("a", 1),
473 /// ("b", 2),
474 /// ("c", 3),
475 /// ]);
476 ///
477 /// for (key, val) in map.iter() {
478 /// println!("key: {key} val: {val}");
479 /// }
480 /// ```
481 ///
482 /// # Performance
483 ///
484 /// In the current implementation, iterating over map takes O(capacity) time
485 /// instead of O(len) because it internally visits empty buckets too.
486 pub fn iter(&self) -> Iter<K, V, S> {
487 Iter {
488 base: self.base.iter(),
489 shard1: None,
490 shard2: None,
491 }
492 }
493
494 /// An iterator visiting all key-value pairs in arbitrary order,
495 /// with mutable references to the values.
496 /// The iterator element type is `(&'a K, &'a mut V)`.
497 ///
498 /// # Examples
499 ///
500 /// ```
501 /// use cow_hashmap::CowHashMap as HashMap;
502 ///
503 /// let mut map = HashMap::from([
504 /// ("a", 1),
505 /// ("b", 2),
506 /// ("c", 3),
507 /// ]);
508 ///
509 /// // Update all values
510 /// for (_, mut val) in map.iter_mut() {
511 /// *val *= 2;
512 /// }
513 ///
514 /// for (key, val) in &map {
515 /// println!("key: {key} val: {val}");
516 /// }
517 /// ```
518 ///
519 /// # Performance
520 ///
521 /// In the current implementation, iterating over map takes O(capacity) time
522 /// instead of O(len) because it internally visits empty buckets too.
523 pub fn iter_mut(&self) -> IterMut<K, V, S> {
524 IterMut {
525 base: self.base.iter(),
526 shard1: None,
527 shard2: None,
528 }
529 }
530
531 /// Returns the number of elements in the map.
532 ///
533 /// # Examples
534 ///
535 /// ```
536 /// use cow_hashmap::CowHashMap as HashMap;
537 ///
538 /// let mut a = HashMap::new();
539 /// assert_eq!(a.len(), 0);
540 /// a.insert(1, "a");
541 /// assert_eq!(a.len(), 1);
542 /// ```
543 pub fn len(&self) -> usize {
544 self.base
545 .iter()
546 .map(|(_, t)| t.iter().map(|(_, t)| t.len()).sum::<usize>())
547 .sum()
548 }
549
550 /// Returns `true` if the map contains no elements.
551 ///
552 /// # Examples
553 ///
554 /// ```
555 /// use cow_hashmap::CowHashMap as HashMap;
556 ///
557 /// let mut a = HashMap::new();
558 /// assert!(a.is_empty());
559 /// a.insert(1, "a");
560 /// assert!(!a.is_empty());
561 /// ```
562 #[inline]
563 pub fn is_empty(&self) -> bool {
564 if self.base.is_empty() {
565 return true;
566 }
567 self.base.iter().all(|(_, t)| t.is_empty())
568 }
569
570 /// Clears the map, returning all key-value pairs as an iterator. Keeps the
571 /// allocated memory for reuse.
572 ///
573 /// If the returned iterator is dropped before being fully consumed, it
574 /// drops the remaining key-value pairs. The returned iterator keeps a
575 /// mutable borrow on the map to optimize its implementation.
576 ///
577 /// # Examples
578 ///
579 /// ```
580 /// use cow_hashmap::CowHashMap as HashMap;
581 /// use std::sync::Arc;
582 ///
583 /// let mut a = HashMap::new();
584 /// a.insert(1, "a");
585 /// a.insert(2, "b");
586 ///
587 /// for (k, v) in a.drain().take(1) {
588 /// assert!(k == 1 || k == 2);
589 /// assert!(v == Arc::new("a") || v == Arc::new("b"));
590 /// }
591 ///
592 /// assert!(a.is_empty());
593 /// ```
594 #[inline]
595 pub fn drain(&self) -> Drain<K, V, S> {
596 let ret = Drain {
597 base: self.base.drain(),
598 shard1: None,
599 shard2: None,
600 };
601 ret
602 }
603
604 /// Retains only the elements specified by the predicate.
605 ///
606 /// In other words, remove all pairs `(k, v)` for which `f(&k, &mut v)` returns `false`.
607 /// The elements are visited in unsorted (and unspecified) order.
608 ///
609 /// # Examples
610 ///
611 /// ```
612 /// use cow_hashmap::CowHashMap as HashMap;
613 ///
614 /// let mut map: HashMap<i32, i32> = (0..8).map(|x| (x, x*10)).collect();
615 /// map.retain(|&k, _| k % 2 == 0);
616 /// assert_eq!(map.len(), 4);
617 /// ```
618 ///
619 /// # Performance
620 ///
621 /// In the current implementation, this operation takes O(capacity) time
622 /// instead of O(len) because it internally visits empty buckets too.
623 #[inline]
624 pub fn retain<F>(&self, mut f: F)
625 where
626 F: FnMut(&K, &V) -> bool,
627 V: Clone,
628 S: Clone,
629 {
630 let mut f = move |k: &K, v: &V| -> bool { f(k, v) };
631 for shard1 in self.base.values() {
632 for shard2 in shard1.values() {
633 shard2.retain(&mut f);
634 }
635 shard1.retain(|_, t| !t.is_empty());
636 }
637 }
638
639 /// Retains only the elements specified by the predicate.
640 ///
641 /// In other words, remove all pairs `(k, v)` for which `f(&k, &mut v)` returns `false`.
642 /// The elements are visited in unsorted (and unspecified) order.
643 ///
644 /// # Examples
645 ///
646 /// ```
647 /// use cow_hashmap::CowHashMap as HashMap;
648 ///
649 /// let mut map: HashMap<i32, i32> = (0..8).map(|x| (x, x*10)).collect();
650 /// map.retain(|&k, _| k % 2 == 0);
651 /// assert_eq!(map.len(), 4);
652 /// ```
653 ///
654 /// # Performance
655 ///
656 /// In the current implementation, this operation takes O(capacity) time
657 /// instead of O(len) because it internally visits empty buckets too.
658 #[inline]
659 pub fn retain_mut<F>(&self, mut f: F)
660 where
661 F: FnMut(&K, &mut V) -> bool,
662 V: Clone,
663 S: Clone,
664 {
665 let mut f = move |k: &K, v: &mut V| -> bool { f(k, v) };
666 for shard1 in self.base.values() {
667 for shard2 in shard1.values() {
668 shard2.retain_mut(&mut f);
669 }
670 shard1.retain(|_, t| !t.is_empty());
671 }
672 }
673
674 /// Clears the map, removing all key-value pairs. Keeps the allocated memory
675 /// for reuse.
676 ///
677 /// # Examples
678 ///
679 /// ```
680 /// use cow_hashmap::CowHashMap as HashMap;
681 ///
682 /// let mut a = HashMap::new();
683 /// a.insert(1, "a");
684 /// a.clear();
685 /// assert!(a.is_empty());
686 /// ```
687 #[inline]
688 pub fn clear(&self) {
689 self.base.clear();
690 }
691
692 /// Returns a reference to the map's [`BuildHasher`].
693 ///
694 /// # Examples
695 ///
696 /// ```
697 /// use cow_hashmap::CowHashMap as HashMap;
698 /// use std::hash::RandomState;
699 ///
700 /// let hasher = RandomState::new();
701 /// let map: HashMap<i32, i32> = HashMap::with_hasher(hasher);
702 /// let hasher: &RandomState = map.hasher();
703 /// ```
704 #[inline]
705 pub fn hasher(&self) -> &S {
706 self.base.hasher()
707 }
708}
709
710impl<K: Clone, V, S> CowHashMap<K, V, S>
711where
712 K: Eq + Hash,
713 S: BuildHasher,
714{
715 /// Grabs the shard that is relevant for this particular key
716 fn shard<Q: ?Sized>(&self, key: &Q) -> Option<Arc<base::CowHashMap<K, V, S>>>
717 where
718 Q: Hash + Eq,
719 {
720 let (shard1, shard2) =
721 key_shards::<Q, S, DEFAULT_SHARD_LEVEL1_SIZE, DEFAULT_SHARD_LEVEL2_SIZE>(
722 key,
723 self.base.hasher(),
724 );
725 self.base.get(&shard1)?.get(&shard2)
726 }
727
728 fn shard_and_parent<Q: ?Sized>(
729 &self,
730 key: &Q,
731 ) -> Option<(
732 Arc<base::CowHashMap<K, V, S>>,
733 Arc<cow_hashbrown::CowHashMap<ShardIndex, cow_hashbrown::CowHashMap<K, V, S>, S>>,
734 )>
735 where
736 Q: Hash + Eq,
737 {
738 let (shard1, shard2) =
739 key_shards::<Q, S, DEFAULT_SHARD_LEVEL1_SIZE, DEFAULT_SHARD_LEVEL2_SIZE>(
740 key,
741 self.base.hasher(),
742 );
743 let parent = self.base.get(&shard1)?;
744
745 let ret = parent.get(&shard2)?;
746
747 Some((ret, parent))
748 }
749
750 /// Grabs the shard that is relevant for this particular key
751 fn shard_mut<Q: ?Sized>(&self, key: &Q) -> CowValueGuard<base::CowHashMap<K, V, S>>
752 where
753 Q: Hash + Eq,
754 S: Clone,
755 {
756 let (shard1, shard2) =
757 key_shards::<Q, S, DEFAULT_SHARD_LEVEL1_SIZE, DEFAULT_SHARD_LEVEL2_SIZE>(
758 key,
759 self.base.hasher(),
760 );
761
762 self.base
763 .entry(shard1)
764 .or_insert_with_mut(|| base::CowHashMap::with_hasher(self.base.hasher().clone()))
765 .entry(shard2)
766 .or_insert_with_mut(|| base::CowHashMap::with_hasher(self.base.hasher().clone()))
767 }
768
769 /// Gets the given key's corresponding entry in the map for in-place manipulation.
770 ///
771 /// # Examples
772 ///
773 /// ```
774 /// use cow_hashmap::CowHashMap as HashMap;
775 /// use std::sync::Arc;
776 ///
777 /// let mut letters = HashMap::new();
778 ///
779 /// for ch in "a short treatise on fungi".chars() {
780 /// letters.entry(ch).and_modify(|mut counter| *counter += 1).or_insert(1);
781 /// }
782 ///
783 /// assert_eq!(letters.get(&'s').unwrap(), Arc::new(2));
784 /// assert_eq!(letters.get(&'t').unwrap(), Arc::new(3));
785 /// assert_eq!(letters.get(&'u').unwrap(), Arc::new(1));
786 /// assert_eq!(letters.get(&'y'), None);
787 /// ```
788 #[inline]
789 pub fn entry(&self, key: K) -> Entry<K, V, S>
790 where
791 S: Clone,
792 {
793 map_entry(self.shard_mut(&key).entry(key))
794 }
795
796 /// Locks the hashmap for exclusive access (all other accessors
797 /// must also use this lock method otherwise they can still
798 /// access the hashmap)
799 pub fn lock<'a>(&'a self) -> MutexGuard<'a, ()> {
800 self.lock.lock().unwrap()
801 }
802
803 /// Gets the given key's corresponding entry in the map for in-place manipulation.
804 ///
805 /// If the entry does not exist then the act of creating the entry will be done
806 /// under a lock to prevent concurrent inserts
807 ///
808 /// # Examples
809 ///
810 /// ```
811 /// use cow_hashmap::CowHashMap as HashMap;
812 /// use std::sync::Arc;
813 ///
814 /// let mut letters = HashMap::new();
815 ///
816 /// for ch in "a short treatise on fungi".chars() {
817 /// letters.entry(ch).and_modify(|mut counter| *counter += 1).or_insert(1);
818 /// }
819 ///
820 /// assert_eq!(letters.get(&'s').unwrap(), Arc::new(2));
821 /// assert_eq!(letters.get(&'t').unwrap(), Arc::new(3));
822 /// assert_eq!(letters.get(&'u').unwrap(), Arc::new(1));
823 /// assert_eq!(letters.get(&'y'), None);
824 /// ```
825 #[inline]
826 pub fn entry_or_lock(&self, key: K) -> LockableEntry<'_, K, V, S>
827 where
828 S: Clone,
829 {
830 let entry = map_entry(self.shard_mut(&key).entry(key));
831 if matches!(entry, Entry::Occupied(_)) {
832 LockableEntry(entry, None)
833 } else {
834 LockableEntry(entry, Some(self.lock.lock().unwrap()))
835 }
836 }
837
838 /// Returns a reference to the value corresponding to the key.
839 ///
840 /// The key may be any borrowed form of the map's key type, but
841 /// [`Hash`] and [`Eq`] on the borrowed form *must* match those for
842 /// the key type.
843 ///
844 /// # Examples
845 ///
846 /// ```
847 /// use cow_hashmap::CowHashMap as HashMap;
848 /// use std::sync::Arc;
849 ///
850 /// let mut map = HashMap::new();
851 /// map.insert(1, "a");
852 /// assert_eq!(map.get(&1), Some(Arc::new("a")));
853 /// assert_eq!(map.get(&2), None);
854 /// ```
855 #[inline]
856 pub fn get<Q: ?Sized>(&self, k: &Q) -> Option<Arc<V>>
857 where
858 K: Borrow<Q>,
859 Q: Hash + Eq,
860 {
861 self.shard(k)?.get(k)
862 }
863
864 /// Returns the key-value pair corresponding to the supplied key.
865 ///
866 /// The supplied key may be any borrowed form of the map's key type, but
867 /// [`Hash`] and [`Eq`] on the borrowed form *must* match those for
868 /// the key type.
869 ///
870 /// # Examples
871 ///
872 /// ```
873 /// use cow_hashmap::CowHashMap as HashMap;
874 /// use std::sync::Arc;
875 ///
876 /// let mut map = HashMap::new();
877 /// map.insert(1, "a");
878 /// assert_eq!(map.get_key_value(&1), Some((1, Arc::new("a"))));
879 /// assert_eq!(map.get_key_value(&2), None);
880 /// ```
881 #[inline]
882 pub fn get_key_value<Q: ?Sized>(&self, k: &Q) -> Option<(K, Arc<V>)>
883 where
884 K: Borrow<Q>,
885 Q: Hash + Eq,
886 {
887 self.shard(k)?.get_key_value(k)
888 }
889
890 /// Returns `true` if the map contains a value for the specified key.
891 ///
892 /// The key may be any borrowed form of the map's key type, but
893 /// [`Hash`] and [`Eq`] on the borrowed form *must* match those for
894 /// the key type.
895 ///
896 /// # Examples
897 ///
898 /// ```
899 /// use cow_hashmap::CowHashMap as HashMap;
900 ///
901 /// let mut map = HashMap::new();
902 /// map.insert(1, "a");
903 /// assert_eq!(map.contains_key(&1), true);
904 /// assert_eq!(map.contains_key(&2), false);
905 /// ```
906 #[inline]
907 pub fn contains_key<Q: ?Sized>(&self, k: &Q) -> bool
908 where
909 K: Borrow<Q>,
910 Q: Hash + Eq,
911 {
912 let map = self.shard(k);
913 match map {
914 Some(map) => map.contains_key(k),
915 None => false,
916 }
917 }
918
919 /// Returns a mutable reference to the value corresponding to the key.
920 ///
921 /// The key may be any borrowed form of the map's key type, but
922 /// [`Hash`] and [`Eq`] on the borrowed form *must* match those for
923 /// the key type.
924 ///
925 /// # Examples
926 ///
927 /// ```
928 /// use cow_hashmap::CowHashMap as HashMap;
929 /// use std::sync::Arc;
930 ///
931 /// let mut map = HashMap::new();
932 /// map.insert(1, "a");
933 /// if let Some(mut x) = map.get_mut(&1) {
934 /// *x = "b";
935 /// }
936 /// assert_eq!(map.get(&1).unwrap(), Arc::new("b"));
937 /// ```
938 #[inline]
939 pub fn get_mut<Q: ?Sized>(&self, k: &Q) -> Option<CowValueGuard<V>>
940 where
941 S: Clone,
942 K: Borrow<Q>,
943 Q: Hash + Eq,
944 V: Clone,
945 {
946 self.shard_mut(k).get_mut(k)
947 }
948
949 /// Inserts a key-value pair into the map.
950 ///
951 /// If the map did not have this key present, [`None`] is returned.
952 ///
953 /// If the map did have this key present, the value is updated, and the old
954 /// value is returned. The key is not updated, though; this matters for
955 /// types that can be `==` without being identical. See the [module-level
956 /// documentation] for more.
957 ///
958 /// [module-level documentation]: crate::collections#insert-and-complex-keys
959 ///
960 /// # Examples
961 ///
962 /// ```
963 /// use cow_hashmap::CowHashMap as HashMap;
964 ///
965 /// let mut map = HashMap::new();
966 /// assert_eq!(map.insert(37, "a"), None);
967 /// assert_eq!(map.is_empty(), false);
968 ///
969 /// map.insert(37, "b");
970 /// assert_eq!(*map.insert(37, "c").unwrap(), "b");
971 /// assert_eq!(*map.get(&37).unwrap(), "c");
972 /// ```
973 #[inline]
974 pub fn insert(&self, k: K, v: V) -> Option<Arc<V>>
975 where
976 S: Clone,
977 {
978 self.shard_mut(&k).insert(k, v)
979 }
980
981 /// Inserts a key-value pair into the map.
982 ///
983 /// If the map did not have this key present, [`None`] is returned.
984 ///
985 /// If the map did have this key present, the value is updated, and the old
986 /// value is returned. The key is not updated, though; this matters for
987 /// types that can be `==` without being identical. See the [module-level
988 /// documentation] for more.
989 ///
990 /// [module-level documentation]: crate::collections#insert-and-complex-keys
991 ///
992 /// # Examples
993 ///
994 /// ```
995 /// use cow_hashmap::CowHashMap as HashMap;
996 ///
997 /// let mut map = HashMap::new();
998 /// assert_eq!(map.insert(37, "a"), None);
999 /// assert_eq!(map.is_empty(), false);
1000 ///
1001 /// map.insert(37, "b");
1002 /// assert_eq!(*map.insert(37, "c").unwrap(), "b");
1003 /// assert_eq!(*map.get(&37).unwrap(), "c");
1004 /// ```
1005 #[inline]
1006 pub fn insert_mut(&self, k: K, v: V) -> Option<CowValueGuard<V>>
1007 where
1008 S: Clone,
1009 V: Clone,
1010 {
1011 self.shard_mut(&k).insert_mut(k, v)
1012 }
1013
1014 /// Tries to insert a key-value pair into the map, and returns
1015 /// a mutable reference to the value in the entry.
1016 ///
1017 /// If the map already had this key present, nothing is updated, and
1018 /// an error containing the occupied entry and the value is returned.
1019 ///
1020 /// # Examples
1021 ///
1022 /// Basic usage:
1023 ///
1024 /// ```
1025 /// use cow_hashmap::CowHashMap as HashMap;
1026 /// use std::sync::Arc;
1027 ///
1028 /// let mut map = HashMap::new();
1029 /// assert_eq!(**map.try_insert(37, "a").unwrap(), *"a");
1030 ///
1031 /// let err = map.try_insert(37, "b").unwrap_err();
1032 /// assert_eq!(err.entry.key(), &37);
1033 /// assert_eq!(err.entry.get(), Arc::new("a"));
1034 /// assert_eq!(err.value, "b");
1035 /// ```
1036 pub fn try_insert(&self, key: K, value: V) -> Result<Arc<V>, OccupiedError<K, V, S>>
1037 where
1038 S: Clone,
1039 {
1040 match self.shard_mut(&key).entry(key) {
1041 cow_hashbrown::hash_map::Entry::Occupied(entry) => Err(OccupiedError {
1042 entry: OccupiedEntry { base: entry },
1043 value,
1044 }),
1045 cow_hashbrown::hash_map::Entry::Vacant(entry) => Ok(entry.insert(value)),
1046 }
1047 }
1048
1049 /// Tries to insert a key-value pair into the map, and returns
1050 /// a mutable reference to the value in the entry.
1051 ///
1052 /// If the map already had this key present, nothing is updated, and
1053 /// an error containing the occupied entry and the value is returned.
1054 ///
1055 /// # Examples
1056 ///
1057 /// Basic usage:
1058 ///
1059 /// ```
1060 /// use cow_hashmap::CowHashMap as HashMap;
1061 /// use std::sync::Arc;
1062 ///
1063 /// let mut map = HashMap::new();
1064 /// assert_eq!(**map.try_insert(37, "a").unwrap(), *"a");
1065 ///
1066 /// let err = map.try_insert(37, "b").unwrap_err();
1067 /// assert_eq!(err.entry.key(), &37);
1068 /// assert_eq!(err.entry.get(), Arc::new("a"));
1069 /// assert_eq!(err.value, "b");
1070 /// ```
1071 pub fn try_insert_mut(
1072 &self,
1073 key: K,
1074 value: V,
1075 ) -> Result<CowValueGuard<V>, OccupiedError<K, V, S>>
1076 where
1077 S: Clone,
1078 V: Clone,
1079 {
1080 match self.shard_mut(&key).entry(key) {
1081 cow_hashbrown::hash_map::Entry::Occupied(entry) => Err(OccupiedError {
1082 entry: OccupiedEntry { base: entry },
1083 value,
1084 }),
1085 cow_hashbrown::hash_map::Entry::Vacant(entry) => Ok(entry.insert_mut(value)),
1086 }
1087 }
1088
1089 /// Removes a key from the map, returning the value at the key if the key
1090 /// was previously in the map.
1091 ///
1092 /// The key may be any borrowed form of the map's key type, but
1093 /// [`Hash`] and [`Eq`] on the borrowed form *must* match those for
1094 /// the key type.
1095 ///
1096 /// # Examples
1097 ///
1098 /// ```
1099 /// use cow_hashmap::CowHashMap as HashMap;
1100 /// use std::sync::Arc;
1101 ///
1102 /// let mut map = HashMap::new();
1103 /// map.insert(1, "a");
1104 /// assert_eq!(map.remove(&1), Some(Arc::new("a")));
1105 /// assert_eq!(map.remove(&1), None);
1106 /// ```
1107 #[inline]
1108 pub fn remove<Q: ?Sized>(&self, k: &Q) -> Option<Arc<V>>
1109 where
1110 K: Borrow<Q>,
1111 Q: Hash + Eq,
1112 S: Clone,
1113 {
1114 let (shard, parent) = self.shard_and_parent(k)?;
1115 let ret = shard.remove(k);
1116
1117 if shard.is_empty() {
1118 parent.retain(|_, t| !t.is_empty());
1119 }
1120
1121 ret
1122 }
1123
1124 /// Removes a key from the map, returning the stored key and value if the
1125 /// key was previously in the map.
1126 ///
1127 /// The key may be any borrowed form of the map's key type, but
1128 /// [`Hash`] and [`Eq`] on the borrowed form *must* match those for
1129 /// the key type.
1130 ///
1131 /// # Examples
1132 ///
1133 /// ```
1134 /// use cow_hashmap::CowHashMap as HashMap;
1135 /// use std::sync::Arc;
1136 ///
1137 /// # fn main() {
1138 /// let mut map = HashMap::new();
1139 /// map.insert(1, "a");
1140 /// assert_eq!(map.remove_entry(&1), Some((1, Arc::new("a"))));
1141 /// assert_eq!(map.remove(&1), None);
1142 /// # }
1143 /// ```
1144 #[inline]
1145 pub fn remove_entry<Q: ?Sized>(&self, k: &Q) -> Option<(K, Arc<V>)>
1146 where
1147 K: Borrow<Q>,
1148 Q: Hash + Eq,
1149 S: Clone,
1150 {
1151 let (shard, parent) = self.shard_and_parent(k)?;
1152
1153 let ret = shard.remove_entry(k);
1154 if shard.is_empty() {
1155 parent.retain(|_, t| !t.is_empty());
1156 }
1157
1158 ret
1159 }
1160}
1161
1162impl<K, V, S> Clone for CowHashMap<K, V, S>
1163where
1164 K: Clone,
1165 V: Clone,
1166 S: Clone,
1167{
1168 #[inline]
1169 fn clone(&self) -> Self {
1170 Self {
1171 base: self.base.clone(),
1172 lock: self.lock.clone(),
1173 }
1174 }
1175
1176 #[inline]
1177 fn clone_from(&mut self, other: &Self) {
1178 self.base.clone_from(&other.base);
1179 self.lock.clone_from(&other.lock);
1180 }
1181}
1182
1183impl<K: Clone, V, S> PartialEq for CowHashMap<K, V, S>
1184where
1185 K: Eq + Hash,
1186 V: PartialEq,
1187 S: BuildHasher,
1188{
1189 fn eq(&self, other: &CowHashMap<K, V, S>) -> bool {
1190 if self.len() != other.len() {
1191 return false;
1192 }
1193
1194 self.iter()
1195 .all(|(key, value)| other.get(&key).map_or(false, |v| *value == *v))
1196 }
1197}
1198
1199impl<K: Clone, V, S> Eq for CowHashMap<K, V, S>
1200where
1201 K: Eq + Hash,
1202 V: Eq,
1203 S: BuildHasher,
1204{
1205}
1206
1207impl<K: Clone, V, S> Debug for CowHashMap<K, V, S>
1208where
1209 K: Debug,
1210 V: Debug,
1211{
1212 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1213 f.debug_map().entries(self.iter()).finish()
1214 }
1215}
1216
1217impl<K: Clone, V, S> Default for CowHashMap<K, V, S>
1218where
1219 S: Default,
1220{
1221 /// Creates an empty `HashMap<K, V, S>`, with the `Default` value for the hasher.
1222 #[inline]
1223 fn default() -> CowHashMap<K, V, S> {
1224 CowHashMap::<K, V, S>::with_hasher(Default::default())
1225 }
1226}
1227
1228// Note: as what is currently the most convenient built-in way to construct
1229// a HashMap, a simple usage of this function must not *require* the user
1230// to provide a type annotation in order to infer the third type parameter
1231// (the hasher parameter, conventionally "S").
1232// To that end, this impl is defined using RandomState as the concrete
1233// type of S, rather than being generic over `S: BuildHasher + Default`.
1234// If type parameter defaults worked on impls, and if type parameter
1235// defaults could be mixed with const generics, then perhaps
1236// this could be generalized.
1237// See also the equivalent impl on HashSet.
1238impl<K: Clone, V, const N: usize> From<[(K, V); N]> for CowHashMap<K, V, RandomState>
1239where
1240 K: Eq + Hash,
1241{
1242 /// # Examples
1243 ///
1244 /// ```
1245 /// use cow_hashmap::CowHashMap as HashMap;
1246 ///
1247 /// let map1 = HashMap::from([(1, 2), (3, 4)]);
1248 /// let map2: HashMap<_, _> = [(1, 2), (3, 4)].into();
1249 /// assert_eq!(map1, map2);
1250 /// ```
1251 fn from(arr: [(K, V); N]) -> Self {
1252 Self::from_iter(arr)
1253 }
1254}
1255
1256/// An iterator over the entries of a `HashMap`.
1257///
1258/// This `struct` is created by the [`iter`] method on [`HashMap`]. See its
1259/// documentation for more.
1260///
1261/// [`iter`]: HashMap::iter
1262///
1263/// # Example
1264///
1265/// ```
1266/// use cow_hashmap::CowHashMap as HashMap;
1267///
1268/// let map = HashMap::from([
1269/// ("a", 1),
1270/// ]);
1271/// let iter = map.iter();
1272/// ```
1273pub struct Iter<K: Clone, V, S> {
1274 base: cow_hashbrown::hash_map::Iter<ShardIndex, ShardMap<K, V, S>>,
1275 shard1: Option<cow_hashbrown::hash_map::Iter<ShardIndex, base::CowHashMap<K, V, S>>>,
1276 shard2: Option<cow_hashbrown::hash_map::Iter<K, V>>,
1277}
1278
1279impl<K: Clone, V, S> Clone for Iter<K, V, S> {
1280 #[inline]
1281 fn clone(&self) -> Self {
1282 Iter {
1283 base: self.base.clone(),
1284 shard1: None,
1285 shard2: None,
1286 }
1287 }
1288}
1289
1290impl<K: Clone + Debug, V: Debug, S> fmt::Debug for Iter<K, V, S> {
1291 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1292 f.debug_list().entries(self.clone()).finish()
1293 }
1294}
1295
1296/// A mutable iterator over the entries of a `HashMap`.
1297///
1298/// This `struct` is created by the [`iter_mut`] method on [`HashMap`]. See its
1299/// documentation for more.
1300///
1301/// [`iter_mut`]: HashMap::iter_mut
1302///
1303/// # Example
1304///
1305/// ```
1306/// use cow_hashmap::CowHashMap as HashMap;
1307///
1308/// let mut map = HashMap::from([
1309/// ("a", 1),
1310/// ]);
1311/// let iter = map.iter_mut();
1312/// ```
1313pub struct IterMut<K: Clone, V, S> {
1314 base: cow_hashbrown::hash_map::Iter<ShardIndex, ShardMap<K, V, S>>,
1315 shard1: Option<cow_hashbrown::hash_map::Iter<ShardIndex, base::CowHashMap<K, V, S>>>,
1316 shard2: Option<cow_hashbrown::hash_map::IterMut<K, V>>,
1317}
1318
1319impl<K: Clone, V, S> IterMut<K, V, S> {
1320 /// Returns an iterator of references over the remaining items.
1321 #[inline]
1322 pub fn iter(&self) -> Iter<K, V, S> {
1323 Iter {
1324 base: self.base.clone(),
1325 shard1: None,
1326 shard2: None,
1327 }
1328 }
1329}
1330
1331/// An owning iterator over the entries of a `HashMap`.
1332///
1333/// This `struct` is created by the [`into_iter`] method on [`HashMap`]
1334/// (provided by the [`IntoIterator`] trait). See its documentation for more.
1335///
1336/// [`into_iter`]: IntoIterator::into_iter
1337///
1338/// # Example
1339///
1340/// ```
1341/// use cow_hashmap::CowHashMap as HashMap;
1342///
1343/// let map = HashMap::from([
1344/// ("a", 1),
1345/// ]);
1346/// let iter = map.into_iter();
1347/// ```
1348pub struct IntoIter<K: Clone, V, S> {
1349 base: cow_hashbrown::hash_map::Iter<ShardIndex, ShardMap<K, V, S>>,
1350 shard1: Option<cow_hashbrown::hash_map::Iter<ShardIndex, base::CowHashMap<K, V, S>>>,
1351 shard2: Option<cow_hashbrown::hash_map::Iter<K, V>>,
1352}
1353
1354impl<K: Clone, V, S> IntoIter<K, V, S> {
1355 /// Returns an iterator of references over the remaining items.
1356 #[inline]
1357 pub fn iter(&self) -> Iter<K, V, S> {
1358 Iter {
1359 base: self.base.clone(),
1360 shard1: None,
1361 shard2: None,
1362 }
1363 }
1364}
1365
1366/// An iterator over the keys of a `HashMap`.
1367///
1368/// This `struct` is created by the [`keys`] method on [`HashMap`]. See its
1369/// documentation for more.
1370///
1371/// [`keys`]: HashMap::keys
1372///
1373/// # Example
1374///
1375/// ```
1376/// use cow_hashmap::CowHashMap as HashMap;
1377///
1378/// let map = HashMap::from([
1379/// ("a", 1),
1380/// ]);
1381/// let iter_keys = map.keys();
1382/// ```
1383pub struct Keys<K: Clone, V, S> {
1384 inner: Iter<K, V, S>,
1385}
1386
1387impl<K: Clone, V, S> Clone for Keys<K, V, S> {
1388 #[inline]
1389 fn clone(&self) -> Self {
1390 Keys {
1391 inner: self.inner.clone(),
1392 }
1393 }
1394}
1395
1396impl<K: Clone + Debug, V, S> fmt::Debug for Keys<K, V, S> {
1397 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1398 f.debug_list().entries(self.clone()).finish()
1399 }
1400}
1401
1402/// An iterator over the values of a `HashMap`.
1403///
1404/// This `struct` is created by the [`values`] method on [`HashMap`]. See its
1405/// documentation for more.
1406///
1407/// [`values`]: HashMap::values
1408///
1409/// # Example
1410///
1411/// ```
1412/// use cow_hashmap::CowHashMap as HashMap;
1413///
1414/// let map = HashMap::from([
1415/// ("a", 1),
1416/// ]);
1417/// let iter_values = map.values();
1418/// ```
1419pub struct Values<K: Clone, V, S> {
1420 inner: Iter<K, V, S>,
1421}
1422
1423impl<K: Clone, V, S> Clone for Values<K, V, S> {
1424 #[inline]
1425 fn clone(&self) -> Self {
1426 Values {
1427 inner: self.inner.clone(),
1428 }
1429 }
1430}
1431
1432impl<K: Clone, V: Debug, S> fmt::Debug for Values<K, V, S> {
1433 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1434 f.debug_list().entries(self.clone()).finish()
1435 }
1436}
1437
1438/// A draining iterator over the entries of a `HashMap`.
1439///
1440/// This `struct` is created by the [`drain`] method on [`HashMap`]. See its
1441/// documentation for more.
1442///
1443/// [`drain`]: HashMap::drain
1444///
1445/// # Example
1446///
1447/// ```
1448/// use cow_hashmap::CowHashMap as HashMap;
1449///
1450/// let mut map = HashMap::from([
1451/// ("a", 1),
1452/// ]);
1453/// let iter = map.drain();
1454/// ```
1455pub struct Drain<K: Clone, V, S> {
1456 base: cow_hashbrown::hash_map::Iter<ShardIndex, ShardMap<K, V, S>>,
1457 shard1: Option<cow_hashbrown::hash_map::Iter<ShardIndex, base::CowHashMap<K, V, S>>>,
1458 shard2: Option<cow_hashbrown::hash_map::Iter<K, V>>,
1459}
1460
1461impl<'a, K: Clone, V, S> Drain<K, V, S> {
1462 /// Returns an iterator of references over the remaining items.
1463 #[inline]
1464 pub fn iter(&self) -> Iter<K, V, S> {
1465 Iter {
1466 base: self.base.clone(),
1467 shard1: None,
1468 shard2: None,
1469 }
1470 }
1471}
1472
1473/// A mutable iterator over the values of a `HashMap`.
1474///
1475/// This `struct` is created by the [`values_mut`] method on [`HashMap`]. See its
1476/// documentation for more.
1477///
1478/// [`values_mut`]: HashMap::values_mut
1479///
1480/// # Example
1481///
1482/// ```
1483/// use cow_hashmap::CowHashMap as HashMap;
1484///
1485/// let mut map = HashMap::from([
1486/// ("a", 1),
1487/// ]);
1488/// let iter_values = map.values_mut();
1489/// ```
1490pub struct ValuesMut<K: Clone, V, S> {
1491 inner: IterMut<K, V, S>,
1492}
1493
1494/// An owning iterator over the keys of a `HashMap`.
1495///
1496/// This `struct` is created by the [`into_keys`] method on [`HashMap`].
1497/// See its documentation for more.
1498///
1499/// [`into_keys`]: HashMap::into_keys
1500///
1501/// # Example
1502///
1503/// ```
1504/// use cow_hashmap::CowHashMap as HashMap;
1505///
1506/// let map = HashMap::from([
1507/// ("a", 1),
1508/// ]);
1509/// let iter_keys = map.into_keys();
1510/// ```
1511pub struct IntoKeys<K: Clone, V, S> {
1512 inner: IntoIter<K, V, S>,
1513}
1514
1515/// An owning iterator over the values of a `HashMap`.
1516///
1517/// This `struct` is created by the [`into_values`] method on [`HashMap`].
1518/// See its documentation for more.
1519///
1520/// [`into_values`]: HashMap::into_values
1521///
1522/// # Example
1523///
1524/// ```
1525/// use cow_hashmap::CowHashMap as HashMap;
1526///
1527/// let map = HashMap::from([
1528/// ("a", 1),
1529/// ]);
1530/// let iter_keys = map.into_values();
1531/// ```
1532pub struct IntoValues<K: Clone, V, S> {
1533 inner: IntoIter<K, V, S>,
1534}
1535
1536/// A view into a single entry in a map, which may either be vacant or occupied.
1537///
1538/// This `enum` is constructed from the [`entry`] method on [`HashMap`].
1539///
1540/// [`entry`]: HashMap::entry
1541pub enum Entry<K: Clone, V, S> {
1542 /// An occupied entry.
1543 Occupied(OccupiedEntry<K, V, S>),
1544
1545 /// A vacant entry.
1546 Vacant(VacantEntry<K, V, S>),
1547}
1548
1549impl<K: Clone + Debug, V: Debug, S> Debug for Entry<K, V, S> {
1550 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1551 match *self {
1552 Vacant(ref v) => f.debug_tuple("Entry").field(v).finish(),
1553 Occupied(ref o) => f.debug_tuple("Entry").field(o).finish(),
1554 }
1555 }
1556}
1557
1558/// A view into a single entry in a map, which may either be vacant or occupied.
1559///
1560/// This `enum` is constructed from the [`entry`] method on [`HashMap`].
1561///
1562/// [`entry`]: HashMap::entry
1563pub struct LockableEntry<'a, K: Clone, V, S>(Entry<K, V, S>, Option<MutexGuard<'a, ()>>);
1564
1565impl<K: Clone + Debug, V: Debug, S> Debug for LockableEntry<'_, K, V, S> {
1566 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1567 match self.0 {
1568 Vacant(ref v) => f.debug_tuple("Entry").field(v).finish(),
1569 Occupied(ref o) => f.debug_tuple("Entry").field(o).finish(),
1570 }
1571 }
1572}
1573
1574/// A view into an occupied entry in a `HashMap`.
1575/// It is part of the [`Entry`] enum.
1576pub struct OccupiedEntry<K: Clone, V, S> {
1577 base: cow_hashbrown::hash_map::OccupiedEntry<K, V, S>,
1578}
1579
1580impl<K: Clone + Debug, V: Debug, S> Debug for OccupiedEntry<K, V, S> {
1581 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1582 f.debug_struct("OccupiedEntry")
1583 .field("key", self.key())
1584 .field("value", &self.get())
1585 .finish_non_exhaustive()
1586 }
1587}
1588
1589/// A view into a vacant entry in a `HashMap`.
1590/// It is part of the [`Entry`] enum.
1591pub struct VacantEntry<K: Clone, V, S> {
1592 base: cow_hashbrown::hash_map::VacantEntry<K, V, S>,
1593}
1594
1595impl<K: Clone + Debug, V, S> Debug for VacantEntry<K, V, S> {
1596 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1597 f.debug_tuple("VacantEntry").field(self.key()).finish()
1598 }
1599}
1600
1601/// The error returned by [`try_insert`](HashMap::try_insert) when the key already exists.
1602///
1603/// Contains the occupied entry, and the value that was not inserted.
1604pub struct OccupiedError<K: Clone, V, S> {
1605 /// The entry in the map that was already occupied.
1606 pub entry: OccupiedEntry<K, V, S>,
1607 /// The value which was not inserted, because the entry was already occupied.
1608 pub value: V,
1609}
1610
1611impl<K: Clone + Debug, V: Debug, S> Debug for OccupiedError<K, V, S> {
1612 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1613 f.debug_struct("OccupiedError")
1614 .field("key", self.entry.key())
1615 .field("old_value", &self.entry.get())
1616 .field("new_value", &self.value)
1617 .finish_non_exhaustive()
1618 }
1619}
1620
1621impl<K: Clone + Debug, V: Debug, S> fmt::Display for OccupiedError<K, V, S> {
1622 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1623 write!(
1624 f,
1625 "failed to insert {:?}, key {:?} already exists with value {:?}",
1626 self.value,
1627 self.entry.key(),
1628 self.entry.get(),
1629 )
1630 }
1631}
1632
1633impl<K: Clone + fmt::Debug, V: fmt::Debug, S> Error for OccupiedError<K, V, S> {
1634 #[allow(deprecated)]
1635 fn description(&self) -> &str {
1636 "key already exists"
1637 }
1638}
1639
1640impl<K: Clone, V, S> IntoIterator for &CowHashMap<K, V, S>
1641where
1642 S: Clone,
1643{
1644 type Item = (K, Arc<V>);
1645 type IntoIter = IntoIter<K, V, S>;
1646
1647 #[inline]
1648 fn into_iter(self) -> IntoIter<K, V, S> {
1649 IntoIter {
1650 base: self.base.iter(),
1651 shard1: None,
1652 shard2: None,
1653 }
1654 }
1655}
1656
1657impl<K: Clone, V, S> IntoIterator for &mut CowHashMap<K, V, S>
1658where
1659 S: Clone,
1660{
1661 type Item = (K, Arc<V>);
1662 type IntoIter = IntoIter<K, V, S>;
1663
1664 #[inline]
1665 fn into_iter(self) -> IntoIter<K, V, S> {
1666 IntoIter {
1667 base: self.base.iter(),
1668 shard1: None,
1669 shard2: None,
1670 }
1671 }
1672}
1673
1674impl<K: Clone, V, S> IntoIterator for CowHashMap<K, V, S>
1675where
1676 S: Clone,
1677{
1678 type Item = (K, Arc<V>);
1679 type IntoIter = IntoIter<K, V, S>;
1680
1681 /// Creates a consuming iterator, that is, one that moves each key-value
1682 /// pair out of the map in arbitrary order. The map cannot be used after
1683 /// calling this.
1684 ///
1685 /// # Examples
1686 ///
1687 /// ```
1688 /// use cow_hashmap::CowHashMap as HashMap;
1689 /// use std::sync::Arc;
1690 ///
1691 /// let map = HashMap::from([
1692 /// ("a", 1),
1693 /// ("b", 2),
1694 /// ("c", 3),
1695 /// ]);
1696 ///
1697 /// // Not possible with .iter()
1698 /// let vec: Vec<(&str, Arc<i32>)> = map.into_iter().collect();
1699 /// ```
1700 #[inline]
1701 fn into_iter(self) -> IntoIter<K, V, S> {
1702 IntoIter {
1703 base: self.base.iter(),
1704 shard1: None,
1705 shard2: None,
1706 }
1707 }
1708}
1709
1710impl<K: Clone, V, S> Iterator for Iter<K, V, S> {
1711 type Item = (K, Arc<V>);
1712
1713 #[inline]
1714 fn next(&mut self) -> Option<(K, Arc<V>)> {
1715 loop {
1716 if let Some(ref mut shard2) = self.shard2 {
1717 if let Some(r) = shard2.next() {
1718 return Some(r);
1719 }
1720 self.shard2.take();
1721 }
1722 if let Some(ref mut shard1) = self.shard1 {
1723 if let Some(r) = shard1.next() {
1724 self.shard2.replace(r.1.iter());
1725 continue;
1726 }
1727 self.shard1.take();
1728 }
1729 if let Some(next) = self.base.next() {
1730 self.shard1.replace(next.1.iter());
1731 continue;
1732 }
1733 return None;
1734 }
1735 }
1736 #[inline]
1737 fn count(self) -> usize {
1738 self.base
1739 .clone()
1740 .map(|(_, t)| t.iter().map(|(_, t)| t.len()).sum::<usize>())
1741 .sum()
1742 }
1743}
1744impl<K: Clone, V, S> ExactSizeIterator for Iter<K, V, S> {
1745 #[inline]
1746 fn len(&self) -> usize {
1747 self.base
1748 .clone()
1749 .map(|(_, t)| t.iter().map(|(_, t)| t.len()).sum::<usize>())
1750 .sum()
1751 }
1752}
1753
1754impl<K: Clone, V, S> FusedIterator for Iter<K, V, S> {}
1755
1756impl<K: Clone, V, S> Iterator for IterMut<K, V, S>
1757where
1758 V: Clone,
1759{
1760 type Item = (K, CowValueGuard<V>);
1761
1762 #[inline]
1763 fn next(&mut self) -> Option<(K, CowValueGuard<V>)> {
1764 loop {
1765 if let Some(ref mut shard2) = self.shard2 {
1766 if let Some(r) = shard2.next() {
1767 return Some(r);
1768 }
1769 self.shard2.take();
1770 }
1771 if let Some(ref mut shard1) = self.shard1 {
1772 if let Some(r) = shard1.next() {
1773 self.shard2.replace(r.1.iter_mut());
1774 continue;
1775 }
1776 self.shard1.take();
1777 }
1778 if let Some(next) = self.base.next() {
1779 self.shard1.replace(next.1.iter());
1780 continue;
1781 }
1782 return None;
1783 }
1784 }
1785 #[inline]
1786 fn count(self) -> usize {
1787 self.base
1788 .clone()
1789 .map(|(_, t)| t.iter().map(|(_, t)| t.len()).sum::<usize>())
1790 .sum()
1791 }
1792}
1793impl<K: Clone, V, S> ExactSizeIterator for IterMut<K, V, S>
1794where
1795 V: Clone,
1796{
1797 #[inline]
1798 fn len(&self) -> usize {
1799 self.base
1800 .clone()
1801 .map(|(_, t)| t.iter().map(|(_, t)| t.len()).sum::<usize>())
1802 .sum()
1803 }
1804}
1805impl<K: Clone, V, S> FusedIterator for IterMut<K, V, S> where V: Clone {}
1806
1807impl<K: Clone, V, S> fmt::Debug for IterMut<K, V, S>
1808where
1809 K: fmt::Debug,
1810 V: fmt::Debug,
1811{
1812 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1813 f.debug_list().entries(self.iter()).finish()
1814 }
1815}
1816
1817impl<K: Clone, V, S> Iterator for IntoIter<K, V, S>
1818where
1819 S: Clone,
1820{
1821 type Item = (K, Arc<V>);
1822
1823 #[inline]
1824 fn next(&mut self) -> Option<(K, Arc<V>)> {
1825 loop {
1826 if let Some(ref mut shard2) = self.shard2 {
1827 if let Some(r) = shard2.next() {
1828 return Some(r);
1829 }
1830 self.shard2.take();
1831 }
1832 if let Some(ref mut shard1) = self.shard1 {
1833 if let Some(r) = shard1.next() {
1834 self.shard2.replace(r.1.iter());
1835 continue;
1836 }
1837 self.shard1.take();
1838 }
1839 if let Some(next) = self.base.next() {
1840 self.shard1.replace(next.1.iter());
1841 continue;
1842 }
1843 return None;
1844 }
1845 }
1846 #[inline]
1847 fn count(self) -> usize {
1848 self.base
1849 .clone()
1850 .map(|(_, t)| t.iter().map(|(_, t)| t.len()).sum::<usize>())
1851 .sum()
1852 }
1853}
1854impl<K: Clone, V, S> ExactSizeIterator for IntoIter<K, V, S>
1855where
1856 S: Clone,
1857{
1858 #[inline]
1859 fn len(&self) -> usize {
1860 self.base
1861 .clone()
1862 .map(|(_, t)| t.iter().map(|(_, t)| t.len()).sum::<usize>())
1863 .sum()
1864 }
1865}
1866impl<K: Clone, V, S> FusedIterator for IntoIter<K, V, S> where S: Clone {}
1867
1868impl<K: Clone + Debug, V: Debug, S> fmt::Debug for IntoIter<K, V, S> {
1869 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1870 f.debug_list().entries(self.iter()).finish()
1871 }
1872}
1873
1874impl<K: Clone, V, S> Iterator for Keys<K, V, S> {
1875 type Item = K;
1876
1877 #[inline]
1878 fn next(&mut self) -> Option<K> {
1879 self.inner.next().map(|(k, _)| k)
1880 }
1881 #[inline]
1882 fn size_hint(&self) -> (usize, Option<usize>) {
1883 self.inner.size_hint()
1884 }
1885 #[inline]
1886 fn count(self) -> usize {
1887 self.inner.len()
1888 }
1889 #[inline]
1890 fn fold<B, F>(self, init: B, mut f: F) -> B
1891 where
1892 Self: Sized,
1893 F: FnMut(B, Self::Item) -> B,
1894 {
1895 self.inner.fold(init, |acc, (k, _)| f(acc, k))
1896 }
1897}
1898impl<K: Clone, V, S> ExactSizeIterator for Keys<K, V, S> {
1899 #[inline]
1900 fn len(&self) -> usize {
1901 self.inner.len()
1902 }
1903}
1904impl<K: Clone, V, S> FusedIterator for Keys<K, V, S> {}
1905
1906impl<K: Clone, V, S> Iterator for Values<K, V, S> {
1907 type Item = Arc<V>;
1908
1909 #[inline]
1910 fn next(&mut self) -> Option<Arc<V>> {
1911 self.inner.next().map(|(_, v)| v)
1912 }
1913 #[inline]
1914 fn size_hint(&self) -> (usize, Option<usize>) {
1915 self.inner.size_hint()
1916 }
1917 #[inline]
1918 fn count(self) -> usize {
1919 self.inner.len()
1920 }
1921 #[inline]
1922 fn fold<B, F>(self, init: B, mut f: F) -> B
1923 where
1924 Self: Sized,
1925 F: FnMut(B, Self::Item) -> B,
1926 {
1927 self.inner.fold(init, |acc, (_, v)| f(acc, v))
1928 }
1929}
1930impl<K: Clone, V, S> ExactSizeIterator for Values<K, V, S> {
1931 #[inline]
1932 fn len(&self) -> usize {
1933 self.inner.len()
1934 }
1935}
1936impl<K: Clone, V, S> FusedIterator for Values<K, V, S> {}
1937
1938impl<K: Clone, V, S> Iterator for ValuesMut<K, V, S>
1939where
1940 V: Clone,
1941{
1942 type Item = CowValueGuard<V>;
1943
1944 #[inline]
1945 fn next(&mut self) -> Option<CowValueGuard<V>> {
1946 self.inner.next().map(|(_, v)| v)
1947 }
1948 #[inline]
1949 fn size_hint(&self) -> (usize, Option<usize>) {
1950 self.inner.size_hint()
1951 }
1952 #[inline]
1953 fn count(self) -> usize {
1954 self.inner.len()
1955 }
1956 #[inline]
1957 fn fold<B, F>(self, init: B, mut f: F) -> B
1958 where
1959 Self: Sized,
1960 F: FnMut(B, Self::Item) -> B,
1961 {
1962 self.inner.fold(init, |acc, (_, v)| f(acc, v))
1963 }
1964}
1965impl<K: Clone, V, S> ExactSizeIterator for ValuesMut<K, V, S>
1966where
1967 V: Clone,
1968{
1969 #[inline]
1970 fn len(&self) -> usize {
1971 self.inner.len()
1972 }
1973}
1974impl<K: Clone, V, S> FusedIterator for ValuesMut<K, V, S> where V: Clone {}
1975
1976impl<K: Clone, V: fmt::Debug, S> fmt::Debug for ValuesMut<K, V, S> {
1977 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1978 f.debug_list()
1979 .entries(self.inner.iter().map(|(_, val)| val))
1980 .finish()
1981 }
1982}
1983
1984impl<K: Clone, V, S> Iterator for IntoKeys<K, V, S>
1985where
1986 S: Clone,
1987{
1988 type Item = K;
1989
1990 #[inline]
1991 fn next(&mut self) -> Option<K> {
1992 self.inner.next().map(|(k, _)| k)
1993 }
1994 #[inline]
1995 fn size_hint(&self) -> (usize, Option<usize>) {
1996 self.inner.size_hint()
1997 }
1998 #[inline]
1999 fn count(self) -> usize {
2000 self.inner.len()
2001 }
2002 #[inline]
2003 fn fold<B, F>(self, init: B, mut f: F) -> B
2004 where
2005 Self: Sized,
2006 F: FnMut(B, Self::Item) -> B,
2007 {
2008 self.inner.fold(init, |acc, (k, _)| f(acc, k))
2009 }
2010}
2011impl<K: Clone, V, S> ExactSizeIterator for IntoKeys<K, V, S>
2012where
2013 S: Clone,
2014{
2015 #[inline]
2016 fn len(&self) -> usize {
2017 self.inner.len()
2018 }
2019}
2020impl<K: Clone, V, S> FusedIterator for IntoKeys<K, V, S> where S: Clone {}
2021
2022impl<K: Clone + Debug, V, S> fmt::Debug for IntoKeys<K, V, S> {
2023 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2024 f.debug_list()
2025 .entries(self.inner.iter().map(|(k, _)| k))
2026 .finish()
2027 }
2028}
2029
2030impl<K: Clone, V, S> Iterator for IntoValues<K, V, S>
2031where
2032 S: Clone,
2033{
2034 type Item = Arc<V>;
2035
2036 #[inline]
2037 fn next(&mut self) -> Option<Arc<V>> {
2038 self.inner.next().map(|(_, v)| v)
2039 }
2040 #[inline]
2041 fn size_hint(&self) -> (usize, Option<usize>) {
2042 self.inner.size_hint()
2043 }
2044 #[inline]
2045 fn count(self) -> usize {
2046 self.inner.len()
2047 }
2048 #[inline]
2049 fn fold<B, F>(self, init: B, mut f: F) -> B
2050 where
2051 Self: Sized,
2052 F: FnMut(B, Self::Item) -> B,
2053 {
2054 self.inner.fold(init, |acc, (_, v)| f(acc, v))
2055 }
2056}
2057impl<K: Clone, V, S> ExactSizeIterator for IntoValues<K, V, S>
2058where
2059 S: Clone,
2060{
2061 #[inline]
2062 fn len(&self) -> usize {
2063 self.inner.len()
2064 }
2065}
2066impl<K: Clone, V, S> FusedIterator for IntoValues<K, V, S> where S: Clone {}
2067
2068impl<K: Clone, V: Debug, S> fmt::Debug for IntoValues<K, V, S> {
2069 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2070 f.debug_list()
2071 .entries(self.inner.iter().map(|(_, v)| v))
2072 .finish()
2073 }
2074}
2075
2076impl<'a, K: Clone, V, S> Iterator for Drain<K, V, S> {
2077 type Item = (K, Arc<V>);
2078
2079 #[inline]
2080 fn next(&mut self) -> Option<(K, Arc<V>)> {
2081 loop {
2082 if let Some(ref mut shard2) = self.shard2 {
2083 if let Some(r) = shard2.next() {
2084 return Some(r);
2085 }
2086 self.shard2.take();
2087 }
2088 if let Some(ref mut shard1) = self.shard1 {
2089 if let Some(r) = shard1.next() {
2090 self.shard2.replace(r.1.iter());
2091 continue;
2092 }
2093 self.shard1.take();
2094 }
2095 if let Some(next) = self.base.next() {
2096 self.shard1.replace(next.1.iter());
2097 continue;
2098 }
2099 return None;
2100 }
2101 }
2102}
2103impl<K: Clone, V, S> ExactSizeIterator for Drain<K, V, S> {
2104 #[inline]
2105 fn len(&self) -> usize {
2106 self.base
2107 .clone()
2108 .map(|(_, t)| t.iter().map(|(_, t)| t.len()).sum::<usize>())
2109 .sum()
2110 }
2111}
2112impl<K: Clone, V, S> FusedIterator for Drain<K, V, S> {}
2113
2114impl<K: Clone, V, S> fmt::Debug for Drain<K, V, S>
2115where
2116 K: fmt::Debug,
2117 V: fmt::Debug,
2118{
2119 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2120 f.debug_list().entries(self.iter()).finish()
2121 }
2122}
2123
2124impl<K: Clone, V, S> Entry<K, V, S> {
2125 /// Ensures a value is in the entry by inserting the default if empty, and returns
2126 /// a mutable reference to the value in the entry.
2127 ///
2128 /// # Examples
2129 ///
2130 /// ```
2131 /// use cow_hashmap::CowHashMap as HashMap;
2132 /// use std::sync::Arc;
2133 ///
2134 /// let mut map: HashMap<&str, u32> = HashMap::new();
2135 ///
2136 /// map.entry("poneyland").or_insert(3);
2137 /// assert_eq!(map.get("poneyland").unwrap(), Arc::new(3));
2138 ///
2139 /// *map.entry("poneyland").or_insert(10) *= 2;
2140 /// assert_eq!(map.get("poneyland").unwrap(), Arc::new(6));
2141 /// ```
2142 #[inline]
2143 pub fn or_insert(self, default: V) -> Arc<V>
2144 where
2145 K: Hash,
2146 S: BuildHasher,
2147 {
2148 match self {
2149 Occupied(entry) => entry.get(),
2150 Vacant(entry) => entry.insert(default),
2151 }
2152 }
2153
2154 /// Ensures a value is in the entry by inserting the default if empty, and returns
2155 /// a mutable reference to the value in the entry.
2156 ///
2157 /// # Examples
2158 ///
2159 /// ```
2160 /// use cow_hashmap::CowHashMap as HashMap;
2161 /// use std::sync::Arc;
2162 ///
2163 /// let mut map: HashMap<&str, u32> = HashMap::new();
2164 ///
2165 /// map.entry("poneyland").or_insert(3);
2166 /// assert_eq!(map.get("poneyland").unwrap(), Arc::new(3));
2167 ///
2168 /// *map.entry("poneyland").or_insert(10) *= 2;
2169 /// assert_eq!(map.get("poneyland").unwrap(), Arc::new(6));
2170 /// ```
2171 #[inline]
2172 pub fn or_insert_mut(self, default: V) -> CowValueGuard<V>
2173 where
2174 K: Hash,
2175 S: BuildHasher,
2176 V: Clone,
2177 {
2178 match self {
2179 Occupied(entry) => entry.into_mut(),
2180 Vacant(entry) => entry.insert_mut(default),
2181 }
2182 }
2183
2184 /// Ensures a value is in the entry by inserting the result of the default function if empty,
2185 /// and returns a mutable reference to the value in the entry.
2186 ///
2187 /// # Examples
2188 ///
2189 /// ```
2190 /// use cow_hashmap::CowHashMap as HashMap;
2191 /// use std::sync::Arc;
2192 ///
2193 /// let mut map = HashMap::new();
2194 /// let value = "hoho";
2195 ///
2196 /// map.entry("poneyland").or_insert_with(|| value);
2197 ///
2198 /// assert_eq!(map.get("poneyland").unwrap(), Arc::new("hoho"));
2199 /// ```
2200 #[inline]
2201 pub fn or_insert_with<F: FnOnce() -> V>(self, default: F) -> Arc<V>
2202 where
2203 K: Hash,
2204 S: BuildHasher,
2205 {
2206 match self {
2207 Occupied(entry) => entry.get(),
2208 Vacant(entry) => entry.insert(default()),
2209 }
2210 }
2211
2212 /// Ensures a value is in the entry by inserting the result of the default function if empty,
2213 /// and returns a mutable reference to the value in the entry.
2214 ///
2215 /// # Examples
2216 ///
2217 /// ```
2218 /// use cow_hashmap::CowHashMap as HashMap;
2219 /// use std::sync::Arc;
2220 ///
2221 /// let mut map = HashMap::new();
2222 /// let value = "hoho";
2223 ///
2224 /// map.entry("poneyland").or_insert_with(|| value);
2225 ///
2226 /// assert_eq!(map.get("poneyland").unwrap(), Arc::new("hoho"));
2227 /// ```
2228 #[inline]
2229 pub fn or_insert_with_mut<F: FnOnce() -> V>(self, default: F) -> CowValueGuard<V>
2230 where
2231 K: Hash,
2232 S: BuildHasher,
2233 V: Clone,
2234 {
2235 match self {
2236 Occupied(entry) => entry.into_mut(),
2237 Vacant(entry) => entry.insert_mut(default()),
2238 }
2239 }
2240
2241 /// Ensures a value is in the entry by trying to insert the result of function if empty,
2242 /// and returns a mutable reference to the value in the entry if that function was
2243 /// successful.
2244 ///
2245 /// # Examples
2246 ///
2247 /// ```
2248 /// use cow_hashmap::CowHashMap as HashMap;
2249 /// use std::sync::Arc;
2250 ///
2251 /// let mut map = HashMap::new();
2252 /// let value = "hoho";
2253 ///
2254 /// map.entry("poneyland").or_try_insert_with(|| Some(value)).unwrap();
2255 ///
2256 /// assert_eq!(map.get("poneyland").unwrap(), Arc::new("hoho"));
2257 /// ```
2258 #[inline]
2259 pub fn or_try_insert_with<F: FnOnce() -> Option<V>>(self, f: F) -> Option<Arc<V>>
2260 where
2261 K: Hash,
2262 S: BuildHasher,
2263 {
2264 Some(match self {
2265 Occupied(entry) => entry.get(),
2266 Vacant(entry) => entry.insert(f()?),
2267 })
2268 }
2269
2270 /// Ensures a value is in the entry by trying to insert the result of function if empty,
2271 /// and returns a mutable reference to the value in the entry if that function was
2272 /// successful.
2273 ///
2274 /// # Examples
2275 ///
2276 /// ```
2277 /// use cow_hashmap::CowHashMap as HashMap;
2278 /// use std::sync::Arc;
2279 ///
2280 /// let mut map = HashMap::new();
2281 /// let value = "hoho";
2282 ///
2283 /// map.entry("poneyland").or_try_insert_with(|| Some(value)).unwrap();
2284 ///
2285 /// assert_eq!(map.get("poneyland").unwrap(), Arc::new("hoho"));
2286 /// ```
2287 #[inline]
2288 pub fn or_try_insert_with_mut<F: FnOnce() -> Option<V>>(self, f: F) -> Option<CowValueGuard<V>>
2289 where
2290 K: Hash,
2291 S: BuildHasher,
2292 V: Clone,
2293 {
2294 Some(match self {
2295 Occupied(entry) => entry.into_mut(),
2296 Vacant(entry) => entry.insert_mut(f()?),
2297 })
2298 }
2299
2300 /// Ensures a value is in the entry by inserting, if empty, the result of the default function.
2301 /// This method allows for generating key-derived values for insertion by providing the default
2302 /// function a reference to the key that was moved during the `.entry(key)` method call.
2303 ///
2304 /// The reference to the moved key is provided so that cloning or copying the key is
2305 /// unnecessary, unlike with `.or_insert_with(|| ... )`.
2306 ///
2307 /// # Examples
2308 ///
2309 /// ```
2310 /// use cow_hashmap::CowHashMap as HashMap;
2311 /// use std::sync::Arc;
2312 ///
2313 /// let mut map: HashMap<&str, usize> = HashMap::new();
2314 ///
2315 /// map.entry("poneyland").or_insert_with_key(|key| key.chars().count());
2316 ///
2317 /// assert_eq!(map.get("poneyland").unwrap(), Arc::new(9));
2318 /// ```
2319 #[inline]
2320 pub fn or_insert_with_key<F: FnOnce(&K) -> V>(self, default: F) -> Arc<V>
2321 where
2322 K: Hash,
2323 S: BuildHasher,
2324 {
2325 match self {
2326 Occupied(entry) => entry.get(),
2327 Vacant(entry) => {
2328 let value = default(entry.key());
2329 entry.insert(value)
2330 }
2331 }
2332 }
2333
2334 /// Ensures a value is in the entry by inserting, if empty, the result of the default function.
2335 /// This method allows for generating key-derived values for insertion by providing the default
2336 /// function a reference to the key that was moved during the `.entry(key)` method call.
2337 ///
2338 /// The reference to the moved key is provided so that cloning or copying the key is
2339 /// unnecessary, unlike with `.or_insert_with(|| ... )`.
2340 ///
2341 /// # Examples
2342 ///
2343 /// ```
2344 /// use cow_hashmap::CowHashMap as HashMap;
2345 /// use std::sync::Arc;
2346 ///
2347 /// let mut map: HashMap<&str, usize> = HashMap::new();
2348 ///
2349 /// map.entry("poneyland").or_insert_with_key(|key| key.chars().count());
2350 ///
2351 /// assert_eq!(map.get("poneyland").unwrap(), Arc::new(9));
2352 /// ```
2353 #[inline]
2354 pub fn or_insert_with_key_mut<F: FnOnce(&K) -> V>(self, default: F) -> CowValueGuard<V>
2355 where
2356 K: Hash,
2357 S: BuildHasher,
2358 V: Clone,
2359 {
2360 match self {
2361 Occupied(entry) => entry.into_mut(),
2362 Vacant(entry) => {
2363 let value = default(entry.key());
2364 entry.insert_mut(value)
2365 }
2366 }
2367 }
2368
2369 /// Returns a reference to this entry's key.
2370 ///
2371 /// # Examples
2372 ///
2373 /// ```
2374 /// use cow_hashmap::CowHashMap as HashMap;
2375 ///
2376 /// let mut map: HashMap<&str, u32> = HashMap::new();
2377 /// assert_eq!(map.entry("poneyland").key(), &"poneyland");
2378 /// ```
2379 #[inline]
2380 pub fn key(&self) -> &K {
2381 match *self {
2382 Occupied(ref entry) => entry.key(),
2383 Vacant(ref entry) => entry.key(),
2384 }
2385 }
2386
2387 /// Provides in-place access to an occupied entry before any
2388 /// potential inserts into the map.
2389 #[inline]
2390 pub fn and<F>(self, f: F) -> Self
2391 where
2392 F: FnOnce(Arc<V>),
2393 V: Clone,
2394 {
2395 match self {
2396 Occupied(entry) => {
2397 f(entry.get());
2398 Occupied(entry)
2399 }
2400 Vacant(entry) => Vacant(entry),
2401 }
2402 }
2403
2404 /// Provides in-place mutable access to an occupied entry before any
2405 /// potential inserts into the map.
2406 ///
2407 /// # Examples
2408 ///
2409 /// ```
2410 /// use cow_hashmap::CowHashMap as HashMap;
2411 ///
2412 /// let mut map: HashMap<&str, u32> = HashMap::new();
2413 ///
2414 /// map.entry("poneyland")
2415 /// .and_modify(|mut e| { *e += 1 })
2416 /// .or_insert(42);
2417 /// assert_eq!(*map.get("poneyland").unwrap(), 42);
2418 ///
2419 /// map.entry("poneyland")
2420 /// .and_modify(|mut e| { *e += 1 })
2421 /// .or_insert(42);
2422 /// assert_eq!(*map.get("poneyland").unwrap(), 43);
2423 /// ```
2424 #[inline]
2425 pub fn and_modify<F>(self, f: F) -> Self
2426 where
2427 F: FnOnce(CowValueGuard<V>),
2428 V: Clone,
2429 {
2430 match self {
2431 Occupied(entry) => {
2432 f(entry.get_mut());
2433 Occupied(entry)
2434 }
2435 Vacant(entry) => Vacant(entry),
2436 }
2437 }
2438}
2439
2440impl<K: Clone, V, S> LockableEntry<'_, K, V, S> {
2441 /// Ensures a value is in the entry by inserting the default if empty, and returns
2442 /// a mutable reference to the value in the entry.
2443 ///
2444 /// # Examples
2445 ///
2446 /// ```
2447 /// use cow_hashmap::CowHashMap as HashMap;
2448 /// use std::sync::Arc;
2449 ///
2450 /// let mut map: HashMap<&str, u32> = HashMap::new();
2451 ///
2452 /// map.entry("poneyland").or_insert(3);
2453 /// assert_eq!(map.get("poneyland").unwrap(), Arc::new(3));
2454 ///
2455 /// *map.entry("poneyland").or_insert(10) *= 2;
2456 /// assert_eq!(map.get("poneyland").unwrap(), Arc::new(6));
2457 /// ```
2458 #[inline]
2459 pub fn or_insert(self, default: V) -> Arc<V>
2460 where
2461 K: Hash,
2462 S: BuildHasher,
2463 {
2464 self.0.or_insert(default)
2465 }
2466
2467 /// Ensures a value is in the entry by inserting the default if empty, and returns
2468 /// a mutable reference to the value in the entry.
2469 ///
2470 /// # Examples
2471 ///
2472 /// ```
2473 /// use cow_hashmap::CowHashMap as HashMap;
2474 /// use std::sync::Arc;
2475 ///
2476 /// let mut map: HashMap<&str, u32> = HashMap::new();
2477 ///
2478 /// map.entry("poneyland").or_insert(3);
2479 /// assert_eq!(map.get("poneyland").unwrap(), Arc::new(3));
2480 ///
2481 /// *map.entry("poneyland").or_insert(10) *= 2;
2482 /// assert_eq!(map.get("poneyland").unwrap(), Arc::new(6));
2483 /// ```
2484 #[inline]
2485 pub fn or_insert_mut(self, default: V) -> CowValueGuard<V>
2486 where
2487 K: Hash,
2488 S: BuildHasher,
2489 V: Clone,
2490 {
2491 self.0.or_insert_mut(default)
2492 }
2493
2494 /// Ensures a value is in the entry by inserting the result of the default function if empty,
2495 /// and returns a mutable reference to the value in the entry.
2496 ///
2497 /// # Examples
2498 ///
2499 /// ```
2500 /// use cow_hashmap::CowHashMap as HashMap;
2501 /// use std::sync::Arc;
2502 ///
2503 /// let mut map = HashMap::new();
2504 /// let value = "hoho";
2505 ///
2506 /// map.entry("poneyland").or_insert_with(|| value);
2507 ///
2508 /// assert_eq!(map.get("poneyland").unwrap(), Arc::new("hoho"));
2509 /// ```
2510 #[inline]
2511 pub fn or_insert_with<F: FnOnce() -> V>(self, default: F) -> Arc<V>
2512 where
2513 K: Hash,
2514 S: BuildHasher,
2515 {
2516 self.0.or_insert_with(default)
2517 }
2518
2519 /// Ensures a value is in the entry by inserting the result of the default function if empty,
2520 /// and returns a mutable reference to the value in the entry.
2521 ///
2522 /// # Examples
2523 ///
2524 /// ```
2525 /// use cow_hashmap::CowHashMap as HashMap;
2526 /// use std::sync::Arc;
2527 ///
2528 /// let mut map = HashMap::new();
2529 /// let value = "hoho";
2530 ///
2531 /// map.entry("poneyland").or_insert_with(|| value);
2532 ///
2533 /// assert_eq!(map.get("poneyland").unwrap(), Arc::new("hoho"));
2534 /// ```
2535 #[inline]
2536 pub fn or_insert_with_mut<F: FnOnce() -> V>(self, default: F) -> CowValueGuard<V>
2537 where
2538 K: Hash,
2539 S: BuildHasher,
2540 V: Clone,
2541 {
2542 self.0.or_insert_with_mut(default)
2543 }
2544
2545 /// Ensures a value is in the entry by trying to insert the result of function if empty,
2546 /// and returns a mutable reference to the value in the entry if that function was
2547 /// successful.
2548 ///
2549 /// # Examples
2550 ///
2551 /// ```
2552 /// use cow_hashmap::CowHashMap as HashMap;
2553 /// use std::sync::Arc;
2554 ///
2555 /// let mut map = HashMap::new();
2556 /// let value = "hoho";
2557 ///
2558 /// map.entry("poneyland").or_try_insert_with(|| Some(value)).unwrap();
2559 ///
2560 /// assert_eq!(map.get("poneyland").unwrap(), Arc::new("hoho"));
2561 /// ```
2562 #[inline]
2563 pub fn or_try_insert_with<F: FnOnce() -> Option<V>>(self, f: F) -> Option<Arc<V>>
2564 where
2565 K: Hash,
2566 S: BuildHasher,
2567 {
2568 self.0.or_try_insert_with(f)
2569 }
2570
2571 /// Ensures a value is in the entry by trying to insert the result of function if empty,
2572 /// and returns a mutable reference to the value in the entry if that function was
2573 /// successful.
2574 ///
2575 /// # Examples
2576 ///
2577 /// ```
2578 /// use cow_hashmap::CowHashMap as HashMap;
2579 /// use std::sync::Arc;
2580 ///
2581 /// let mut map = HashMap::new();
2582 /// let value = "hoho";
2583 ///
2584 /// map.entry("poneyland").or_try_insert_with(|| Some(value)).unwrap();
2585 ///
2586 /// assert_eq!(map.get("poneyland").unwrap(), Arc::new("hoho"));
2587 /// ```
2588 #[inline]
2589 pub fn or_try_insert_with_mut<F: FnOnce() -> Option<V>>(self, f: F) -> Option<CowValueGuard<V>>
2590 where
2591 K: Hash,
2592 S: BuildHasher,
2593 V: Clone,
2594 {
2595 self.0.or_try_insert_with_mut(f)
2596 }
2597
2598 /// Ensures a value is in the entry by inserting, if empty, the result of the default function.
2599 /// This method allows for generating key-derived values for insertion by providing the default
2600 /// function a reference to the key that was moved during the `.entry(key)` method call.
2601 ///
2602 /// The reference to the moved key is provided so that cloning or copying the key is
2603 /// unnecessary, unlike with `.or_insert_with(|| ... )`.
2604 ///
2605 /// # Examples
2606 ///
2607 /// ```
2608 /// use cow_hashmap::CowHashMap as HashMap;
2609 /// use std::sync::Arc;
2610 ///
2611 /// let mut map: HashMap<&str, usize> = HashMap::new();
2612 ///
2613 /// map.entry("poneyland").or_insert_with_key(|key| key.chars().count());
2614 ///
2615 /// assert_eq!(map.get("poneyland").unwrap(), Arc::new(9));
2616 /// ```
2617 #[inline]
2618 pub fn or_insert_with_key<F: FnOnce(&K) -> V>(self, default: F) -> Arc<V>
2619 where
2620 K: Hash,
2621 S: BuildHasher,
2622 {
2623 self.0.or_insert_with_key(default)
2624 }
2625
2626 /// Ensures a value is in the entry by inserting, if empty, the result of the default function.
2627 /// This method allows for generating key-derived values for insertion by providing the default
2628 /// function a reference to the key that was moved during the `.entry(key)` method call.
2629 ///
2630 /// The reference to the moved key is provided so that cloning or copying the key is
2631 /// unnecessary, unlike with `.or_insert_with(|| ... )`.
2632 ///
2633 /// # Examples
2634 ///
2635 /// ```
2636 /// use cow_hashmap::CowHashMap as HashMap;
2637 /// use std::sync::Arc;
2638 ///
2639 /// let mut map: HashMap<&str, usize> = HashMap::new();
2640 ///
2641 /// map.entry("poneyland").or_insert_with_key(|key| key.chars().count());
2642 ///
2643 /// assert_eq!(map.get("poneyland").unwrap(), Arc::new(9));
2644 /// ```
2645 #[inline]
2646 pub fn or_insert_with_key_mut<F: FnOnce(&K) -> V>(self, default: F) -> CowValueGuard<V>
2647 where
2648 K: Hash,
2649 S: BuildHasher,
2650 V: Clone,
2651 {
2652 self.0.or_insert_with_key_mut(default)
2653 }
2654
2655 /// Returns a reference to this entry's key.
2656 ///
2657 /// # Examples
2658 ///
2659 /// ```
2660 /// use cow_hashmap::CowHashMap as HashMap;
2661 ///
2662 /// let mut map: HashMap<&str, u32> = HashMap::new();
2663 /// assert_eq!(map.entry("poneyland").key(), &"poneyland");
2664 /// ```
2665 #[inline]
2666 pub fn key(&self) -> &K {
2667 self.0.key()
2668 }
2669
2670 /// Provides in-place access to an occupied entry before any
2671 /// potential inserts into the map.
2672 #[inline]
2673 pub fn and<F>(self, f: F) -> Self
2674 where
2675 F: FnOnce(Arc<V>),
2676 V: Clone,
2677 {
2678 match self.0 {
2679 Occupied(entry) => {
2680 f(entry.get());
2681 Self(Occupied(entry), self.1)
2682 }
2683 Vacant(entry) => Self(Vacant(entry), self.1),
2684 }
2685 }
2686
2687 /// Provides in-place mutable access to an occupied entry before any
2688 /// potential inserts into the map.
2689 ///
2690 /// # Examples
2691 ///
2692 /// ```
2693 /// use cow_hashmap::CowHashMap as HashMap;
2694 ///
2695 /// let mut map: HashMap<&str, u32> = HashMap::new();
2696 ///
2697 /// map.entry("poneyland")
2698 /// .and_modify(|mut e| { *e += 1 })
2699 /// .or_insert(42);
2700 /// assert_eq!(*map.get("poneyland").unwrap(), 42);
2701 ///
2702 /// map.entry("poneyland")
2703 /// .and_modify(|mut e| { *e += 1 })
2704 /// .or_insert(42);
2705 /// assert_eq!(*map.get("poneyland").unwrap(), 43);
2706 /// ```
2707 #[inline]
2708 pub fn and_modify<F>(self, f: F) -> Self
2709 where
2710 F: FnOnce(CowValueGuard<V>),
2711 V: Clone,
2712 {
2713 Self(self.0.and_modify(f), self.1)
2714 }
2715}
2716
2717impl<K: Clone, V: Default, S> Entry<K, V, S> {
2718 /// Ensures a value is in the entry by inserting the default value if empty,
2719 /// and returns a mutable reference to the value in the entry.
2720 ///
2721 /// # Examples
2722 ///
2723 /// ```
2724 /// # fn main() {
2725 /// use cow_hashmap::CowHashMap as HashMap;
2726 /// use std::sync::Arc;
2727 ///
2728 /// let mut map: HashMap<&str, Option<u32>> = HashMap::new();
2729 /// map.entry("poneyland").or_default();
2730 ///
2731 /// assert_eq!(map.get("poneyland").unwrap(), Arc::new(None));
2732 /// # }
2733 /// ```
2734 #[inline]
2735 pub fn or_default(self) -> Arc<V>
2736 where
2737 K: Hash,
2738 S: BuildHasher,
2739 {
2740 match self {
2741 Occupied(entry) => entry.get(),
2742 Vacant(entry) => entry.insert(Default::default()),
2743 }
2744 }
2745
2746 /// Ensures a value is in the entry by inserting the default value if empty,
2747 /// and returns a mutable reference to the value in the entry.
2748 ///
2749 /// # Examples
2750 ///
2751 /// ```
2752 /// # fn main() {
2753 /// use cow_hashmap::CowHashMap as HashMap;
2754 /// use std::sync::Arc;
2755 ///
2756 /// let mut map: HashMap<&str, Option<u32>> = HashMap::new();
2757 /// map.entry("poneyland").or_default();
2758 ///
2759 /// assert_eq!(map.get("poneyland").unwrap(), Arc::new(None));
2760 /// # }
2761 /// ```
2762 #[inline]
2763 pub fn or_default_mut(self) -> CowValueGuard<V>
2764 where
2765 K: Hash,
2766 S: BuildHasher,
2767 V: Clone,
2768 {
2769 match self {
2770 Occupied(entry) => entry.into_mut(),
2771 Vacant(entry) => entry.insert_mut(Default::default()),
2772 }
2773 }
2774}
2775
2776impl<K: Clone, V: Default, S> LockableEntry<'_, K, V, S> {
2777 /// Ensures a value is in the entry by inserting the default value if empty,
2778 /// and returns a mutable reference to the value in the entry.
2779 ///
2780 /// # Examples
2781 ///
2782 /// ```
2783 /// # fn main() {
2784 /// use cow_hashmap::CowHashMap as HashMap;
2785 /// use std::sync::Arc;
2786 ///
2787 /// let mut map: HashMap<&str, Option<u32>> = HashMap::new();
2788 /// map.entry("poneyland").or_default();
2789 ///
2790 /// assert_eq!(map.get("poneyland").unwrap(), Arc::new(None));
2791 /// # }
2792 /// ```
2793 #[inline]
2794 pub fn or_default(self) -> Arc<V>
2795 where
2796 K: Hash,
2797 S: BuildHasher,
2798 {
2799 self.0.or_default()
2800 }
2801
2802 /// Ensures a value is in the entry by inserting the default value if empty,
2803 /// and returns a mutable reference to the value in the entry.
2804 ///
2805 /// # Examples
2806 ///
2807 /// ```
2808 /// # fn main() {
2809 /// use cow_hashmap::CowHashMap as HashMap;
2810 /// use std::sync::Arc;
2811 ///
2812 /// let mut map: HashMap<&str, Option<u32>> = HashMap::new();
2813 /// map.entry("poneyland").or_default();
2814 ///
2815 /// assert_eq!(map.get("poneyland").unwrap(), Arc::new(None));
2816 /// # }
2817 /// ```
2818 #[inline]
2819 pub fn or_default_mut(self) -> CowValueGuard<V>
2820 where
2821 K: Hash,
2822 S: BuildHasher,
2823 V: Clone,
2824 {
2825 self.0.or_default_mut()
2826 }
2827}
2828
2829impl<K: Clone, V, S> OccupiedEntry<K, V, S> {
2830 /// Gets a reference to the key in the entry.
2831 ///
2832 /// # Examples
2833 ///
2834 /// ```
2835 /// use cow_hashmap::CowHashMap as HashMap;
2836 ///
2837 /// let mut map: HashMap<&str, u32> = HashMap::new();
2838 /// map.entry("poneyland").or_insert(12);
2839 /// assert_eq!(map.entry("poneyland").key(), &"poneyland");
2840 /// ```
2841 #[inline]
2842 pub fn key(&self) -> &K {
2843 self.base.key()
2844 }
2845
2846 /// Take the ownership of the key and value from the map.
2847 ///
2848 /// # Examples
2849 ///
2850 /// ```
2851 /// use cow_hashmap::CowHashMap as HashMap;
2852 /// use cow_hashmap::Entry;
2853 ///
2854 /// let mut map: HashMap<String, u32> = HashMap::new();
2855 /// let key = "ponyland".to_string();
2856 /// map.entry(key.clone()).or_insert(12);
2857 ///
2858 /// if let Entry::Occupied(o) = map.entry(key.clone()) {
2859 /// // We delete the entry from the map.
2860 /// o.remove_entry();
2861 /// }
2862 ///
2863 /// assert_eq!(map.contains_key(&key), false);
2864 /// ```
2865 #[inline]
2866 pub fn remove_entry(self) -> (K, Arc<V>)
2867 where
2868 K: Equivalent<K>,
2869 {
2870 self.base.remove_entry()
2871 }
2872
2873 /// Gets a reference to the value in the entry.
2874 ///
2875 /// # Examples
2876 ///
2877 /// ```
2878 /// use cow_hashmap::CowHashMap as HashMap;
2879 /// use cow_hashmap::Entry;
2880 /// use std::sync::Arc;
2881 ///
2882 /// let mut map: HashMap<String, u32> = HashMap::new();
2883 /// let key = "ponyland".to_string();
2884 /// map.entry(key.clone()).or_insert(12);
2885 ///
2886 /// if let Entry::Occupied(o) = map.entry(key.clone()) {
2887 /// assert_eq!(o.get(), Arc::new(12));
2888 /// }
2889 /// ```
2890 #[inline]
2891 pub fn get(&self) -> Arc<V> {
2892 self.base.get()
2893 }
2894
2895 /// Gets a mutable reference to the value in the entry.
2896 ///
2897 /// If you need a reference to the `OccupiedEntry` which may outlive the
2898 /// destruction of the `Entry` value, see [`into_mut`].
2899 ///
2900 /// [`into_mut`]: Self::into_mut
2901 ///
2902 /// # Examples
2903 ///
2904 /// ```
2905 /// use cow_hashmap::CowHashMap as HashMap;
2906 /// use cow_hashmap::Entry;
2907 /// use std::sync::Arc;
2908 ///
2909 /// let mut map: HashMap<&str, u32> = HashMap::new();
2910 /// map.entry("poneyland").or_insert(12);
2911 ///
2912 /// assert_eq!(map.get("poneyland").unwrap(), Arc::new(12));
2913 /// if let Entry::Occupied(mut o) = map.entry("poneyland") {
2914 /// *o.get_mut() += 10;
2915 /// assert_eq!(*o.get(), 22);
2916 ///
2917 /// // We can use the same Entry multiple times.
2918 /// *o.get_mut() += 2;
2919 /// }
2920 ///
2921 /// assert_eq!(map.get("poneyland").unwrap(), Arc::new(24));
2922 /// ```
2923 #[inline]
2924 pub fn get_mut(&self) -> CowValueGuard<V>
2925 where
2926 V: Clone,
2927 {
2928 self.base.get_mut()
2929 }
2930
2931 /// Converts the `OccupiedEntry` into a mutable reference to the value in the entry
2932 /// with a lifetime bound to the map itself.
2933 ///
2934 /// If you need multiple references to the `OccupiedEntry`, see [`get_mut`].
2935 ///
2936 /// [`get_mut`]: Self::get_mut
2937 ///
2938 /// # Examples
2939 ///
2940 /// ```
2941 /// use cow_hashmap::CowHashMap as HashMap;
2942 /// use cow_hashmap::Entry;
2943 /// use std::sync::Arc;
2944 ///
2945 /// let mut map: HashMap<String, u32> = HashMap::new();
2946 /// let key = "poneyland".to_string();
2947 /// map.entry(key.clone()).or_insert(12);
2948 ///
2949 /// assert_eq!(map.get(&key).unwrap(), Arc::new(12));
2950 /// if let Entry::Occupied(o) = map.entry(key.clone()) {
2951 /// *o.into_mut() += 10;
2952 /// }
2953 ///
2954 /// assert_eq!(map.get(&key).unwrap(), Arc::new(22));
2955 /// ```
2956 #[inline]
2957 pub fn into_mut(self) -> CowValueGuard<V>
2958 where
2959 V: Clone,
2960 {
2961 self.base.into_mut()
2962 }
2963
2964 /// Sets the value of the entry, and returns the entry's old value.
2965 ///
2966 /// # Examples
2967 ///
2968 /// ```
2969 /// use cow_hashmap::CowHashMap as HashMap;
2970 /// use cow_hashmap::Entry;
2971 /// use std::sync::Arc;
2972 ///
2973 /// let mut map: HashMap<&str, u32> = HashMap::new();
2974 /// map.entry("poneyland").or_insert(12);
2975 ///
2976 /// if let Entry::Occupied(mut o) = map.entry("poneyland") {
2977 /// assert_eq!(o.insert(15), Arc::new(12));
2978 /// }
2979 ///
2980 /// assert_eq!(map.get("poneyland").unwrap(), Arc::new(15));
2981 /// ```
2982 #[inline]
2983 pub fn insert(&self, value: V) -> Arc<V> {
2984 self.base.insert(value)
2985 }
2986
2987 /// Takes the value out of the entry, and returns it.
2988 ///
2989 /// # Examples
2990 ///
2991 /// ```
2992 /// use cow_hashmap::CowHashMap as HashMap;
2993 /// use cow_hashmap::Entry;
2994 /// use std::sync::Arc;
2995 ///
2996 /// let mut map: HashMap<String, u32> = HashMap::new();
2997 /// let key = "poneyland".to_string();
2998 /// map.entry(key.clone()).or_insert(12);
2999 ///
3000 /// if let Entry::Occupied(o) = map.entry(key.clone()) {
3001 /// assert_eq!(o.remove(), Arc::new(12));
3002 /// }
3003 ///
3004 /// assert_eq!(map.contains_key(&key), false);
3005 /// ```
3006 #[inline]
3007 pub fn remove(self) -> Arc<V>
3008 where
3009 K: Equivalent<K>,
3010 {
3011 self.base.remove()
3012 }
3013
3014 /// Replaces the entry, returning the old key and value. The new key in the hash map will be
3015 /// the key used to create this entry.
3016 #[inline]
3017 pub fn replace_entry(self, value: V) -> (K, Arc<V>)
3018 where
3019 V: Clone,
3020 {
3021 self.base.replace_entry(value)
3022 }
3023
3024 /// Replaces the entry, returning the old key and value. The new key in the hash map will be
3025 /// the key used to create this entry.
3026 #[inline]
3027 pub fn replace_entry_mut(self, value: V) -> (K, CowValueGuard<V>)
3028 where
3029 V: Clone,
3030 {
3031 self.base.replace_entry_mut(value)
3032 }
3033
3034 /// Replaces the key in the hash map with the key used to create this entry.
3035 /// ```
3036 #[inline]
3037 pub fn replace_key(self) -> K {
3038 self.base.replace_key()
3039 }
3040}
3041
3042impl<K: Clone, V, S> VacantEntry<K, V, S> {
3043 /// Gets a reference to the key that would be used when inserting a value
3044 /// through the `VacantEntry`.
3045 ///
3046 /// # Examples
3047 ///
3048 /// ```
3049 /// use cow_hashmap::CowHashMap as HashMap;
3050 ///
3051 /// let mut map: HashMap<&str, u32> = HashMap::new();
3052 /// assert_eq!(map.entry("poneyland").key(), &"poneyland");
3053 /// ```
3054 #[inline]
3055 pub fn key(&self) -> &K {
3056 self.base.key()
3057 }
3058
3059 /// Take ownership of the key.
3060 ///
3061 /// # Examples
3062 ///
3063 /// ```
3064 /// use cow_hashmap::CowHashMap as HashMap;
3065 /// use cow_hashmap::Entry;
3066 ///
3067 /// let mut map: HashMap<&str, u32> = HashMap::new();
3068 ///
3069 /// if let Entry::Vacant(v) = map.entry("poneyland") {
3070 /// v.into_key();
3071 /// }
3072 /// ```
3073 #[inline]
3074 pub fn into_key(self) -> K {
3075 self.base.into_key()
3076 }
3077
3078 /// Sets the value of the entry with the `VacantEntry`'s key,
3079 /// and returns a mutable reference to it.
3080 ///
3081 /// # Examples
3082 ///
3083 /// ```
3084 /// use cow_hashmap::CowHashMap as HashMap;
3085 /// use cow_hashmap::Entry;
3086 /// use std::sync::Arc;
3087 ///
3088 /// let mut map: HashMap<&str, u32> = HashMap::new();
3089 ///
3090 /// if let Entry::Vacant(o) = map.entry("poneyland") {
3091 /// o.insert(37);
3092 /// }
3093 /// assert_eq!(map.get("poneyland").unwrap(), Arc::new(37));
3094 /// ```
3095 #[inline]
3096 pub fn insert(self, value: V) -> Arc<V>
3097 where
3098 K: Hash,
3099 S: BuildHasher,
3100 {
3101 self.base.insert(value)
3102 }
3103
3104 /// Sets the value of the entry with the `VacantEntry`'s key,
3105 /// and returns a mutable reference to it.
3106 ///
3107 /// # Examples
3108 ///
3109 /// ```
3110 /// use cow_hashmap::CowHashMap as HashMap;
3111 /// use cow_hashmap::Entry;
3112 /// use std::sync::Arc;
3113 ///
3114 /// let mut map: HashMap<&str, u32> = HashMap::new();
3115 ///
3116 /// if let Entry::Vacant(o) = map.entry("poneyland") {
3117 /// o.insert(37);
3118 /// }
3119 /// assert_eq!(map.get("poneyland").unwrap(), Arc::new(37));
3120 /// ```
3121 #[inline]
3122 pub fn insert_mut(self, value: V) -> CowValueGuard<V>
3123 where
3124 K: Hash,
3125 S: BuildHasher,
3126 V: Clone,
3127 {
3128 self.base.insert_mut(value)
3129 }
3130}
3131
3132impl<K: Clone, V, S> FromIterator<(K, V)> for CowHashMap<K, V, S>
3133where
3134 K: Eq + Hash,
3135 S: BuildHasher + Clone + Default,
3136{
3137 fn from_iter<T: IntoIterator<Item = (K, V)>>(iter: T) -> CowHashMap<K, V, S> {
3138 let mut map = CowHashMap::with_hasher(Default::default());
3139 map.extend(iter);
3140 map
3141 }
3142}
3143
3144/// Inserts all new key-values from the iterator and replaces values with existing
3145/// keys with new values returned from the iterator.
3146impl<K: Clone, V, S> Extend<(K, V)> for CowHashMap<K, V, S>
3147where
3148 K: Eq + Hash,
3149 S: BuildHasher + Clone,
3150{
3151 #[inline]
3152 fn extend<T: IntoIterator<Item = (K, V)>>(&mut self, iter: T) {
3153 for (k, v) in iter {
3154 self.shard_mut(&k).insert(k, v);
3155 }
3156 }
3157}
3158
3159impl<'a, K: Clone, V, S> Extend<(&'a K, &'a V)> for CowHashMap<K, V, S>
3160where
3161 K: Eq + Hash,
3162 V: Clone,
3163 S: BuildHasher + Clone,
3164{
3165 #[inline]
3166 fn extend<T: IntoIterator<Item = (&'a K, &'a V)>>(&mut self, iter: T) {
3167 for (k, v) in iter {
3168 self.shard_mut(k).insert(k.clone(), v.clone());
3169 }
3170 }
3171}
3172
3173#[inline]
3174fn map_entry<K: Clone, V, S>(raw: cow_hashbrown::hash_map::Entry<K, V, S>) -> Entry<K, V, S> {
3175 match raw {
3176 cow_hashbrown::hash_map::Entry::Occupied(base) => Entry::Occupied(OccupiedEntry { base }),
3177 cow_hashbrown::hash_map::Entry::Vacant(base) => Entry::Vacant(VacantEntry { base }),
3178 }
3179}