Skip to main content

weak_table/
weak_weak_hash_map.rs

1//! A hash map where the keys and values are both held by weak pointers, and keys are compared by
2//! value.
3
4use super::traits::*;
5use super::*;
6use crate::common::*;
7
8pub use super::WeakWeakHashMap;
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 + WeakKey, 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 + WeakKey, V: 'a + WeakElement>(
21    inner::OccupiedEntry<'a, inner::WeakK<K>, inner::WeakV<V>>,
22);
23
24/// A vacant entry, which can be inserted in or viewed.
25pub struct VacantEntry<'a, K: 'a + WeakKey, V: 'a + WeakElement>(
26    inner::VacantEntry<'a, inner::WeakK<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::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/// 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: 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/// 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: 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)]
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::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
96/// An iterator that consumes a weak hash map, leaving it empty.
97pub 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    /// Gets the requested entry.
120    ///
121    /// expected *O*(*n*) time; worst-case *O*(*nq*) time (where *n* is
122    /// `self.capacity()` and *q* is the length of the probe sequences
123    /// in `other`)
124    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    /// Returns a reference to the value corresponding to the key.
132    ///
133    /// Returns `None` if no matching key is found.
134    ///
135    /// expected *O*(1) time; worst-case *O*(*p*) time
136    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    /// Returns the strong reference to the key, if present.
145    ///
146    /// expected *O*(1) time; worst-case *O*(*p*) time
147    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    /// Returns strong references to both the key and the value, if present.
156    ///
157    /// expected *O*(1) time; worst-case *O*(*p*) time
158    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    /// Returns true if the map contains the specified key.
167    ///
168    /// expected *O*(1) time; worst-case *O*(*p*) time
169    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    /// Unconditionally inserts the value, returning the old value if already present.
178    ///
179    /// Unlike `std::collections::HashMap`, this replaces the key even if occupied.
180    ///
181    /// expected *O*(1) time; worst-case *O*(*p*) time
182    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    /// Removes the entry with the given key, if it exists, and returns the value.
193    ///
194    /// expected *O*(1) time; worst-case *O*(*p*) time
195    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    /// Removes the entry with the given key, if it exists, and returns both the
204    /// key and value.
205    ///
206    /// expected *O*(1) time; worst-case *O*(*p*) time
207    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    /// Removes all mappings not satisfying the given predicate.
216    ///
217    /// Also removes any expired mappings.
218    ///
219    /// *O*(*n*) time
220    pub fn retain<F>(&mut self, mut f: F)
221    where
222        F: FnMut(K::Strong, V::Strong) -> bool,
223    {
224        // TODO: It would be better to use a retain method on Table, but I've
225        // run into lifetime issues there. See "TODO retain" in inner/table.rs
226        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    /// Is this map a submap of the other, using the given value comparison.
236    ///
237    /// In particular, all the keys of `self` must be in `other` and the values must compare
238    /// `true` with `value_equal`.
239    ///
240    /// expected *O*(*n*) time; worst-case *O*(*nq*) time (where *n* is
241    /// `self.capacity()` and *q* is the length of the probe sequences
242    /// in `other`)
243    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    /// Is `self` a submap of `other`?
267    ///
268    /// expected *O*(*n*) time; worst-case *O*(*nq*) time (where *n* is
269    /// `self.capacity()` and *q* is the length of the probe sequences
270    /// in `other`)
271    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    /// Are the keys of `self` a subset of the keys of `other`?
281    ///
282    /// expected *O*(*n*) time; worst-case *O*(*nq*) time (where *n* is
283    /// `self.capacity()` and *q* is the length of the probe sequences
284    /// in `other`)
285    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    /// Converts an array of key-value pairs into a map.
330    ///
331    /// If any entries in the array have equal keys,
332    /// all but one of the corresponding values will be dropped.
333    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    /// Ensures a value is in the entry by inserting a default value
356    /// if empty, and returns a mutable reference to the value in the
357    /// entry.
358    ///
359    /// *O*(1) time
360    pub fn or_insert(self, default: V::Strong) -> V::Strong {
361        self.or_insert_with(|| default)
362    }
363
364    /// Ensures a value is in the entry by inserting the result of the
365    /// `default` function if empty, and returns a strong reference to
366    /// the value in the entry.
367    ///
368    /// *O*(1) time
369    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    /// Ensures that a value is in the entry by inserting the result of calling the
377    /// `default` function on this entry's key if the function is empty, and
378    /// returns a strong reference to the value in the entry.
379    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    /// Returns a reference to this entry's key.
393    ///
394    /// *O*(1) time
395    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    /// Inserts a value into this entry, and returns an [`OccupiedEntry`].
403    ///
404    /// *O*(1) time
405    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    /// Gets a reference to the key held by the entry.
418    ///
419    /// *O*(1) time
420    pub fn key(&self) -> &K::Strong {
421        self.0.get().0
422    }
423
424    /// Takes ownership of the key and value, removing them from the map.
425    ///
426    /// expected *O*(1) time; worst-case *O*(*p*) time
427    pub fn remove_entry(self) -> (K::Strong, V::Strong) {
428        self.0.remove()
429    }
430
431    /// Gets a reference to the value in the entry.
432    ///
433    /// *O*(1) time
434    pub fn get(&self) -> &V::Strong {
435        self.0.get().1
436    }
437
438    /// Gets a clone of the reference to the value in the entry.
439    ///
440    /// *O*(1) time
441    pub fn get_strong(&self) -> V::Strong {
442        V::clone(self.get())
443    }
444
445    /// Replaces the value in the entry with the given value.
446    ///
447    /// Returns the previous value.
448    ///
449    /// *O*(1) time
450    pub fn insert(&mut self, value: V::Strong) -> V::Strong {
451        self.0.insert(value)
452    }
453
454    /// Removes the entry, returning the value.
455    ///
456    /// expected *O*(1) time; worst-case *O*(*p*) time
457    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    /// Gets a reference to the key that would be used when inserting a
464    /// value through the `VacantEntry`.
465    ///
466    /// *O*(1) time
467    pub fn key(&self) -> &K::Strong {
468        self.0.key()
469    }
470
471    /// Returns an owned reference to the key.
472    ///
473    /// *O*(1) time
474    pub fn into_key(self) -> K::Strong {
475        self.0.into_key()
476    }
477
478    /// Inserts the key and value into the map, returning the same value.
479    ///
480    /// *O*(1) time
481    pub fn insert(self, value: V::Strong) -> V::Strong {
482        V::clone(self.0.insert(value).get().1)
483    }
484
485    /// Inserts the key and value into the map, returning an `OccupiedEntry`.
486    ///
487    /// *O*(1) time
488    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    /// Creates an owning iterator from `self`.
515    ///
516    /// *O*(1) time (and *O*(*n*) time to dispose of the result)
517    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    /// Creates a borrowing iterator from `self`.
527    ///
528    /// *O*(1) time
529    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    /// Gets an iterator over the keys and values.
536    ///
537    /// *O*(1) time
538    pub fn iter(&self) -> Iter<'_, K, V> {
539        self.into_iter()
540    }
541
542    /// Gets an iterator over the keys.
543    ///
544    /// *O*(1) time
545    pub fn keys(&self) -> Keys<'_, K, V> {
546        Keys(self.iter())
547    }
548
549    /// Gets an iterator over the values.
550    ///
551    /// *O*(1) time
552    pub fn values(&self) -> Values<'_, K, V> {
553        Values(self.iter())
554    }
555
556    /// Gets a draining iterator, which removes all the values but retains the storage.
557    ///
558    /// *O*(1) time (and *O*(*n*) time to dispose of the result)
559    pub fn drain(&mut self) -> Drain<'_, K, V> {
560        Drain(self.0.drain())
561    }
562
563    into_kv_methods! {}
564
565    /// Gets an iterator that removes and returns elements matching a given predicate.
566    ///
567    /// Expired elements are also removed.
568    ///
569    /// If this iterator is dropped before it is completed, then no further
570    /// elements are removed.
571    /// (This is in contrast to the behavior of [`drain`](Self::drain)).
572    ///
573    /// *O*(1) time
574    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/// An iterator that removes members that match a given predicate.
592#[must_use = "iterators do nothing unless consumed; \
593    consider using `retain` instead"]
594pub struct ExtractIf<'a, K: WeakElement, V: WeakElement, F> {
595    /// The underlying iterator.
596    inner: inner::ExtractIf<'a, inner::WeakK<K>, inner::WeakV<V>>,
597    /// A marker so that F does not appear unused.
598    _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    // TODO 050: remove.
615    #![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        // Absent key case:
696        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        // Present key case:
707        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}