1use super::traits::*;
5use super::*;
6use crate::common::*;
7
8pub use super::WeakWeakHashMap;
9
10#[allow(clippy::exhaustive_enums)]
12pub enum Entry<'a, K: 'a + WeakKey, V: 'a + WeakElement> {
13 Occupied(OccupiedEntry<'a, K, V>),
15 Vacant(VacantEntry<'a, K, V>),
17}
18
19pub struct OccupiedEntry<'a, K: 'a + WeakKey, V: 'a + WeakElement>(
21 inner::OccupiedEntry<'a, inner::WeakK<K>, inner::WeakV<V>>,
22);
23
24pub struct VacantEntry<'a, K: 'a + WeakKey, V: 'a + WeakElement>(
26 inner::VacantEntry<'a, inner::WeakK<K>, inner::WeakV<V>>,
27);
28
29#[derive(Clone, Debug)]
31pub struct Iter<'a, K: 'a, V: 'a>(inner::Iter<'a, inner::WeakK<K>, inner::WeakV<V>>);
32
33impl<'a, K: WeakElement, V: WeakElement> Iterator for Iter<'a, K, V> {
34 type Item = (K::Strong, 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: WeakElement, V: WeakElement> Iterator for Keys<'a, K, V> {
50 type Item = K::Strong;
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: WeakElement, 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::WeakK<K>, inner::WeakV<V>>);
83
84impl<'a, K: WeakElement, V: WeakElement> Iterator for Drain<'a, K, V> {
85 type Item = (K::Strong, 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::WeakK<K>, inner::WeakV<V>>);
98
99impl<K: WeakElement, V: WeakElement> Iterator for IntoIter<K, V> {
100 type Item = (K::Strong, 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::Strong, V::Strong where {K: WeakElement, V:WeakElement});
112universal_hashless_members! {
113 WeakWeakHashMap ("`WeakWeakHashMap", a "map") inner::Table::new {K,V}
114}
115
116impl<K: WeakKey, V: WeakElement, S: BuildHasher> WeakWeakHashMap<K, V, S> {
117 universal_key_independent_members! {"mappings"}
118
119 pub fn entry(&mut self, key: K::Strong) -> Entry<'_, K, V> {
125 match self.0.entry(key) {
126 inner::Entry::Occupied(occupied) => Entry::Occupied(OccupiedEntry(occupied)),
127 inner::Entry::Vacant(vacant) => Entry::Vacant(VacantEntry(vacant)),
128 }
129 }
130
131 pub fn get<Q>(&self, key: &Q) -> Option<V::Strong>
137 where
138 Q: ?Sized + Hash + Eq,
139 K::Key: Borrow<Q>,
140 {
141 Some(self.0.find(key)?.1)
142 }
143
144 pub fn get_key<Q>(&self, key: &Q) -> Option<K::Strong>
148 where
149 Q: ?Sized + Hash + Eq,
150 K::Key: Borrow<Q>,
151 {
152 Some(self.0.find(key)?.0)
153 }
154
155 pub fn get_both<Q>(&self, key: &Q) -> Option<(K::Strong, V::Strong)>
159 where
160 Q: ?Sized + Hash + Eq,
161 K::Key: Borrow<Q>,
162 {
163 self.0.find(key)
164 }
165
166 pub fn contains_key<Q>(&self, key: &Q) -> bool
170 where
171 Q: ?Sized + Hash + Eq,
172 K::Key: Borrow<Q>,
173 {
174 self.0.find(key).is_some()
175 }
176
177 pub fn insert(&mut self, key: K::Strong, value: V::Strong) -> Option<V::Strong> {
183 match self.entry(key) {
184 Entry::Occupied(mut occupied) => Some(occupied.insert(value)),
185 Entry::Vacant(vacant) => {
186 vacant.insert(value);
187 None
188 }
189 }
190 }
191
192 pub fn remove<Q>(&mut self, key: &Q) -> Option<V::Strong>
196 where
197 Q: ?Sized + Hash + Eq,
198 K::Key: Borrow<Q>,
199 {
200 self.0.find_entry(key).map(|occupied| occupied.remove().1)
201 }
202
203 pub fn remove_entry<Q>(&mut self, key: &Q) -> Option<(K::Strong, V::Strong)>
208 where
209 Q: ?Sized + Hash + Eq,
210 K::Key: Borrow<Q>,
211 {
212 Some(self.0.find_entry(key)?.remove())
213 }
214
215 pub fn retain<F>(&mut self, mut f: F)
221 where
222 F: FnMut(K::Strong, V::Strong) -> bool,
223 {
224 self.0.table.retain(|(k, v)| {
227 if let (Some(k), Some(v)) = (k.val.view(), v.val.view()) {
228 f(k, v)
229 } else {
230 false
231 }
232 });
233 }
234
235 pub fn is_submap_with<F, S1, V1>(
244 &self,
245 other: &WeakWeakHashMap<K, V1, S1>,
246 mut value_equal: F,
247 ) -> bool
248 where
249 V1: WeakElement,
250 F: FnMut(V::Strong, V1::Strong) -> bool,
251 S1: BuildHasher,
252 {
253 for (key, value1) in self {
254 if let Some(value2) = K::with_key(&key, |k| other.get(k)) {
255 if !value_equal(value1, value2) {
256 return false;
257 }
258 } else {
259 return false;
260 }
261 }
262
263 true
264 }
265
266 pub fn is_submap<V1, S1>(&self, other: &WeakWeakHashMap<K, V1, S1>) -> bool
272 where
273 V1: WeakElement,
274 V::Strong: PartialEq<V1::Strong>,
275 S1: BuildHasher,
276 {
277 self.is_submap_with(other, |v, v1| v == v1)
278 }
279
280 pub fn domain_is_subset<V1, S1>(&self, other: &WeakWeakHashMap<K, V1, S1>) -> bool
286 where
287 V1: WeakElement,
288 S1: BuildHasher,
289 {
290 self.is_submap_with(other, |_, _| true)
291 }
292}
293
294impl<K, V, V1, S, S1> PartialEq<WeakWeakHashMap<K, V1, S1>> for WeakWeakHashMap<K, V, S>
295where
296 K: WeakKey,
297 V: WeakElement,
298 V1: WeakElement,
299 V::Strong: PartialEq<V1::Strong>,
300 S: BuildHasher,
301 S1: BuildHasher,
302{
303 fn eq(&self, other: &WeakWeakHashMap<K, V1, S1>) -> bool {
304 self.is_submap(other) && other.domain_is_subset(self)
305 }
306}
307
308impl<K: WeakKey, V: WeakElement, S: BuildHasher> Eq for WeakWeakHashMap<K, V, S> where V::Strong: Eq {}
309
310impl<K, V, S> iter::FromIterator<(K::Strong, V::Strong)> for WeakWeakHashMap<K, V, S>
311where
312 K: WeakKey,
313 V: WeakElement,
314 S: BuildHasher + Default,
315{
316 fn from_iter<T: IntoIterator<Item = (K::Strong, V::Strong)>>(iter: T) -> Self {
317 let iter = iter.into_iter();
318 let min_size = iter.size_hint().0;
319 let mut result = WeakWeakHashMap::with_capacity_and_hasher(min_size, Default::default());
320 result.extend(iter);
321 result
322 }
323}
324
325#[cfg(any(test, feature = "std", feature = "ahash"))]
326impl<K: WeakKey, V: WeakElement, const N: usize> From<[(K::Strong, V::Strong); N]>
327 for WeakWeakHashMap<K, V, RandomState>
328{
329 fn from(value: [(K::Strong, V::Strong); N]) -> Self {
334 Self::from_iter(value)
335 }
336}
337
338impl<K, V, S> Extend<(K::Strong, V::Strong)> for WeakWeakHashMap<K, V, S>
339where
340 K: WeakKey,
341 V: WeakElement,
342 S: BuildHasher,
343{
344 fn extend<T: IntoIterator<Item = (K::Strong, V::Strong)>>(&mut self, iter: T) {
345 let iter = iter.into_iter();
346 let min_size = iter.size_hint().0;
347 self.reserve(min_size);
348 for (key, value) in iter {
349 self.insert(key, value);
350 }
351 }
352}
353
354impl<'a, K: WeakKey, V: WeakElement> Entry<'a, K, V> {
355 pub fn or_insert(self, default: V::Strong) -> V::Strong {
361 self.or_insert_with(|| default)
362 }
363
364 pub fn or_insert_with<F: FnOnce() -> V::Strong>(self, default: F) -> V::Strong {
370 match self {
371 Entry::Occupied(occupied) => occupied.get_strong(),
372 Entry::Vacant(vacant) => vacant.insert(default()),
373 }
374 }
375
376 pub fn or_insert_with_key<F>(self, default: F) -> V::Strong
380 where
381 F: FnOnce(&K::Strong) -> V::Strong,
382 {
383 match self {
384 Entry::Occupied(occupied) => occupied.get_strong(),
385 Entry::Vacant(vacant) => {
386 let value = default(vacant.key());
387 vacant.insert(value)
388 }
389 }
390 }
391
392 pub fn key(&self) -> &K::Strong {
396 match *self {
397 Entry::Occupied(ref occupied) => occupied.key(),
398 Entry::Vacant(ref vacant) => vacant.key(),
399 }
400 }
401
402 pub fn insert_entry(self, value: V::Strong) -> OccupiedEntry<'a, K, V> {
406 match self {
407 Entry::Occupied(mut occupied) => {
408 occupied.insert(value);
409 occupied
410 }
411 Entry::Vacant(vacant) => vacant.insert_entry(value),
412 }
413 }
414}
415
416impl<'a, K: WeakKey, V: WeakElement> OccupiedEntry<'a, K, V> {
417 pub fn key(&self) -> &K::Strong {
421 self.0.get().0
422 }
423
424 pub fn remove_entry(self) -> (K::Strong, V::Strong) {
428 self.0.remove()
429 }
430
431 pub fn get(&self) -> &V::Strong {
435 self.0.get().1
436 }
437
438 pub fn get_strong(&self) -> V::Strong {
442 V::clone(self.get())
443 }
444
445 pub fn insert(&mut self, value: V::Strong) -> V::Strong {
451 self.0.insert(value)
452 }
453
454 pub fn remove(self) -> V::Strong {
458 self.remove_entry().1
459 }
460}
461
462impl<'a, K: WeakKey, V: WeakElement> VacantEntry<'a, K, V> {
463 pub fn key(&self) -> &K::Strong {
468 self.0.key()
469 }
470
471 pub fn into_key(self) -> K::Strong {
475 self.0.into_key()
476 }
477
478 pub fn insert(self, value: V::Strong) -> V::Strong {
482 V::clone(self.0.insert(value).get().1)
483 }
484
485 pub fn insert_entry(self, value: V::Strong) -> OccupiedEntry<'a, K, V> {
489 OccupiedEntry(self.0.insert(value))
490 }
491}
492
493impl<K: WeakElement, V: WeakElement, S> Debug for WeakWeakHashMap<K, V, S>
494where
495 K::Strong: Debug,
496 V::Strong: Debug,
497{
498 fn fmt(&self, f: &mut Formatter) -> fmt::Result {
499 f.debug_map().entries(self.iter()).finish()
500 }
501}
502
503debug_for_entry! {where {
504 K: WeakKey,
505 K::Strong: Debug,
506 V: WeakElement,
507 V::Strong: Debug
508}}
509
510impl<K: WeakElement, V: WeakElement, S> IntoIterator for WeakWeakHashMap<K, V, S> {
511 type Item = (K::Strong, V::Strong);
512 type IntoIter = IntoIter<K, V>;
513
514 fn into_iter(self) -> Self::IntoIter {
518 IntoIter(self.0.into_iter())
519 }
520}
521
522impl<'a, K: WeakElement, V: WeakElement, S> IntoIterator for &'a WeakWeakHashMap<K, V, S> {
523 type Item = (K::Strong, V::Strong);
524 type IntoIter = Iter<'a, K, V>;
525
526 fn into_iter(self) -> Self::IntoIter {
530 Iter(self.0.iter())
531 }
532}
533
534impl<K: WeakElement, V: WeakElement, S> WeakWeakHashMap<K, V, S> {
535 pub fn iter(&self) -> Iter<'_, K, V> {
539 self.into_iter()
540 }
541
542 pub fn keys(&self) -> Keys<'_, K, V> {
546 Keys(self.iter())
547 }
548
549 pub fn values(&self) -> Values<'_, K, V> {
553 Values(self.iter())
554 }
555
556 pub fn drain(&mut self) -> Drain<'_, K, V> {
560 Drain(self.0.drain())
561 }
562
563 into_kv_methods! {}
564
565 pub fn extract_if<'a, F>(&'a mut self, mut f: F) -> ExtractIf<'a, K, V, F>
575 where
576 F: FnMut(K::Strong, V::Strong) -> bool + 'a,
577 {
578 ExtractIf {
579 inner: self.0.extract_if(move |e| {
580 if let (Some(k), Some(v)) = (e.0.val.view(), e.1.val.view()) {
581 f(k, v)
582 } else {
583 true
584 }
585 }),
586 _phantom: PhantomData,
587 }
588 }
589}
590
591#[must_use = "iterators do nothing unless consumed; \
593 consider using `retain` instead"]
594pub struct ExtractIf<'a, K: WeakElement, V: WeakElement, F> {
595 inner: inner::ExtractIf<'a, inner::WeakK<K>, inner::WeakV<V>>,
597 _phantom: PhantomData<F>,
599}
600
601impl<'a, K: WeakElement, V: WeakElement, F> Iterator for ExtractIf<'a, K, V, F> {
602 type Item = (K::Strong, V::Strong);
603
604 fn next(&mut self) -> Option<Self::Item> {
605 self.inner.next()
606 }
607 fn size_hint(&self) -> (usize, Option<usize>) {
608 self.inner.size_hint()
609 }
610}
611
612#[cfg(test)]
613mod test {
614 #![cfg_attr(feature = "ahash", allow(deprecated))]
616
617 use super::WeakWeakHashMap;
618 use crate::{
619 compat::{
620 format,
621 rc::{Rc, Weak},
622 Vec,
623 },
624 tests::util::VecDebugAsMap,
625 };
626
627 crate::tests::common::empty_constructor_tests! {WeakWeakHashMap<Weak<u32>, Weak<u32>>}
628
629 #[test]
630 fn debug_map() {
631 let rcs: Vec<Rc<u32>> = (0..20).map(Rc::new).collect();
632 let map: WeakWeakHashMap<Weak<u32>, Weak<u32>> =
633 rcs.iter().map(|n| (n.clone(), n.clone())).collect();
634 let vec: VecDebugAsMap<_, _> = map.iter().collect();
635 assert_eq!(format!("{map:?}"), format!("{vec:?}"));
636 }
637
638 #[test]
639 fn is_submap() {
640 let mut rcs: Vec<Rc<u32>> = (0..50).map(Rc::new).collect();
641 let weakmap: WeakWeakHashMap<Weak<u32>, Weak<u32>> = rcs
642 .iter()
643 .take(25)
644 .map(|n| (n.clone(), n.clone()))
645 .collect();
646 let mut weakmap2 = weakmap.clone();
647
648 assert!(weakmap.is_submap(&weakmap2));
649 assert!(weakmap2.is_submap(&weakmap));
650
651 weakmap2.extend(rcs.iter().skip(25).map(|n| (n.clone(), n.clone())));
652 assert!(weakmap.is_submap(&weakmap2));
653 assert!(!weakmap2.is_submap(&weakmap));
654
655 weakmap2.insert(rcs[0].clone(), rcs[12].clone());
656 assert!(!weakmap.is_submap(&weakmap2));
657 assert!(!weakmap2.is_submap(&weakmap));
658
659 let _ = rcs.remove(0);
660 assert!(weakmap.is_submap(&weakmap2));
661 }
662
663 #[test]
664 fn entry_methods() {
665 let rcs: Vec<Rc<u32>> = (0..5).map(Rc::new).collect();
666 let mut weakmap: WeakWeakHashMap<Weak<u32>, Weak<u32>> =
667 rcs.iter().map(|n| (n.clone(), n.clone())).collect();
668
669 let seven = Rc::new(7);
670 let fourteen = Rc::new(14);
671 let ptr = weakmap.entry(seven.clone()).or_insert(fourteen.clone());
672 assert_eq!(*ptr, 14);
673
674 let twelve = Rc::new(12);
675 let e = weakmap.entry(twelve.clone());
676 if let super::Entry::Vacant(v) = e {
677 let t2 = v.into_key();
678 assert_eq!(*t2, 12);
679 } else {
680 panic!();
681 }
682 assert!(!weakmap.contains_key(&12));
683 }
684
685 #[test]
686 fn or_insert_with() {
687 let rcs: Vec<Rc<u32>> = (0..5).map(Rc::new).collect();
688 let mut weakmap: WeakWeakHashMap<Weak<u32>, Weak<u32>> =
689 rcs.iter().map(|n| (n.clone(), n.clone())).collect();
690 let seven = Rc::new(7);
691 let eight = Rc::new(8);
692 let fourteen = Rc::new(14);
693 let sixteen = Rc::new(16);
694
695 let ptr: Rc<u32> = weakmap
697 .entry(seven.clone())
698 .or_insert_with(|| fourteen.clone());
699 assert_eq!(*ptr, 14);
700 let ptr: Rc<u32> = weakmap.entry(eight.clone()).or_insert_with_key(|k| {
701 assert_eq!(**k, 8);
702 sixteen.clone()
703 });
704 assert_eq!(*ptr, 16);
705
706 let one = Rc::new(1);
708 let ptr: Rc<u32> = weakmap
709 .entry(one.clone())
710 .or_insert_with(|| fourteen.clone());
711
712 assert_eq!(*ptr, 1);
713 let ptr: Rc<u32> = weakmap.entry(one.clone()).or_insert_with_key(|k| {
714 assert_eq!(**k, 8);
715 sixteen.clone()
716 });
717 assert_eq!(*ptr, 1);
718 }
719
720 #[test]
721 fn entry_insert_entry() {
722 let rcs: Vec<Rc<u32>> = (0..5).map(Rc::new).collect();
723 let mut weakmap: WeakWeakHashMap<Weak<u32>, Weak<u32>> =
724 rcs.iter().map(|n| (n.clone(), n.clone())).collect();
725
726 let one = Rc::new(1);
727 let ten = Rc::new(10);
728 let n1001 = Rc::new(1001);
729 let n1010 = Rc::new(1010);
730
731 let e1: super::OccupiedEntry<'_, Weak<u32>, Weak<u32>> =
732 weakmap.entry(one.clone()).insert_entry(n1001.clone());
733 assert_eq!(e1.key(), &one);
734 assert_eq!(e1.get(), &n1001);
735
736 let e2: super::OccupiedEntry<'_, Weak<u32>, Weak<u32>> =
737 weakmap.entry(ten.clone()).insert_entry(n1010.clone());
738 assert_eq!(e2.key(), &ten);
739 assert_eq!(e2.get(), &n1010);
740
741 assert_eq!(weakmap.get(&1), Some(n1001));
742 assert_eq!(weakmap.get(&10), Some(n1010));
743 }
744
745 #[test]
746 fn vacant_insert_entry() {
747 let mut weakmap: WeakWeakHashMap<Weak<u32>, Weak<u32>> = Default::default();
748 let five = Rc::new(5);
749 let n500 = Rc::new(500);
750
751 let super::Entry::Vacant(e) = weakmap.entry(five.clone()) else {
752 panic!("Not vacant");
753 };
754 let e: super::OccupiedEntry<'_, Weak<u32>, Weak<u32>> = e.insert_entry(n500.clone());
755 assert_eq!(e.get(), &n500);
756 }
757}