1use crate::common::*;
4
5use super::traits::*;
6use super::*;
7
8pub use super::WeakValueHashMap;
9
10#[allow(clippy::exhaustive_enums)]
12pub enum Entry<'a, K: 'a, V: 'a + WeakElement> {
13 Occupied(OccupiedEntry<'a, K, V>),
15 Vacant(VacantEntry<'a, K, V>),
17}
18
19pub struct OccupiedEntry<'a, K: 'a, V: 'a + WeakElement>(
21 inner::OccupiedEntry<'a, inner::Owned<K>, inner::WeakV<V>>,
22);
23
24pub struct VacantEntry<'a, K: 'a, V: 'a + WeakElement>(
26 inner::VacantEntry<'a, inner::Owned<K>, inner::WeakV<V>>,
27);
28
29#[derive(Clone, Debug)]
31pub struct Iter<'a, K: 'a, V: 'a>(inner::Iter<'a, inner::Owned<K>, inner::WeakV<V>>);
32
33impl<'a, K, V: WeakElement> Iterator for Iter<'a, K, V> {
34 type Item = (&'a K, V::Strong);
35
36 fn next(&mut self) -> Option<Self::Item> {
37 self.0.next()
38 }
39
40 fn size_hint(&self) -> (usize, Option<usize>) {
41 self.0.size_hint()
42 }
43}
44
45#[derive(Clone, Debug)]
47pub struct Keys<'a, K: 'a, V: 'a>(Iter<'a, K, V>);
48
49impl<'a, K, V: WeakElement> Iterator for Keys<'a, K, V> {
50 type Item = &'a K;
51
52 fn next(&mut self) -> Option<Self::Item> {
53 self.0.next().map(|(k, _)| k)
54 }
55
56 fn size_hint(&self) -> (usize, Option<usize>) {
57 self.0.size_hint()
58 }
59}
60
61#[derive(Clone, Debug)]
63pub struct Values<'a, K: 'a, V: 'a>(Iter<'a, K, V>);
64
65impl<'a, K, V: WeakElement> Iterator for Values<'a, K, V> {
66 type Item = V::Strong;
67
68 fn next(&mut self) -> Option<Self::Item> {
69 self.0.next().map(|(_, v)| v)
70 }
71
72 fn size_hint(&self) -> (usize, Option<usize>) {
73 self.0.size_hint()
74 }
75}
76
77#[derive(Debug)]
78pub struct Drain<'a, K: 'a, V: 'a>(inner::Drain<'a, inner::Owned<K>, inner::WeakV<V>>);
83
84impl<'a, K, V: WeakElement> Iterator for Drain<'a, K, V> {
85 type Item = (K, V::Strong);
86
87 fn next(&mut self) -> Option<Self::Item> {
88 self.0.next()
89 }
90
91 fn size_hint(&self) -> (usize, Option<usize>) {
92 self.0.size_hint()
93 }
94}
95
96pub struct IntoIter<K, V>(inner::IntoIter<inner::Owned<K>, inner::WeakV<V>>);
98
99impl<K, V: WeakElement> Iterator for IntoIter<K, V> {
100 type Item = (K, V::Strong);
101
102 fn next(&mut self) -> Option<Self::Item> {
103 self.0.next()
104 }
105
106 fn size_hint(&self) -> (usize, Option<usize>) {
107 self.0.size_hint()
108 }
109}
110
111into_kv_types!(K, V::Strong where {V: WeakElement});
112universal_hashless_members! {
113 WeakValueHashMap ("`WeakValueHashMap`", a "map") inner::Table::new {K,V}
114}
115
116impl<K: Eq + Hash, V: WeakElement, S: BuildHasher> WeakValueHashMap<K, V, S> {
117 universal_key_independent_members! {"mappings"}
118
119 pub fn entry(&mut self, key: K) -> Entry<'_, K, V> {
123 match self.0.entry(key) {
124 inner::Entry::Occupied(occupied) => Entry::Occupied(OccupiedEntry(occupied)),
125 inner::Entry::Vacant(vacant) => Entry::Vacant(VacantEntry(vacant)),
126 }
127 }
128
129 pub fn get<Q>(&self, key: &Q) -> Option<V::Strong>
135 where
136 Q: ?Sized + Hash + Eq,
137 K: Borrow<Q>,
138 {
139 Some(self.0.find(key)?.1)
140 }
141
142 pub fn contains_key<Q>(&self, key: &Q) -> bool
146 where
147 Q: ?Sized + Hash + Eq,
148 K: Borrow<Q>,
149 {
150 self.0.find(key).is_some()
151 }
152
153 pub fn insert(&mut self, key: K, value: V::Strong) -> Option<V::Strong> {
159 match self.entry(key) {
160 Entry::Occupied(mut occupied) => Some(occupied.insert(value)),
161 Entry::Vacant(vacant) => {
162 vacant.insert(value);
163 None
164 }
165 }
166 }
167
168 pub fn remove<Q>(&mut self, key: &Q) -> Option<V::Strong>
172 where
173 Q: ?Sized + Hash + Eq,
174 K: Borrow<Q>,
175 {
176 self.0.find_entry(key).map(|occupied| occupied.remove().1)
177 }
178
179 pub fn remove_entry<Q>(&mut self, key: &Q) -> Option<(K, V::Strong)>
184 where
185 Q: ?Sized + Hash + Eq,
186 K: Borrow<Q>,
187 {
188 Some(self.0.find_entry(key)?.remove())
189 }
190
191 pub fn retain<F>(&mut self, mut f: F)
197 where
198 F: FnMut(&K, V::Strong) -> bool,
199 {
200 self.0.table.retain(|(k, v)| {
203 if let Some(v) = v.val.view() {
204 f(&k.val, v)
205 } else {
206 false
207 }
208 });
209 }
210
211 pub fn is_submap_with<F, S1, V1>(
220 &self,
221 other: &WeakValueHashMap<K, V1, S1>,
222 mut value_equal: F,
223 ) -> bool
224 where
225 V1: WeakElement,
226 F: FnMut(V::Strong, V1::Strong) -> bool,
227 S1: BuildHasher,
228 {
229 for (key, value1) in self {
230 if let Some(value2) = other.get(key) {
231 if !value_equal(value1, value2) {
232 return false;
233 }
234 } else {
235 return false;
236 }
237 }
238
239 true
240 }
241
242 pub fn is_submap<V1, S1>(&self, other: &WeakValueHashMap<K, V1, S1>) -> bool
248 where
249 V1: WeakElement,
250 V::Strong: PartialEq<V1::Strong>,
251 S1: BuildHasher,
252 {
253 self.is_submap_with(other, |v, v1| v == v1)
254 }
255
256 pub fn domain_is_subset<V1, S1>(&self, other: &WeakValueHashMap<K, V1, S1>) -> bool
262 where
263 V1: WeakElement,
264 S1: BuildHasher,
265 {
266 self.is_submap_with(other, |_, _| true)
267 }
268}
269
270impl<K, V, V1, S, S1> PartialEq<WeakValueHashMap<K, V1, S1>> for WeakValueHashMap<K, V, S>
271where
272 K: Eq + Hash,
273 V: WeakElement,
274 V1: WeakElement,
275 V::Strong: PartialEq<V1::Strong>,
276 S: BuildHasher,
277 S1: BuildHasher,
278{
279 fn eq(&self, other: &WeakValueHashMap<K, V1, S1>) -> bool {
280 self.is_submap(other) && other.domain_is_subset(self)
281 }
282}
283
284impl<K: Eq + Hash, V: WeakElement, S: BuildHasher> Eq for WeakValueHashMap<K, V, S> where
285 V::Strong: Eq
286{
287}
288
289impl<K, V, S> iter::FromIterator<(K, V::Strong)> for WeakValueHashMap<K, V, S>
290where
291 K: Eq + Hash,
292 V: WeakElement,
293 S: BuildHasher + Default,
294{
295 fn from_iter<T: IntoIterator<Item = (K, V::Strong)>>(iter: T) -> Self {
296 let iter = iter.into_iter();
297 let min_size = iter.size_hint().0;
298 let mut result = WeakValueHashMap::with_capacity_and_hasher(min_size, Default::default());
299 result.extend(iter);
300 result
301 }
302}
303
304#[cfg(any(test, feature = "std", feature = "ahash"))]
305impl<K: Eq + Hash, V: WeakElement, const N: usize> From<[(K, V::Strong); N]>
306 for WeakValueHashMap<K, V, RandomState>
307{
308 fn from(value: [(K, V::Strong); N]) -> Self {
313 Self::from_iter(value)
314 }
315}
316
317impl<K, V, S> Extend<(K, V::Strong)> for WeakValueHashMap<K, V, S>
318where
319 K: Eq + Hash,
320 V: WeakElement,
321 S: BuildHasher,
322{
323 fn extend<T: IntoIterator<Item = (K, V::Strong)>>(&mut self, iter: T) {
324 let iter = iter.into_iter();
325 let min_size = iter.size_hint().0;
326 self.reserve(min_size);
327
328 for (key, value) in iter {
329 self.insert(key, value);
330 }
331 }
332}
333
334impl<'a, K, V, S> Extend<(&'a K, &'a V::Strong)> for WeakValueHashMap<K, V, S>
335where
336 K: 'a + Eq + Hash + Clone,
337 V: 'a + WeakElement,
338 V::Strong: Clone,
339 S: BuildHasher,
340{
341 fn extend<T: IntoIterator<Item = (&'a K, &'a V::Strong)>>(&mut self, iter: T) {
342 let iter = iter.into_iter();
343 let min_size = iter.size_hint().0;
344 self.reserve(min_size);
345
346 for (key, value) in iter {
347 self.insert(key.clone(), value.clone());
348 }
349 }
350}
351
352impl<'a, K, V: WeakElement> Entry<'a, K, V> {
353 pub fn or_insert(self, default: V::Strong) -> V::Strong {
358 self.or_insert_with(|| default)
359 }
360
361 pub fn or_insert_with<F: FnOnce() -> V::Strong>(self, default: F) -> V::Strong {
367 match self {
368 Entry::Occupied(occupied) => occupied.get_strong(),
369 Entry::Vacant(vacant) => vacant.insert(default()),
370 }
371 }
372
373 pub fn or_insert_with_key<F>(self, default: F) -> V::Strong
377 where
378 F: FnOnce(&K) -> V::Strong,
379 {
380 match self {
381 Entry::Occupied(occupied) => occupied.get_strong(),
382 Entry::Vacant(vacant) => {
383 let value = default(vacant.key());
384 vacant.insert(value)
385 }
386 }
387 }
388
389 pub fn key(&self) -> &K {
393 match *self {
394 Entry::Occupied(ref occupied) => occupied.key(),
395 Entry::Vacant(ref vacant) => vacant.key(),
396 }
397 }
398
399 pub fn insert_entry(self, value: V::Strong) -> OccupiedEntry<'a, K, V> {
403 match self {
404 Entry::Occupied(mut occupied) => {
405 occupied.insert(value);
406 occupied
407 }
408 Entry::Vacant(vacant) => vacant.insert_entry(value),
409 }
410 }
411}
412
413impl<'a, K, V: WeakElement> OccupiedEntry<'a, K, V> {
414 pub fn key(&self) -> &K {
418 self.0.get().0
419 }
420
421 pub fn remove_entry(self) -> (K, V::Strong) {
425 self.0.remove()
426 }
427
428 pub fn get(&self) -> &V::Strong {
432 self.0.get().1
433 }
434
435 pub fn get_strong(&self) -> V::Strong {
439 V::clone(self.get())
440 }
441
442 pub fn insert(&mut self, value: V::Strong) -> V::Strong {
446 self.0.insert(value)
447 }
448
449 pub fn remove(self) -> V::Strong {
453 self.remove_entry().1
454 }
455}
456
457impl<'a, K, V: WeakElement> VacantEntry<'a, K, V> {
458 pub fn key(&self) -> &K {
463 self.0.key()
464 }
465
466 pub fn into_key(self) -> K {
470 self.0.into_key()
471 }
472
473 pub fn insert(self, value: V::Strong) -> V::Strong {
477 let occ = self.0.insert(value);
478 V::clone(occ.get().1)
479 }
480
481 pub fn insert_entry(self, value: V::Strong) -> OccupiedEntry<'a, K, V> {
485 OccupiedEntry(self.0.insert(value))
486 }
487}
488
489impl<K: Debug, V: WeakElement, S> Debug for WeakValueHashMap<K, V, S>
490where
491 V::Strong: Debug,
492{
493 fn fmt(&self, f: &mut Formatter) -> fmt::Result {
494 f.debug_map().entries(self.iter()).finish()
495 }
496}
497
498debug_for_entry! {where {
499 K: Debug,
500 V: WeakElement,
501 V::Strong: Debug
502}}
503
504impl<K, V: WeakElement, S> IntoIterator for WeakValueHashMap<K, V, S> {
505 type Item = (K, V::Strong);
506 type IntoIter = IntoIter<K, V>;
507
508 fn into_iter(self) -> Self::IntoIter {
512 IntoIter(self.0.into_iter())
513 }
514}
515
516impl<'a, K, V: WeakElement, S> IntoIterator for &'a WeakValueHashMap<K, V, S> {
517 type Item = (&'a K, V::Strong);
518 type IntoIter = Iter<'a, K, V>;
519
520 fn into_iter(self) -> Self::IntoIter {
524 Iter(self.0.iter())
525 }
526}
527
528impl<K, V: WeakElement, S> WeakValueHashMap<K, V, S> {
529 pub fn iter(&self) -> Iter<'_, K, V> {
533 self.into_iter()
534 }
535
536 pub fn keys(&self) -> Keys<'_, K, V> {
540 Keys(self.iter())
541 }
542
543 pub fn values(&self) -> Values<'_, K, V> {
547 Values(self.iter())
548 }
549
550 pub fn drain(&mut self) -> Drain<'_, K, V> {
554 Drain(self.0.drain())
555 }
556
557 into_kv_methods! {}
558
559 pub fn extract_if<'a, F>(&'a mut self, mut f: F) -> ExtractIf<'a, K, V, F>
569 where
570 F: FnMut(&K, V::Strong) -> bool + 'a,
571 {
572 ExtractIf {
573 inner: self.0.extract_if(move |e| {
574 if let Some(v) = e.1.val.view() {
575 f(&e.0.val, v)
576 } else {
577 true
578 }
579 }),
580 _phantom: PhantomData,
581 }
582 }
583}
584
585#[must_use = "iterators do nothing unless consumed; \
587 consider using `retain` instead"]
588pub struct ExtractIf<'a, K, V: WeakElement, F> {
589 inner: inner::ExtractIf<'a, inner::Owned<K>, inner::WeakV<V>>,
591 _phantom: PhantomData<F>,
593}
594
595impl<'a, K, V: WeakElement, F> Iterator for ExtractIf<'a, K, V, F> {
596 type Item = (K, V::Strong);
597
598 fn next(&mut self) -> Option<Self::Item> {
599 self.inner.next()
600 }
601 fn size_hint(&self) -> (usize, Option<usize>) {
602 self.inner.size_hint()
603 }
604}
605
606#[cfg(test)]
607mod test {
608 #![cfg_attr(feature = "ahash", allow(deprecated))]
610
611 use super::WeakValueHashMap;
612 use crate::{
613 compat::{
614 format,
615 rc::{Rc, Weak},
616 Vec,
617 },
618 tests::util::VecDebugAsMap,
619 };
620
621 crate::tests::common::empty_constructor_tests! {WeakValueHashMap<u32, Weak<u32>>}
622
623 #[test]
624 fn debug_map() {
625 let rcs: Vec<Rc<u32>> = (0..20).map(Rc::new).collect();
626 let map: WeakValueHashMap<u32, Weak<u32>> =
627 rcs.iter().map(|n| (**n * 7, n.clone())).collect();
628 let vec: VecDebugAsMap<_, _> = map.iter().collect();
629 assert_eq!(format!("{map:?}"), format!("{vec:?}"));
630 }
631
632 #[test]
633 fn is_submap() {
634 let mut rcs: Vec<Rc<u32>> = (0..50).map(Rc::new).collect();
635 let weakmap: WeakValueHashMap<u32, Weak<u32>> =
636 rcs.iter().take(25).map(|n| (**n, n.clone())).collect();
637 let mut weakmap2 = weakmap.clone();
638
639 assert!(weakmap.is_submap(&weakmap2));
640 assert!(weakmap2.is_submap(&weakmap));
641
642 weakmap2.extend(rcs.iter().skip(25).map(|n| (**n, n.clone())));
643 assert!(weakmap.is_submap(&weakmap2));
644 assert!(!weakmap2.is_submap(&weakmap));
645
646 weakmap2.insert(0, rcs[12].clone());
647 assert!(!weakmap.is_submap(&weakmap2));
648 assert!(!weakmap2.is_submap(&weakmap));
649
650 let _ = rcs.remove(0);
651 assert!(weakmap.is_submap(&weakmap2));
652 }
653
654 #[test]
655 fn entry_methods() {
656 let rcs: Vec<Rc<u32>> = (0..5).map(Rc::new).collect();
657 let mut weakmap: WeakValueHashMap<u32, Weak<u32>> =
658 rcs.iter().map(|n| (**n, n.clone())).collect();
659
660 let fourteen = Rc::new(14);
661
662 let ptr = weakmap.entry(7).or_insert(fourteen.clone());
663 assert_eq!(*ptr, 14);
664
665 assert_eq!(weakmap.get(&7), Some(fourteen.clone()));
666
667 let e = weakmap.entry(12);
668 if let super::Entry::Vacant(v) = e {
669 let t2 = v.into_key();
670 assert_eq!(t2, 12);
671 } else {
672 panic!();
673 }
674 assert!(!weakmap.contains_key(&12));
675 }
676
677 #[test]
678 fn or_insert_with() {
679 let rcs: Vec<Rc<u32>> = (0..5).map(Rc::new).collect();
680 let mut weakmap: WeakValueHashMap<u32, Weak<u32>> =
681 rcs.iter().map(|n| (**n, n.clone())).collect();
682 let fourteen = Rc::new(14);
683 let sixteen = Rc::new(16);
684
685 let ptr: Rc<u32> = weakmap.entry(7).or_insert_with(|| fourteen.clone());
687 assert_eq!(*ptr, 14);
688 let ptr: Rc<u32> = weakmap.entry(8).or_insert_with_key(|k| {
689 assert_eq!(*k, 8);
690 sixteen.clone()
691 });
692 assert_eq!(*ptr, 16);
693
694 let ptr: Rc<u32> = weakmap.entry(1).or_insert_with(|| fourteen.clone());
696 assert_eq!(*ptr, 1);
697 let ptr: Rc<u32> = weakmap.entry(1).or_insert_with_key(|k| {
698 assert_eq!(*k, 1);
699 sixteen.clone()
700 });
701 assert_eq!(*ptr, 1);
702 }
703
704 #[test]
705 fn entry_insert_entry() {
706 let rcs: Vec<Rc<u32>> = (0..5).map(Rc::new).collect();
707 let mut weakmap: WeakValueHashMap<u32, Weak<u32>> =
708 rcs.iter().map(|n| (**n, n.clone())).collect();
709 let n1001 = Rc::new(1001);
710 let n1010 = Rc::new(1010);
711
712 let e1: super::OccupiedEntry<'_, u32, Weak<u32>> =
713 weakmap.entry(1).insert_entry(n1001.clone());
714 assert_eq!(e1.key(), &1);
715 assert_eq!(e1.get(), &n1001);
716
717 let e2: super::OccupiedEntry<'_, u32, Weak<u32>> =
718 weakmap.entry(10).insert_entry(n1010.clone());
719 assert_eq!(e2.key(), &10);
720 assert_eq!(e2.get(), &n1010);
721
722 assert_eq!(weakmap.get(&1), Some(n1001));
723 assert_eq!(weakmap.get(&10), Some(n1010));
724 }
725
726 #[test]
727 fn vacant_insert_entry() {
728 let mut weakmap: WeakValueHashMap<u32, Weak<u32>> = Default::default();
729 let n500 = Rc::new(500);
730
731 let super::Entry::Vacant(e) = weakmap.entry(5) else {
732 panic!("Not vacant");
733 };
734 let e: super::OccupiedEntry<'_, u32, Weak<u32>> = e.insert_entry(n500.clone());
735 assert_eq!(e.get(), &n500);
736 }
737}