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
304impl<K: Eq + Hash, V: WeakElement, const N: usize> From<[(K, V::Strong); N]>
305    for WeakValueHashMap<K, V, RandomState>
306{
307    /// Converts an array of key-value pairs into a map.
308    ///
309    /// If any entries in the array have equal keys,
310    /// all but one of the corresponding values will be dropped.
311    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    /// Ensures a value is in the entry by inserting a default value
353    /// if empty.
354    ///
355    /// *O*(1) time
356    pub fn or_insert(self, default: V::Strong) -> V::Strong {
357        self.or_insert_with(|| default)
358    }
359
360    /// Ensures a value is in the entry by inserting the result of the
361    /// `default` function if empty, and returns a strong reference to
362    /// the value in the entry.
363    ///
364    /// *O*(1) time
365    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    /// Ensures that a value is in the entry by inserting the result of calling the
373    /// `default` function on this entry's key if the function is empty, and
374    /// returns a strong reference to the value in the entry.
375    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    /// Returns a reference to this entry's key.
389    ///
390    /// *O*(1) time
391    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    /// Inserts a value into this entry, and returns an [`OccupiedEntry`].
399    ///
400    /// *O*(1) time
401    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    /// Gets a reference to the key held by the entry.
414    ///
415    /// *O*(1) time
416    pub fn key(&self) -> &K {
417        self.0.get().0
418    }
419
420    /// Takes ownership of the key and value, removing them from the map.
421    ///
422    /// expected *O*(1) time; worst-case *O*(*p*) time
423    pub fn remove_entry(self) -> (K, V::Strong) {
424        self.0.remove()
425    }
426
427    /// Gets a reference to the value in the entry.
428    ///
429    /// *O*(1) time
430    pub fn get(&self) -> &V::Strong {
431        self.0.get().1
432    }
433
434    /// Gets a copy of the strong value reference stored in the entry.
435    ///
436    /// *O*(1) time
437    pub fn get_strong(&self) -> V::Strong {
438        V::clone(self.get())
439    }
440
441    /// Replaces the value in the entry with the given value, returning the old value.
442    ///
443    /// *O*(1) time
444    pub fn insert(&mut self, value: V::Strong) -> V::Strong {
445        self.0.insert(value)
446    }
447
448    /// Removes the entry, returning the value.
449    ///
450    /// expected *O*(1) time; worst-case *O*(*p*) time
451    pub fn remove(self) -> V::Strong {
452        self.remove_entry().1
453    }
454}
455
456impl<'a, K, V: WeakElement> VacantEntry<'a, K, V> {
457    /// Gets a reference to the key that would be used when inserting a
458    /// value through the `VacantEntry`.
459    ///
460    /// *O*(1) time
461    pub fn key(&self) -> &K {
462        self.0.key()
463    }
464
465    /// Returns an owned reference to the key.
466    ///
467    /// *O*(1) time
468    pub fn into_key(self) -> K {
469        self.0.into_key()
470    }
471
472    /// Inserts the value into the map, returning the same value.
473    ///
474    /// *O*(1) time
475    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    /// Inserts the key and value into the map, returning an `OccupiedEntry`.
481    ///
482    /// *O*(1) time
483    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    /// Creates an owning iterator from `self`.
508    ///
509    /// *O*(1) time (and *O*(*n*) time to dispose of the result)
510    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    /// Creates a borrowing iterator from `self`.
520    ///
521    /// *O*(1) time
522    fn into_iter(self) -> Self::IntoIter {
523        Iter(self.0.iter())
524    }
525}
526
527impl<K, V: WeakElement, S> WeakValueHashMap<K, V, S> {
528    /// Gets an iterator over the keys and values.
529    ///
530    /// *O*(1) time
531    pub fn iter(&self) -> Iter<'_, K, V> {
532        self.into_iter()
533    }
534
535    /// Gets an iterator over the keys.
536    ///
537    /// *O*(1) time
538    pub fn keys(&self) -> Keys<'_, K, V> {
539        Keys(self.iter())
540    }
541
542    /// Gets an iterator over the values.
543    ///
544    /// *O*(1) time
545    pub fn values(&self) -> Values<'_, K, V> {
546        Values(self.iter())
547    }
548
549    /// Gets a draining iterator, which removes all the values but retains the storage.
550    ///
551    /// *O*(1) time (and *O*(*n*) time to dispose of the result)
552    pub fn drain(&mut self) -> Drain<'_, K, V> {
553        Drain(self.0.drain())
554    }
555
556    into_kv_methods! {}
557
558    /// Gets an iterator that removes and returns elements matching a given predicate.
559    ///
560    /// Expired elements are also removed.
561    ///
562    /// If this iterator is dropped before it is completed, then no further
563    /// elements are removed.
564    /// (This is in contrast to the behavior of [`drain`](Self::drain)).
565    ///
566    /// *O*(1) time
567    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
584/// An iterator that removes members that match a given predicate.
585pub struct ExtractIf<'a, K, V: WeakElement, F> {
586    /// The underlying iterator.
587    inner: inner::ExtractIf<'a, inner::Owned<K>, inner::WeakV<V>>,
588    /// A marker so that F does not appear unused.
589    _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        // Absent key case:
680        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        // Present key case:
689        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}