Skip to main content

weak_table/
weak_key_hash_map.rs

1//! A hash map where the keys are held by weak pointers and compared by key value.
2
3use super::inner;
4use super::traits::*;
5use super::*;
6use crate::common::*;
7
8pub use super::WeakKeyHashMap;
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> {
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>(
21    inner::OccupiedEntry<'a, inner::WeakK<K>, inner::Owned<V>>,
22);
23
24/// A vacant entry, which can be inserted in or viewed.
25pub struct VacantEntry<'a, K: 'a + WeakKey, V: 'a>(
26    inner::VacantEntry<'a, inner::WeakK<K>, inner::Owned<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::Owned<V>>);
32
33impl<'a, K: WeakElement, V> Iterator for Iter<'a, K, V> {
34    type Item = (K::Strong, &'a V);
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(Debug)]
46/// An iterator over the keys and mutable values of the weak hash map.
47pub struct IterMut<'a, K: 'a, V: 'a>(inner::IterMut<'a, inner::WeakK<K>, inner::Owned<V>>);
48
49impl<'a, K: WeakElement, V> Iterator for IterMut<'a, K, V> {
50    type Item = (K::Strong, &'a mut V);
51
52    fn next(&mut self) -> Option<Self::Item> {
53        self.0.next()
54    }
55
56    fn size_hint(&self) -> (usize, Option<usize>) {
57        self.0.size_hint()
58    }
59}
60
61/// An iterator over the keys of the weak hash map.
62#[derive(Clone, Debug)]
63pub struct Keys<'a, K: 'a, V: 'a>(Iter<'a, K, V>);
64
65impl<'a, K: WeakElement, V> Iterator for Keys<'a, K, V> {
66    type Item = K::Strong;
67
68    fn next(&mut self) -> Option<Self::Item> {
69        self.0.next().map(|(k, _)| k)
70    }
71
72    fn size_hint(&self) -> (usize, Option<usize>) {
73        self.0.size_hint()
74    }
75}
76
77/// An iterator over the values of the weak hash map.
78#[derive(Clone, Debug)]
79pub struct Values<'a, K: 'a, V: 'a>(Iter<'a, K, V>);
80
81impl<'a, K: WeakElement, V> Iterator for Values<'a, K, V> {
82    type Item = &'a V;
83
84    fn next(&mut self) -> Option<Self::Item> {
85        self.0.next().map(|(_, v)| v)
86    }
87
88    fn size_hint(&self) -> (usize, Option<usize>) {
89        self.0.size_hint()
90    }
91}
92
93#[derive(Debug)]
94/// An iterator over the mutable values of the weak hash map.
95pub struct ValuesMut<'a, K: 'a, V: 'a>(IterMut<'a, K, V>);
96
97impl<'a, K: WeakElement, V> Iterator for ValuesMut<'a, K, V> {
98    type Item = &'a mut V;
99
100    fn next(&mut self) -> Option<Self::Item> {
101        self.0.next().map(|(_, v)| v)
102    }
103
104    fn size_hint(&self) -> (usize, Option<usize>) {
105        self.0.size_hint()
106    }
107}
108
109#[derive(Debug)]
110/// An iterator that consumes the values of a weak hash map, leaving it empty.
111///
112/// Once this iterator is dropped, all values are removed from the map,
113/// whether the iterator itself was drained or not.
114pub struct Drain<'a, K: 'a, V: 'a>(inner::Drain<'a, inner::WeakK<K>, inner::Owned<V>>);
115
116impl<'a, K: WeakElement, V> Iterator for Drain<'a, K, V> {
117    type Item = (K::Strong, V);
118
119    fn next(&mut self) -> Option<Self::Item> {
120        self.0.next()
121    }
122
123    fn size_hint(&self) -> (usize, Option<usize>) {
124        self.0.size_hint()
125    }
126}
127
128/// An iterator that consumes a weak hash map, leaving it empty.
129pub struct IntoIter<K, V>(inner::IntoIter<inner::WeakK<K>, inner::Owned<V>>);
130
131impl<K: WeakElement, V> Iterator for IntoIter<K, V> {
132    type Item = (K::Strong, V);
133
134    fn next(&mut self) -> Option<Self::Item> {
135        self.0.next()
136    }
137
138    fn size_hint(&self) -> (usize, Option<usize>) {
139        self.0.size_hint()
140    }
141}
142
143into_kv_types!(K::Strong, V where {K: WeakElement});
144
145universal_hashless_members! {
146    WeakKeyHashMap ("`WeakKeyHashMap`", a "map") inner::Table::new {K,V}
147}
148
149impl<K: WeakKey, V, S: BuildHasher> WeakKeyHashMap<K, V, S> {
150    universal_key_independent_members! {"mappings"}
151
152    /// Gets the requested entry.
153    ///
154    /// expected *O*(1) time; worst-case *O*(*p*) time
155    pub fn entry(&mut self, key: K::Strong) -> Entry<'_, K, V> {
156        match self.0.entry(key) {
157            inner::Entry::Occupied(occ) => Entry::Occupied(OccupiedEntry(occ)),
158            inner::Entry::Vacant(vac) => Entry::Vacant(VacantEntry(vac)),
159        }
160    }
161    /// Returns a reference to the value corresponding to the key.
162    ///
163    /// Returns `None` if no matching key is found.
164    ///
165    /// expected *O*(1) time; worst-case *O*(*p*) time
166    pub fn get<Q>(&self, key: &Q) -> Option<&V>
167    where
168        Q: ?Sized + Hash + Eq,
169        K::Key: Borrow<Q>,
170    {
171        Some(self.0.find(key)?.1)
172    }
173
174    /// Returns true if the map contains the specified key.
175    ///
176    /// expected *O*(1) time; worst-case *O*(*p*) time
177    pub fn contains_key<Q>(&self, key: &Q) -> bool
178    where
179        Q: ?Sized + Hash + Eq,
180        K::Key: Borrow<Q>,
181    {
182        self.0.find(key).is_some()
183    }
184
185    /// Returns a strong reference to the key, if found.
186    ///
187    /// expected *O*(1) time; worst-case *O*(*p*) time
188    pub fn get_key<Q>(&self, key: &Q) -> Option<K::Strong>
189    where
190        Q: ?Sized + Hash + Eq,
191        K::Key: Borrow<Q>,
192    {
193        Some(self.0.find(key)?.0)
194    }
195
196    /// Returns a pair of a strong reference to the key, and a reference to the value, if present.
197    ///
198    /// expected *O*(1) time; worst-case *O*(*p*) time
199    pub fn get_both<Q>(&self, key: &Q) -> Option<(K::Strong, &V)>
200    where
201        Q: ?Sized + Hash + Eq,
202        K::Key: Borrow<Q>,
203    {
204        self.0.find(key)
205    }
206
207    /// Returns a mutable reference to the value corresponding to the key.
208    ///
209    /// Returns `None` if no matching key is found.
210    ///
211    /// expected *O*(1) time; worst-case *O*(*p*) time
212    pub fn get_mut<Q>(&mut self, key: &Q) -> Option<&mut V>
213    where
214        Q: ?Sized + Hash + Eq,
215        K::Key: Borrow<Q>,
216    {
217        Some(self.0.find_mut(key)?.1)
218    }
219
220    /// Returns a pair of a strong reference to the key, and a mutable reference to the value,
221    /// if present.
222    ///
223    /// expected *O*(1) time; worst-case *O*(*p*) time
224    pub fn get_both_mut<Q>(&mut self, key: &Q) -> Option<(K::Strong, &mut V)>
225    where
226        Q: ?Sized + Hash + Eq,
227        K::Key: Borrow<Q>,
228    {
229        self.0.find_mut(key)
230    }
231
232    /// Looks up mutable references to the values corresponding to several keys
233    /// at a time.
234    ///
235    /// (Because of borrowing rules, Rust doesn't allow you to call `get_mut()` again
236    /// while the result of a previous `get_mut()` is still live.  This method exists
237    /// to work around that limitation.)
238    ///
239    /// Only one mutable reference can exist to any given value at a time.
240    /// Therefore, all keys must refer to different values, or this
241    /// method will panic.
242    ///
243    /// expected *O*(1 `N^2`) time; worst-case *O*(*p* `N^2`) time,
244    /// where N is the length of the array.
245    ///
246    /// # Panics
247    ///
248    /// Panics if any keys refer to the same value.
249    pub fn get_disjoint_mut<Q, const N: usize>(&mut self, ks: [&Q; N]) -> [Option<&mut V>; N]
250    where
251        Q: Hash + Eq + ?Sized,
252        K::Key: Borrow<Q>,
253    {
254        self.0.get_disjoint_mut(ks).map(|e| e.map(|(_k, v)| v))
255    }
256
257    /// Looks up mutable references to the values corresponding to several keys
258    /// at a time.  Returns those references along with their keys as stored in
259    /// the table.
260    ///
261    /// (Because of borrowing rules, Rust doesn't allow you to call `get_mut()` again
262    /// while the result of a previous `get_mut()` is still live.  This method exists
263    /// to work around that limitation.)
264    ///
265    /// Only one mutable reference can exist to any given value at a time.
266    /// Therefore, all keys must refer to different values, or this
267    /// method will panic.
268    ///
269    /// expected *O*(1 `N^2`) time; worst-case *O*(*p* `N^2`) time,
270    /// where N is the length of the array.
271    ///
272    /// # Panics
273    ///
274    /// Panics if any keys refer to the same value.
275    pub fn get_both_disjoint_mut<Q, const N: usize>(
276        &mut self,
277        ks: [&Q; N],
278    ) -> [Option<(K::Strong, &mut V)>; N]
279    where
280        Q: Hash + Eq + ?Sized,
281        K::Key: Borrow<Q>,
282    {
283        self.0.get_disjoint_mut(ks)
284    }
285
286    /// Unconditionally inserts the value, returning the old value if already present.
287    ///
288    /// Unlike `std::collections::HashMap`, this replaces the key even the entry was occupied.
289    ///
290    /// expected *O*(1) time; worst-case *O*(*p*) time
291    pub fn insert(&mut self, key: K::Strong, value: V) -> Option<V> {
292        match self.entry(key) {
293            Entry::Occupied(mut occupied) => Some(occupied.insert(value)),
294            Entry::Vacant(vacant) => {
295                vacant.insert(value);
296                None
297            }
298        }
299    }
300
301    /// Removes the entry with the given key, if it exists, and returns the value.
302    ///
303    /// expected *O*(1) time; worst-case *O*(*p*) time
304    pub fn remove<Q>(&mut self, key: &Q) -> Option<V>
305    where
306        Q: ?Sized + Hash + Eq,
307        K::Key: Borrow<Q>,
308    {
309        Some(self.0.find_entry(key)?.remove().1)
310    }
311
312    /// Removes the entry with the given key, if it exists, and returns both the
313    /// key and value.
314    ///
315    /// expected *O*(1) time; worst-case *O*(*p*) time
316    pub fn remove_entry<Q>(&mut self, key: &Q) -> Option<(K::Strong, V)>
317    where
318        Q: ?Sized + Hash + Eq,
319        K::Key: Borrow<Q>,
320    {
321        Some(self.0.find_entry(key)?.remove())
322    }
323
324    /// Removes all mappings not satisfying the given predicate.
325    ///
326    /// Also removes any expired mappings.
327    ///
328    /// *O*(*n*) time
329    pub fn retain<F>(&mut self, mut f: F)
330    where
331        F: FnMut(K::Strong, &mut V) -> bool,
332    {
333        // TODO: It would be better to use a retain method on Table, but I've
334        // run into lifetime issues there. See "TODO retain" in inner/table.rs
335        self.0.table.retain(|(k, v)| {
336            if let Some(k) = k.val.view() {
337                f(k, &mut v.val)
338            } else {
339                false
340            }
341        });
342    }
343
344    /// Is this map a submap of the other under the given value comparison `cmp`?
345    ///
346    /// In particular, for every key `k` of `self`,
347    ///
348    ///  - `k` must also be a key of `other` and
349    ///  - `cmp(self[k], other[k])` must hold.
350    ///
351    /// expected *O*(*n*) time; worst-case *O*(*nq*) time (where *n* is
352    /// `self.capacity()` and *q* is the length of the probe sequences
353    /// in `other`)
354    pub fn is_submap_with<F, S1, V1>(&self, other: &WeakKeyHashMap<K, V1, S1>, mut cmp: F) -> bool
355    where
356        F: FnMut(&V, &V1) -> bool,
357        S1: BuildHasher,
358    {
359        for (key, value1) in self {
360            if let Some(value2) = K::with_key(&key, |k| other.get(k)) {
361                if !cmp(value1, value2) {
362                    return false;
363                }
364            } else {
365                return false;
366            }
367        }
368
369        true
370    }
371
372    /// Is `self` a submap of `other`?
373    ///
374    /// expected *O*(*n*) time; worst-case *O*(*nq*) time (where *n* is
375    /// `self.capacity()` and *q* is the length of the probe sequences
376    /// in `other`)
377    pub fn is_submap<V1, S1>(&self, other: &WeakKeyHashMap<K, V1, S1>) -> bool
378    where
379        V: PartialEq<V1>,
380        S1: BuildHasher,
381    {
382        self.is_submap_with(other, PartialEq::eq)
383    }
384
385    /// Are the keys of `self` a subset of the keys of `other`?
386    ///
387    /// expected *O*(*n*) time; worst-case *O*(*nq*) time (where *n* is
388    /// `self.capacity()` and *q* is the length of the probe sequences
389    /// in `other`)
390    pub fn domain_is_subset<V1, S1>(&self, other: &WeakKeyHashMap<K, V1, S1>) -> bool
391    where
392        S1: BuildHasher,
393    {
394        self.is_submap_with(other, |_, _| true)
395    }
396}
397
398impl<K, V, V1, S, S1> PartialEq<WeakKeyHashMap<K, V1, S1>> for WeakKeyHashMap<K, V, S>
399where
400    K: WeakKey,
401    V: PartialEq<V1>,
402    S: BuildHasher,
403    S1: BuildHasher,
404{
405    fn eq(&self, other: &WeakKeyHashMap<K, V1, S1>) -> bool {
406        self.is_submap(other) && other.domain_is_subset(self)
407    }
408}
409
410impl<K: WeakKey, V: Eq, S: BuildHasher> Eq for WeakKeyHashMap<K, V, S> {}
411
412impl<'a, K, V, S, Q> ops::Index<&'a Q> for WeakKeyHashMap<K, V, S>
413where
414    K: WeakKey,
415    K::Key: Borrow<Q>,
416    S: BuildHasher,
417    Q: ?Sized + Eq + Hash,
418{
419    type Output = V;
420
421    fn index(&self, index: &'a Q) -> &Self::Output {
422        self.get(index).expect("Index::index: key not found")
423    }
424}
425
426impl<'a, K, V, S, Q> ops::IndexMut<&'a Q> for WeakKeyHashMap<K, V, S>
427where
428    K: WeakKey,
429    K::Key: Borrow<Q>,
430    S: BuildHasher,
431    Q: ?Sized + Eq + Hash,
432{
433    fn index_mut(&mut self, index: &'a Q) -> &mut Self::Output {
434        self.get_mut(index)
435            .expect("IndexMut::index_mut: key not found")
436    }
437}
438
439impl<K, V, S> iter::FromIterator<(K::Strong, V)> for WeakKeyHashMap<K, V, S>
440where
441    K: WeakKey,
442    S: BuildHasher + Default,
443{
444    fn from_iter<T: IntoIterator<Item = (K::Strong, V)>>(iter: T) -> Self {
445        let iter = iter.into_iter();
446        let min_size = iter.size_hint().0;
447        let mut result = WeakKeyHashMap::with_capacity_and_hasher(min_size, Default::default());
448        result.extend(iter);
449        result
450    }
451}
452
453impl<K: WeakKey, V, const N: usize> From<[(K::Strong, V); N]>
454    for WeakKeyHashMap<K, V, RandomState>
455{
456    /// Converts an array of key-value pairs into a map.
457    ///
458    /// If any entries in the array have equal keys,
459    /// all but one of the corresponding values will be dropped.
460    fn from(value: [(K::Strong, V); N]) -> Self {
461        Self::from_iter(value)
462    }
463}
464
465impl<K, V, S> iter::Extend<(K::Strong, V)> for WeakKeyHashMap<K, V, S>
466where
467    K: WeakKey,
468    S: BuildHasher,
469{
470    fn extend<T: IntoIterator<Item = (K::Strong, V)>>(&mut self, iter: T) {
471        let iter = iter.into_iter();
472        let min_size = iter.size_hint().0;
473        self.reserve(min_size);
474        for (key, value) in iter {
475            self.insert(key, value);
476        }
477    }
478}
479
480impl<'a, K, V, S> iter::Extend<(&'a K::Strong, &'a V)> for WeakKeyHashMap<K, V, S>
481where
482    K: 'a + WeakKey,
483    K::Strong: Clone,
484    V: 'a + Clone,
485    S: BuildHasher,
486{
487    fn extend<T: IntoIterator<Item = (&'a K::Strong, &'a V)>>(&mut self, iter: T) {
488        let iter = iter.into_iter();
489        let min_size = iter.size_hint().0;
490        self.reserve(min_size);
491        for (key, value) in iter {
492            self.insert(key.clone(), value.clone());
493        }
494    }
495}
496
497impl<'a, K: WeakKey, V> Entry<'a, K, V> {
498    /// Ensures a value is in the entry by inserting a default value
499    /// if empty, and returns a mutable reference to the value in the
500    /// entry.
501    ///
502    /// *O*(1) time
503    pub fn or_insert(self, default: V) -> &'a mut V {
504        self.or_insert_with(|| default)
505    }
506
507    /// Ensures a value is in the entry by inserting the result of the
508    /// `default` function if empty, and returns a mutable reference to
509    /// the value in the entry.
510    ///
511    /// *O*(1) time
512    pub fn or_insert_with<F: FnOnce() -> V>(self, default: F) -> &'a mut V {
513        match self {
514            Entry::Occupied(occupied) => occupied.into_mut(),
515            Entry::Vacant(vacant) => vacant.insert(default()),
516        }
517    }
518
519    /// Ensures that a value is in the entry by inserting the result of calling the
520    /// `default` function on this entry's key if the function is empty, and
521    /// returns a mutable reference to the value in the entry.
522    pub fn or_insert_with_key<F>(self, default: F) -> &'a mut V
523    where
524        F: FnOnce(&K::Strong) -> V,
525    {
526        match self {
527            Entry::Occupied(occupied) => occupied.into_mut(),
528            Entry::Vacant(vacant) => {
529                let value = default(vacant.key());
530                vacant.insert(value)
531            }
532        }
533    }
534
535    /// Returns a reference to this entry's key.
536    ///
537    /// *O*(1) time
538    pub fn key(&self) -> &K::Strong {
539        match *self {
540            Entry::Occupied(ref occupied) => occupied.key(),
541            Entry::Vacant(ref vacant) => vacant.key(),
542        }
543    }
544
545    /// Inserts a value into this entry, and returns an [`OccupiedEntry`].
546    ///
547    /// *O*(1) time
548    pub fn insert_entry(self, value: V) -> OccupiedEntry<'a, K, V> {
549        match self {
550            Entry::Occupied(mut occupied) => {
551                occupied.insert(value);
552                occupied
553            }
554            Entry::Vacant(vacant) => vacant.insert_entry(value),
555        }
556    }
557
558    /// If this entry is occupied, uses `f` to modify its value in place.
559    ///
560    /// (Otherwise, if the entry is vacant, does nothing.)
561    ///
562    /// *O*(1) time
563    pub fn and_modify<F>(mut self, f: F) -> Self
564    where
565        F: FnOnce(&mut V),
566    {
567        if let Entry::Occupied(occupied) = &mut self {
568            f(occupied.get_mut());
569        }
570        self
571    }
572}
573
574impl<'a, K: WeakKey, V> OccupiedEntry<'a, K, V> {
575    /// Gets a reference to the key held by the entry.
576    ///
577    /// *O*(1) time
578    pub fn key(&self) -> &K::Strong {
579        self.0.get().0
580    }
581
582    /// Takes ownership of the key and value, removing them from the map.
583    ///
584    /// expected *O*(1) time; worst-case *O*(*p*) time
585    pub fn remove_entry(self) -> (K::Strong, V) {
586        self.0.remove()
587    }
588
589    /// Gets a reference to the value in the entry.
590    ///
591    /// *O*(1) time
592    pub fn get(&self) -> &V {
593        self.0.get().1
594    }
595
596    /// Gets a mutable reference to the value in the entry.
597    ///
598    /// *O*(1) time
599    pub fn get_mut(&mut self) -> &mut V {
600        // TODO: It would be better to use a get_mut method on inner::OccupiedEntry, but I've
601        // run into lifetime issues there. See "TODO get_mut" in inner/table.rs
602        &mut self.0.inner.get_mut().1.val
603    }
604
605    /// Turns the entry into a mutable reference to the value borrowed from the map.
606    ///
607    /// *O*(1) time
608    pub fn into_mut(self) -> &'a mut V {
609        self.0.into_mut()
610    }
611
612    /// Replaces the value in the entry with the given value.
613    ///
614    /// Returns the previous value.
615    ///
616    /// *O*(1) time
617    pub fn insert(&mut self, mut value: V) -> V {
618        mem::swap(&mut value, self.get_mut());
619        value
620    }
621
622    /// Removes the entry, returning the value.
623    ///
624    /// expected *O*(1) time; worst-case *O*(*p*) time
625    pub fn remove(self) -> V {
626        self.remove_entry().1
627    }
628}
629
630impl<'a, K: WeakKey, V> VacantEntry<'a, K, V> {
631    /// Gets a reference to the key that would be used when inserting a
632    /// value through the `VacantEntry`.
633    ///
634    /// *O*(1) time
635    pub fn key(&self) -> &K::Strong {
636        self.0.key()
637    }
638
639    /// Returns an owned reference to the key.
640    ///
641    /// *O*(1) time
642    pub fn into_key(self) -> K::Strong {
643        self.0.into_key()
644    }
645
646    /// Inserts the key and value into the map and return a mutable
647    /// reference to the value.
648    ///
649    /// expected *O*(1) time; worst-case *O*(*p*) time
650    pub fn insert(self, value: V) -> &'a mut V {
651        let occupied = self.0.insert(value);
652        occupied.into_mut()
653    }
654
655    /// Inserts the key and value into the map, returning an `OccupiedEntry`.
656    ///
657    /// *O*(1) time
658    pub fn insert_entry(self, value: V) -> OccupiedEntry<'a, K, V> {
659        OccupiedEntry(self.0.insert(value))
660    }
661}
662
663impl<K: WeakElement, V: Debug, S> Debug for WeakKeyHashMap<K, V, S>
664where
665    K::Strong: Debug,
666{
667    fn fmt(&self, f: &mut Formatter) -> fmt::Result {
668        f.debug_map().entries(self.iter()).finish()
669    }
670}
671
672debug_for_entry! {where {
673    K: WeakKey,
674    K::Strong: Debug,
675    V: Debug}
676}
677
678impl<K: WeakElement, V, S> IntoIterator for WeakKeyHashMap<K, V, S> {
679    type Item = (K::Strong, V);
680    type IntoIter = IntoIter<K, V>;
681
682    /// Creates an owning iterator from `self`.
683    ///
684    /// *O*(1) time (and *O*(*n*) time to dispose of the result)
685    fn into_iter(self) -> Self::IntoIter {
686        IntoIter(self.0.into_iter())
687    }
688}
689
690impl<'a, K: WeakElement, V, S> IntoIterator for &'a WeakKeyHashMap<K, V, S> {
691    type Item = (K::Strong, &'a V);
692    type IntoIter = Iter<'a, K, V>;
693
694    /// Creates a borrowing iterator from `self`.
695    ///
696    /// *O*(1) time
697    fn into_iter(self) -> Self::IntoIter {
698        Iter(self.0.iter())
699    }
700}
701
702impl<'a, K: WeakElement, V, S> IntoIterator for &'a mut WeakKeyHashMap<K, V, S> {
703    type Item = (K::Strong, &'a mut V);
704    type IntoIter = IterMut<'a, K, V>;
705
706    /// Creates a borrowing iterator from `self`.
707    ///
708    /// *O*(1) time
709    fn into_iter(self) -> Self::IntoIter {
710        IterMut(self.0.iter_mut())
711    }
712}
713
714impl<K: WeakElement, V, S> WeakKeyHashMap<K, V, S> {
715    /// Gets an iterator over the keys and values.
716    ///
717    /// *O*(1) time
718    pub fn iter(&self) -> Iter<'_, K, V> {
719        self.into_iter()
720    }
721
722    /// Gets an iterator over the keys.
723    ///
724    /// *O*(1) time
725    pub fn keys(&self) -> Keys<'_, K, V> {
726        Keys(self.iter())
727    }
728
729    /// Gets an iterator over the values.
730    ///
731    /// *O*(1) time
732    pub fn values(&self) -> Values<'_, K, V> {
733        Values(self.iter())
734    }
735
736    /// Gets an iterator over the keys and mutable values.
737    ///
738    /// *O*(1) time
739    pub fn iter_mut(&mut self) -> IterMut<'_, K, V> {
740        self.into_iter()
741    }
742
743    /// Gets an iterator over the mutable values.
744    ///
745    /// *O*(1) time
746    pub fn values_mut(&mut self) -> ValuesMut<'_, K, V> {
747        ValuesMut(self.iter_mut())
748    }
749
750    /// Gets a draining iterator, which removes all the values but retains the storage.
751    ///
752    /// *O*(1) time (and *O*(*n*) time to dispose of the result)
753    pub fn drain(&mut self) -> Drain<'_, K, V> {
754        Drain(self.0.drain())
755    }
756
757    into_kv_methods! {}
758
759    /// Gets an iterator that removes and returns elements matching a given predicate.
760    ///
761    /// Expired elements are also removed.
762    ///
763    /// If this iterator is dropped before it is completed, then no further
764    /// elements are removed.
765    /// (This is in contrast to the behavior of [`drain`](Self::drain)).
766    ///
767    /// *O*(1) time
768    pub fn extract_if<'a, F>(&'a mut self, mut f: F) -> ExtractIf<'a, K, V, F>
769    where
770        F: FnMut(K::Strong, &mut V) -> bool + 'a,
771    {
772        ExtractIf {
773            inner: self.0.extract_if(move |e| {
774                if let Some(k) = e.0.val.view() {
775                    f(k, &mut e.1.val)
776                } else {
777                    true
778                }
779            }),
780            _phantom: PhantomData,
781        }
782    }
783}
784
785/// An iterator that removes members that match a given predicate.
786pub struct ExtractIf<'a, K: WeakElement, V, F> {
787    /// The underlying iterator.
788    inner: inner::ExtractIf<'a, inner::WeakK<K>, inner::Owned<V>>,
789    /// A marker so that F does not appear unused.
790    _phantom: PhantomData<F>,
791}
792
793impl<'a, K: WeakElement, V, F> Iterator for ExtractIf<'a, K, V, F> {
794    type Item = (K::Strong, V);
795
796    fn next(&mut self) -> Option<Self::Item> {
797        self.inner.next()
798    }
799    fn size_hint(&self) -> (usize, Option<usize>) {
800        self.inner.size_hint()
801    }
802}
803
804#[cfg(test)]
805mod test {
806    #![allow(clippy::print_stderr)]
807
808    use super::{Entry, WeakKeyHashMap};
809    use crate::{
810        compat::{
811            eprintln, format,
812            rc::{Rc, Weak},
813            RandomState, String, ToString as _, Vec,
814        },
815        tests::util::VecDebugAsMap,
816        util,
817    };
818
819    crate::tests::common::empty_constructor_tests! {WeakKeyHashMap<Weak<u8>, u32>}
820
821    #[test]
822    fn simple() {
823        let mut map: WeakKeyHashMap<Weak<str>, usize> = WeakKeyHashMap::new();
824        assert_eq!(map.len(), 0);
825        assert!(!map.contains_key("five"));
826
827        let five: Rc<str> = Rc::from(String::from("five"));
828        map.insert(five.clone(), 5);
829
830        assert_eq!(map.len(), 1);
831        assert!(map.contains_key("five"));
832
833        drop(five);
834
835        assert_eq!(map.len(), 1);
836        assert!(!map.contains_key("five"));
837
838        map.remove_expired();
839
840        assert_eq!(map.len(), 0);
841        assert!(!map.contains_key("five"));
842    }
843
844    #[test]
845    fn simple_arc() {
846        use crate::compat::sync::{Arc, Weak};
847        let mut map: WeakKeyHashMap<Weak<str>, usize> = WeakKeyHashMap::new();
848        assert_eq!(map.len(), 0);
849        assert!(!map.contains_key("five"));
850
851        let five: Arc<str> = Arc::from(String::from("five"));
852        map.insert(five.clone(), 5);
853
854        assert_eq!(map.len(), 1);
855        assert!(map.contains_key("five"));
856
857        drop(five);
858
859        assert_eq!(map.len(), 1);
860        assert!(!map.contains_key("five"));
861
862        map.remove_expired();
863
864        assert_eq!(map.len(), 0);
865        assert!(!map.contains_key("five"));
866    }
867
868    #[test]
869    fn access_hasher() {
870        let bh = RandomState::new();
871
872        let map: WeakKeyHashMap<Weak<str>, usize> = WeakKeyHashMap::with_hasher(bh.clone());
873
874        assert_eq!(
875            util::hash_one(&bh, "hello world"),
876            util::hash_one(map.hasher(), "hello world")
877        );
878    }
879
880    #[test]
881    fn load_factor() {
882        let mut rcs: Vec<Rc<u32>> = (0..50).map(Rc::new).collect();
883        let weakmap: WeakKeyHashMap<Weak<u32>, u32> =
884            rcs.iter().map(|n| (n.clone(), *n.as_ref())).collect();
885        rcs.retain(|n| **n % 3 != 0);
886
887        let load = weakmap.load_factor();
888        assert!(load < 1.0);
889        assert!(load > 0.0);
890    }
891
892    #[test]
893    fn is_submap() {
894        let mut rcs: Vec<Rc<u32>> = (0..50).map(Rc::new).collect();
895        let weakmap: WeakKeyHashMap<Weak<u32>, u32> = rcs
896            .iter()
897            .take(25)
898            .map(|n| (n.clone(), *n.as_ref()))
899            .collect();
900        let mut weakmap2 = weakmap.clone();
901
902        assert!(weakmap.is_submap(&weakmap2));
903        assert!(weakmap2.is_submap(&weakmap));
904
905        weakmap2.extend(rcs.iter().skip(25).map(|n| (n, n.as_ref())));
906        assert!(weakmap.is_submap(&weakmap2));
907        assert!(!weakmap2.is_submap(&weakmap));
908
909        weakmap2[&0] = 12;
910        assert!(!weakmap.is_submap(&weakmap2));
911        assert!(!weakmap2.is_submap(&weakmap));
912
913        let _ = rcs.remove(0);
914        assert!(weakmap.is_submap(&weakmap2));
915    }
916
917    #[test]
918    fn entry_methods() {
919        let rcs: Vec<Rc<u32>> = (0..5).map(Rc::new).collect();
920        let mut weakmap: WeakKeyHashMap<Weak<u32>, u32> =
921            rcs.iter().map(|n| (n.clone(), *n.as_ref())).collect();
922
923        let seven = Rc::new(7);
924        let ptr = weakmap.entry(seven.clone()).or_insert(14);
925        assert_eq!(*ptr, 14);
926        *ptr = 21;
927
928        assert_eq!(weakmap.get(&7), Some(&21));
929
930        let twelve = Rc::new(12);
931        let e = weakmap.entry(twelve.clone());
932        if let Entry::Vacant(v) = e {
933            let t2 = v.into_key();
934            assert_eq!(*t2, 12);
935        } else {
936            panic!();
937        }
938        assert!(!weakmap.contains_key(&12));
939    }
940
941    #[test]
942    fn or_insert_with() {
943        let rcs: Vec<Rc<u32>> = (0..5).map(Rc::new).collect();
944        let mut weakmap: WeakKeyHashMap<Weak<u32>, u32> =
945            rcs.iter().map(|n| (n.clone(), **n)).collect();
946        let seven = Rc::new(7);
947        let eight = Rc::new(8);
948
949        // Absent key case:
950        let ptr: &mut u32 = weakmap.entry(seven.clone()).or_insert_with(|| 14);
951        assert_eq!(*ptr, 14);
952        let ptr: &mut u32 = weakmap.entry(eight.clone()).or_insert_with_key(|k| **k * 2);
953        assert_eq!(*ptr, 16);
954
955        // Present key case:
956        let one = Rc::new(1);
957        let ptr: &mut u32 = weakmap.entry(one.clone()).or_insert_with(|| 14);
958        assert_eq!(*ptr, 1);
959        let ptr: &mut u32 = weakmap.entry(one.clone()).or_insert_with_key(|k| **k * 2);
960        assert_eq!(*ptr, 1);
961    }
962
963    #[test]
964    fn entry_insert_entry() {
965        let rcs: Vec<Rc<u32>> = (0..5).map(Rc::new).collect();
966        let mut weakmap: WeakKeyHashMap<Weak<u32>, u32> =
967            rcs.iter().map(|n| (n.clone(), **n)).collect();
968
969        let one = Rc::new(1);
970        let ten = Rc::new(10);
971
972        let e1: super::OccupiedEntry<'_, Weak<u32>, u32> =
973            weakmap.entry(one.clone()).insert_entry(1001);
974        assert_eq!(e1.key(), &one);
975        assert_eq!(e1.get(), &1001);
976
977        let e2: super::OccupiedEntry<'_, Weak<u32>, u32> =
978            weakmap.entry(ten.clone()).insert_entry(1010);
979        assert_eq!(e2.key(), &ten);
980        assert_eq!(e2.get(), &1010);
981
982        assert_eq!(weakmap.get(&1), Some(&1001));
983        assert_eq!(weakmap.get(&10), Some(&1010));
984    }
985
986    #[test]
987    fn entry_and_modify() {
988        let rcs: Vec<Rc<u32>> = (0..5).map(Rc::new).collect();
989        let mut weakmap: WeakKeyHashMap<Weak<u32>, u32> =
990            rcs.iter().map(|n| (n.clone(), **n)).collect();
991
992        let one = Rc::new(1);
993        let ten = Rc::new(10);
994
995        let e = weakmap.entry(one.clone()).and_modify(|v| *v *= 2);
996        assert!(matches!(e, Entry::Occupied(e) if e.get() == &2));
997
998        let e = weakmap.entry(ten.clone()).and_modify(|v| *v *= 2);
999        assert!(matches!(e, Entry::Vacant(_)));
1000    }
1001
1002    #[test]
1003    fn vacant_insert_entry() {
1004        let mut weakmap: WeakKeyHashMap<Weak<u32>, u32> = Default::default();
1005        let five = Rc::new(5);
1006
1007        let Entry::Vacant(e) = weakmap.entry(five.clone()) else {
1008            panic!("Not vacant");
1009        };
1010        let e: super::OccupiedEntry<'_, Weak<u32>, u32> = e.insert_entry(500);
1011        assert_eq!(e.get(), &500);
1012    }
1013
1014    #[test]
1015    fn from_array() {
1016        let a = [(Rc::new(5), 25), (Rc::new(7), 49), (Rc::new(9), 81)];
1017        let v = a.to_vec();
1018
1019        let map: WeakKeyHashMap<Weak<u32>, u32> = WeakKeyHashMap::from(a);
1020        assert_eq!(map.iter().count(), 3);
1021        let mut v2: Vec<_> = map.iter().map(|(k, v)| (k, *v)).collect();
1022        v2.sort();
1023        assert_eq!(v, v2);
1024    }
1025
1026    // From https://github.com/tov/weak-table-rs/issues/1#issuecomment-461858060
1027    #[test]
1028    fn insert_and_check() {
1029        let mut rcs: Vec<Rc<u32>> = Vec::new();
1030
1031        for i in 0..50 {
1032            rcs.push(Rc::new(i));
1033        }
1034
1035        let mut weakmap: WeakKeyHashMap<Weak<u32>, f32> = WeakKeyHashMap::new();
1036
1037        for key in rcs.iter().cloned() {
1038            let f = *key as f32 + 0.1;
1039            weakmap.insert(key, f);
1040        }
1041
1042        let mut count = 0;
1043
1044        for key in &rcs {
1045            assert_eq!(weakmap.get(key), Some(&(**key as f32 + 0.1)));
1046
1047            match weakmap.entry(Rc::clone(key)) {
1048                Entry::Occupied(_) => count += 1,
1049                Entry::Vacant(_) => eprintln!("WeakKeyHashMap: missing: {}", *key),
1050            }
1051        }
1052
1053        assert_eq!(count, rcs.len());
1054    }
1055
1056    #[test]
1057    fn extract_if() {
1058        let rcs: Vec<Rc<u32>> = (0..50).map(Rc::new).collect();
1059        let mut weakmap: WeakKeyHashMap<Weak<u32>, u32> =
1060            rcs.iter().map(|k| (k.clone(), *k.as_ref())).collect();
1061        let even_numbers: crate::compat::HashSet<u32> = (0..50).filter(|n| n % 2 == 0).collect();
1062
1063        let evens: Vec<_> = weakmap
1064            .extract_if(|k, v| {
1065                debug_assert!(k.as_ref() == v);
1066                *v *= 2;
1067                even_numbers.contains(k.as_ref())
1068            })
1069            .collect();
1070
1071        assert_eq!(weakmap.iter().count(), 25);
1072        assert_eq!(evens.len(), 25);
1073    }
1074
1075    #[test]
1076    fn failed_try_reserve() {
1077        let rcs: Vec<Rc<u32>> = (0..1000).map(Rc::new).collect();
1078        let mut map: WeakKeyHashMap<Weak<u32>, u32> =
1079            rcs.iter().map(|n| (n.clone(), **n)).collect();
1080
1081        // This one will cause an integer overflow in our code.
1082        let e = map.try_reserve(usize::MAX - 500);
1083        assert!(matches!(e, Err(crate::TryReserveError::CapacityOverflow)));
1084        assert_eq!(
1085            e.expect_err("Already checked").to_string(),
1086            "Allocation failed: arithmetic overflow in capacity calculation"
1087        );
1088
1089        // This one will cause an integer overflow in hashbrown.
1090        let e = map.try_reserve(usize::MAX / 4);
1091        assert!(matches!(e, Err(crate::TryReserveError::CapacityOverflow)));
1092    }
1093
1094    #[test]
1095    fn debug_map() {
1096        let rcs: Vec<Rc<u32>> = (0..20).map(Rc::new).collect();
1097        let map: WeakKeyHashMap<Weak<u32>, u32> =
1098            rcs.iter().map(|n| (n.clone(), **n * 7)).collect();
1099        let vec: VecDebugAsMap<_, _> = map.iter().collect();
1100        assert_eq!(format!("{map:?}"), format!("{vec:?}"));
1101    }
1102
1103    #[test]
1104    fn debug_entry() {
1105        let three = Rc::new(3);
1106        let mut map = WeakKeyHashMap::<Weak<u32>, u32>::new();
1107        map.insert(three.clone(), 9);
1108        let e1 = map.entry(three.clone());
1109        assert_eq!(format!("{e1:?}"), "OccupiedEntry { key: 3, val: 9 }");
1110
1111        let four = Rc::new(4);
1112        let e2 = map.entry(four.clone());
1113        assert_eq!(format!("{e2:?}"), "VacantEntry { key: 4 }");
1114    }
1115}