Skip to main content

weak_table/
weak_value_hash_map.rs

1//! A hash map where the values are held by weak pointers.
2
3use crate::common::*;
4
5use super::traits::*;
6use super::*;
7
8pub use super::WeakValueHashMap;
9
10/// Represents an entry in the table which may be occupied or vacant.
11#[allow(clippy::exhaustive_enums)]
12pub enum Entry<'a, K: 'a, V: 'a + WeakElement> {
13    /// An occupied entry.
14    Occupied(OccupiedEntry<'a, K, V>),
15    /// A vacant entry.
16    Vacant(VacantEntry<'a, K, V>),
17}
18
19/// An occupied entry, which can be removed, modified, or viewed.
20pub struct OccupiedEntry<'a, K: 'a, V: 'a + WeakElement>(
21    inner::OccupiedEntry<'a, inner::Owned<K>, inner::WeakV<V>>,
22);
23
24/// A vacant entry, which can be inserted in or viewed.
25pub struct VacantEntry<'a, K: 'a, V: 'a + WeakElement>(
26    inner::VacantEntry<'a, inner::Owned<K>, inner::WeakV<V>>,
27);
28
29/// An iterator over the keys and values of the weak hash map.
30#[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/// An iterator over the keys of the weak hash map.
46#[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/// An iterator over the values of the weak hash map.
62#[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)]
78/// An iterator that consumes the values of a weak hash map, leaving it empty.
79///
80/// Once this iterator is dropped, all values are removed from the map,
81/// whether the iterator itself was drained or not.
82pub 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
96/// An iterator that consumes a weak hash map, leaving it empty.
97pub 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    /// Gets the requested entry.
120    ///
121    /// expected *O*(1) time; worst-case *O*(*p*) time
122    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    /// Returns a reference to the value corresponding to the key.
130    ///
131    /// Returns `None` if no matching key is found.
132    ///
133    /// expected *O*(1) time; worst-case *O*(*p*) time
134    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    /// Returns true if the map contains the specified key.
143    ///
144    /// expected *O*(1) time; worst-case *O*(*p*) time
145    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    /// Unconditionally inserts the value, returning the old value if already present.
154    ///
155    /// Like `std::collections::HashMap`, this does not replace the key if occupied.
156    ///
157    /// expected *O*(1) time; worst-case *O*(*p*) time
158    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    /// Removes the entry with the given key, if it exists, and returns the value.
169    ///
170    /// expected *O*(1) time; worst-case *O*(*p*) time
171    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    /// Removes the entry with the given key, if it exists, and returns both the
180    /// key and value.
181    ///
182    /// expected *O*(1) time; worst-case *O*(*p*) time
183    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    /// Removes all mappings not satisfying the given predicate.
192    ///
193    /// Also removes any expired mappings.
194    ///
195    /// *O*(*n*) time
196    pub fn retain<F>(&mut self, mut f: F)
197    where
198        F: FnMut(&K, V::Strong) -> bool,
199    {
200        // TODO: It would be better to use a retain method on Table, but I've
201        // run into lifetime issues there. See "TODO retain" in inner/table.rs
202        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    /// Is this map a submap of the other, using the given value comparison.
212    ///
213    /// In particular, all the keys of `self` must be in `other` and the values must compare
214    /// `true` with `value_equal`.
215    ///
216    /// expected *O*(*n*) time; worst-case *O*(*nq*) time (where *n* is
217    /// `self.capacity()` and *q* is the length of the probe sequences
218    /// in `other`)
219    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    /// Is `self` a submap of `other`?
243    ///
244    /// expected *O*(*n*) time; worst-case *O*(*nq*) time (where *n* is
245    /// `self.capacity()` and *q* is the length of the probe sequences
246    /// in `other`)
247    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    /// Are the keys of `self` a subset of the keys of `other`?
257    ///
258    /// expected *O*(*n*) time; worst-case *O*(*nq*) time (where *n* is
259    /// `self.capacity()` and *q* is the length of the probe sequences
260    /// in `other`)
261    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    /// Converts an array of key-value pairs into a map.
309    ///
310    /// If any entries in the array have equal keys,
311    /// all but one of the corresponding values will be dropped.
312    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    /// Ensures a value is in the entry by inserting a default value
354    /// if empty.
355    ///
356    /// *O*(1) time
357    pub fn or_insert(self, default: V::Strong) -> V::Strong {
358        self.or_insert_with(|| default)
359    }
360
361    /// Ensures a value is in the entry by inserting the result of the
362    /// `default` function if empty, and returns a strong reference to
363    /// the value in the entry.
364    ///
365    /// *O*(1) time
366    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    /// Ensures that a value is in the entry by inserting the result of calling the
374    /// `default` function on this entry's key if the function is empty, and
375    /// returns a strong reference to the value in the entry.
376    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    /// Returns a reference to this entry's key.
390    ///
391    /// *O*(1) time
392    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    /// Inserts a value into this entry, and returns an [`OccupiedEntry`].
400    ///
401    /// *O*(1) time
402    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    /// Gets a reference to the key held by the entry.
415    ///
416    /// *O*(1) time
417    pub fn key(&self) -> &K {
418        self.0.get().0
419    }
420
421    /// Takes ownership of the key and value, removing them from the map.
422    ///
423    /// expected *O*(1) time; worst-case *O*(*p*) time
424    pub fn remove_entry(self) -> (K, V::Strong) {
425        self.0.remove()
426    }
427
428    /// Gets a reference to the value in the entry.
429    ///
430    /// *O*(1) time
431    pub fn get(&self) -> &V::Strong {
432        self.0.get().1
433    }
434
435    /// Gets a copy of the strong value reference stored in the entry.
436    ///
437    /// *O*(1) time
438    pub fn get_strong(&self) -> V::Strong {
439        V::clone(self.get())
440    }
441
442    /// Replaces the value in the entry with the given value, returning the old value.
443    ///
444    /// *O*(1) time
445    pub fn insert(&mut self, value: V::Strong) -> V::Strong {
446        self.0.insert(value)
447    }
448
449    /// Removes the entry, returning the value.
450    ///
451    /// expected *O*(1) time; worst-case *O*(*p*) time
452    pub fn remove(self) -> V::Strong {
453        self.remove_entry().1
454    }
455}
456
457impl<'a, K, V: WeakElement> VacantEntry<'a, K, V> {
458    /// Gets a reference to the key that would be used when inserting a
459    /// value through the `VacantEntry`.
460    ///
461    /// *O*(1) time
462    pub fn key(&self) -> &K {
463        self.0.key()
464    }
465
466    /// Returns an owned reference to the key.
467    ///
468    /// *O*(1) time
469    pub fn into_key(self) -> K {
470        self.0.into_key()
471    }
472
473    /// Inserts the value into the map, returning the same value.
474    ///
475    /// *O*(1) time
476    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    /// Inserts the key and value into the map, returning an `OccupiedEntry`.
482    ///
483    /// *O*(1) time
484    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    /// Creates an owning iterator from `self`.
509    ///
510    /// *O*(1) time (and *O*(*n*) time to dispose of the result)
511    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    /// Creates a borrowing iterator from `self`.
521    ///
522    /// *O*(1) time
523    fn into_iter(self) -> Self::IntoIter {
524        Iter(self.0.iter())
525    }
526}
527
528impl<K, V: WeakElement, S> WeakValueHashMap<K, V, S> {
529    /// Gets an iterator over the keys and values.
530    ///
531    /// *O*(1) time
532    pub fn iter(&self) -> Iter<'_, K, V> {
533        self.into_iter()
534    }
535
536    /// Gets an iterator over the keys.
537    ///
538    /// *O*(1) time
539    pub fn keys(&self) -> Keys<'_, K, V> {
540        Keys(self.iter())
541    }
542
543    /// Gets an iterator over the values.
544    ///
545    /// *O*(1) time
546    pub fn values(&self) -> Values<'_, K, V> {
547        Values(self.iter())
548    }
549
550    /// Gets a draining iterator, which removes all the values but retains the storage.
551    ///
552    /// *O*(1) time (and *O*(*n*) time to dispose of the result)
553    pub fn drain(&mut self) -> Drain<'_, K, V> {
554        Drain(self.0.drain())
555    }
556
557    into_kv_methods! {}
558
559    /// Gets an iterator that removes and returns elements matching a given predicate.
560    ///
561    /// Expired elements are also removed.
562    ///
563    /// If this iterator is dropped before it is completed, then no further
564    /// elements are removed.
565    /// (This is in contrast to the behavior of [`drain`](Self::drain)).
566    ///
567    /// *O*(1) time
568    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/// An iterator that removes members that match a given predicate.
586#[must_use = "iterators do nothing unless consumed; \
587    consider using `retain` instead"]
588pub struct ExtractIf<'a, K, V: WeakElement, F> {
589    /// The underlying iterator.
590    inner: inner::ExtractIf<'a, inner::Owned<K>, inner::WeakV<V>>,
591    /// A marker so that F does not appear unused.
592    _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    // TODO 050: remove.
609    #![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        // Absent key case:
686        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        // Present key case:
695        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}