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
304impl<K: Eq + Hash, V: WeakElement, const N: usize> From<[(K, V::Strong); N]>
305 for WeakValueHashMap<K, V, RandomState>
306{
307 fn from(value: [(K, V::Strong); N]) -> Self {
312 Self::from_iter(value)
313 }
314}
315
316impl<K, V, S> Extend<(K, V::Strong)> for WeakValueHashMap<K, V, S>
317where
318 K: Eq + Hash,
319 V: WeakElement,
320 S: BuildHasher,
321{
322 fn extend<T: IntoIterator<Item = (K, V::Strong)>>(&mut self, iter: T) {
323 let iter = iter.into_iter();
324 let min_size = iter.size_hint().0;
325 self.reserve(min_size);
326
327 for (key, value) in iter {
328 self.insert(key, value);
329 }
330 }
331}
332
333impl<'a, K, V, S> Extend<(&'a K, &'a V::Strong)> for WeakValueHashMap<K, V, S>
334where
335 K: 'a + Eq + Hash + Clone,
336 V: 'a + WeakElement,
337 V::Strong: Clone,
338 S: BuildHasher,
339{
340 fn extend<T: IntoIterator<Item = (&'a K, &'a V::Strong)>>(&mut self, iter: T) {
341 let iter = iter.into_iter();
342 let min_size = iter.size_hint().0;
343 self.reserve(min_size);
344
345 for (key, value) in iter {
346 self.insert(key.clone(), value.clone());
347 }
348 }
349}
350
351impl<'a, K, V: WeakElement> Entry<'a, K, V> {
352 pub fn or_insert(self, default: V::Strong) -> V::Strong {
357 self.or_insert_with(|| default)
358 }
359
360 pub fn or_insert_with<F: FnOnce() -> V::Strong>(self, default: F) -> V::Strong {
366 match self {
367 Entry::Occupied(occupied) => occupied.get_strong(),
368 Entry::Vacant(vacant) => vacant.insert(default()),
369 }
370 }
371
372 pub fn or_insert_with_key<F>(self, default: F) -> V::Strong
376 where
377 F: FnOnce(&K) -> V::Strong,
378 {
379 match self {
380 Entry::Occupied(occupied) => occupied.get_strong(),
381 Entry::Vacant(vacant) => {
382 let value = default(vacant.key());
383 vacant.insert(value)
384 }
385 }
386 }
387
388 pub fn key(&self) -> &K {
392 match *self {
393 Entry::Occupied(ref occupied) => occupied.key(),
394 Entry::Vacant(ref vacant) => vacant.key(),
395 }
396 }
397
398 pub fn insert_entry(self, value: V::Strong) -> OccupiedEntry<'a, K, V> {
402 match self {
403 Entry::Occupied(mut occupied) => {
404 occupied.insert(value);
405 occupied
406 }
407 Entry::Vacant(vacant) => vacant.insert_entry(value),
408 }
409 }
410}
411
412impl<'a, K, V: WeakElement> OccupiedEntry<'a, K, V> {
413 pub fn key(&self) -> &K {
417 self.0.get().0
418 }
419
420 pub fn remove_entry(self) -> (K, V::Strong) {
424 self.0.remove()
425 }
426
427 pub fn get(&self) -> &V::Strong {
431 self.0.get().1
432 }
433
434 pub fn get_strong(&self) -> V::Strong {
438 V::clone(self.get())
439 }
440
441 pub fn insert(&mut self, value: V::Strong) -> V::Strong {
445 self.0.insert(value)
446 }
447
448 pub fn remove(self) -> V::Strong {
452 self.remove_entry().1
453 }
454}
455
456impl<'a, K, V: WeakElement> VacantEntry<'a, K, V> {
457 pub fn key(&self) -> &K {
462 self.0.key()
463 }
464
465 pub fn into_key(self) -> K {
469 self.0.into_key()
470 }
471
472 pub fn insert(self, value: V::Strong) -> V::Strong {
476 let occ = self.0.insert(value);
477 V::clone(occ.get().1)
478 }
479
480 pub fn insert_entry(self, value: V::Strong) -> OccupiedEntry<'a, K, V> {
484 OccupiedEntry(self.0.insert(value))
485 }
486}
487
488impl<K: Debug, V: WeakElement, S> Debug for WeakValueHashMap<K, V, S>
489where
490 V::Strong: Debug,
491{
492 fn fmt(&self, f: &mut Formatter) -> fmt::Result {
493 f.debug_map().entries(self.iter()).finish()
494 }
495}
496
497debug_for_entry! {where {
498 K: Debug,
499 V: WeakElement,
500 V::Strong: Debug
501}}
502
503impl<K, V: WeakElement, S> IntoIterator for WeakValueHashMap<K, V, S> {
504 type Item = (K, V::Strong);
505 type IntoIter = IntoIter<K, V>;
506
507 fn into_iter(self) -> Self::IntoIter {
511 IntoIter(self.0.into_iter())
512 }
513}
514
515impl<'a, K, V: WeakElement, S> IntoIterator for &'a WeakValueHashMap<K, V, S> {
516 type Item = (&'a K, V::Strong);
517 type IntoIter = Iter<'a, K, V>;
518
519 fn into_iter(self) -> Self::IntoIter {
523 Iter(self.0.iter())
524 }
525}
526
527impl<K, V: WeakElement, S> WeakValueHashMap<K, V, S> {
528 pub fn iter(&self) -> Iter<'_, K, V> {
532 self.into_iter()
533 }
534
535 pub fn keys(&self) -> Keys<'_, K, V> {
539 Keys(self.iter())
540 }
541
542 pub fn values(&self) -> Values<'_, K, V> {
546 Values(self.iter())
547 }
548
549 pub fn drain(&mut self) -> Drain<'_, K, V> {
553 Drain(self.0.drain())
554 }
555
556 into_kv_methods! {}
557
558 pub fn extract_if<'a, F>(&'a mut self, mut f: F) -> ExtractIf<'a, K, V, F>
568 where
569 F: FnMut(&K, V::Strong) -> bool + 'a,
570 {
571 ExtractIf {
572 inner: self.0.extract_if(move |e| {
573 if let Some(v) = e.1.val.view() {
574 f(&e.0.val, v)
575 } else {
576 true
577 }
578 }),
579 _phantom: PhantomData,
580 }
581 }
582}
583
584pub struct ExtractIf<'a, K, V: WeakElement, F> {
586 inner: inner::ExtractIf<'a, inner::Owned<K>, inner::WeakV<V>>,
588 _phantom: PhantomData<F>,
590}
591
592impl<'a, K, V: WeakElement, F> Iterator for ExtractIf<'a, K, V, F> {
593 type Item = (K, V::Strong);
594
595 fn next(&mut self) -> Option<Self::Item> {
596 self.inner.next()
597 }
598 fn size_hint(&self) -> (usize, Option<usize>) {
599 self.inner.size_hint()
600 }
601}
602
603#[cfg(test)]
604mod test {
605 use super::WeakValueHashMap;
606 use crate::{
607 compat::{
608 format,
609 rc::{Rc, Weak},
610 Vec,
611 },
612 tests::util::VecDebugAsMap,
613 };
614
615 crate::tests::common::empty_constructor_tests! {WeakValueHashMap<u32, Weak<u32>>}
616
617 #[test]
618 fn debug_map() {
619 let rcs: Vec<Rc<u32>> = (0..20).map(Rc::new).collect();
620 let map: WeakValueHashMap<u32, Weak<u32>> =
621 rcs.iter().map(|n| (**n * 7, n.clone())).collect();
622 let vec: VecDebugAsMap<_, _> = map.iter().collect();
623 assert_eq!(format!("{map:?}"), format!("{vec:?}"));
624 }
625
626 #[test]
627 fn is_submap() {
628 let mut rcs: Vec<Rc<u32>> = (0..50).map(Rc::new).collect();
629 let weakmap: WeakValueHashMap<u32, Weak<u32>> =
630 rcs.iter().take(25).map(|n| (**n, n.clone())).collect();
631 let mut weakmap2 = weakmap.clone();
632
633 assert!(weakmap.is_submap(&weakmap2));
634 assert!(weakmap2.is_submap(&weakmap));
635
636 weakmap2.extend(rcs.iter().skip(25).map(|n| (**n, n.clone())));
637 assert!(weakmap.is_submap(&weakmap2));
638 assert!(!weakmap2.is_submap(&weakmap));
639
640 weakmap2.insert(0, rcs[12].clone());
641 assert!(!weakmap.is_submap(&weakmap2));
642 assert!(!weakmap2.is_submap(&weakmap));
643
644 let _ = rcs.remove(0);
645 assert!(weakmap.is_submap(&weakmap2));
646 }
647
648 #[test]
649 fn entry_methods() {
650 let rcs: Vec<Rc<u32>> = (0..5).map(Rc::new).collect();
651 let mut weakmap: WeakValueHashMap<u32, Weak<u32>> =
652 rcs.iter().map(|n| (**n, n.clone())).collect();
653
654 let fourteen = Rc::new(14);
655
656 let ptr = weakmap.entry(7).or_insert(fourteen.clone());
657 assert_eq!(*ptr, 14);
658
659 assert_eq!(weakmap.get(&7), Some(fourteen.clone()));
660
661 let e = weakmap.entry(12);
662 if let super::Entry::Vacant(v) = e {
663 let t2 = v.into_key();
664 assert_eq!(t2, 12);
665 } else {
666 panic!();
667 }
668 assert!(!weakmap.contains_key(&12));
669 }
670
671 #[test]
672 fn or_insert_with() {
673 let rcs: Vec<Rc<u32>> = (0..5).map(Rc::new).collect();
674 let mut weakmap: WeakValueHashMap<u32, Weak<u32>> =
675 rcs.iter().map(|n| (**n, n.clone())).collect();
676 let fourteen = Rc::new(14);
677 let sixteen = Rc::new(16);
678
679 let ptr: Rc<u32> = weakmap.entry(7).or_insert_with(|| fourteen.clone());
681 assert_eq!(*ptr, 14);
682 let ptr: Rc<u32> = weakmap.entry(8).or_insert_with_key(|k| {
683 assert_eq!(*k, 8);
684 sixteen.clone()
685 });
686 assert_eq!(*ptr, 16);
687
688 let ptr: Rc<u32> = weakmap.entry(1).or_insert_with(|| fourteen.clone());
690 assert_eq!(*ptr, 1);
691 let ptr: Rc<u32> = weakmap.entry(1).or_insert_with_key(|k| {
692 assert_eq!(*k, 1);
693 sixteen.clone()
694 });
695 assert_eq!(*ptr, 1);
696 }
697
698 #[test]
699 fn entry_insert_entry() {
700 let rcs: Vec<Rc<u32>> = (0..5).map(Rc::new).collect();
701 let mut weakmap: WeakValueHashMap<u32, Weak<u32>> =
702 rcs.iter().map(|n| (**n, n.clone())).collect();
703 let n1001 = Rc::new(1001);
704 let n1010 = Rc::new(1010);
705
706 let e1: super::OccupiedEntry<'_, u32, Weak<u32>> =
707 weakmap.entry(1).insert_entry(n1001.clone());
708 assert_eq!(e1.key(), &1);
709 assert_eq!(e1.get(), &n1001);
710
711 let e2: super::OccupiedEntry<'_, u32, Weak<u32>> =
712 weakmap.entry(10).insert_entry(n1010.clone());
713 assert_eq!(e2.key(), &10);
714 assert_eq!(e2.get(), &n1010);
715
716 assert_eq!(weakmap.get(&1), Some(n1001));
717 assert_eq!(weakmap.get(&10), Some(n1010));
718 }
719
720 #[test]
721 fn vacant_insert_entry() {
722 let mut weakmap: WeakValueHashMap<u32, Weak<u32>> = Default::default();
723 let n500 = Rc::new(500);
724
725 let super::Entry::Vacant(e) = weakmap.entry(5) else {
726 panic!("Not vacant");
727 };
728 let e: super::OccupiedEntry<'_, u32, Weak<u32>> = e.insert_entry(n500.clone());
729 assert_eq!(e.get(), &n500);
730 }
731}