stable_map/
iter_mut.rs

1#[cfg(test)]
2mod tests;
3
4use {
5    crate::{
6        map::StableMap,
7        pos_vec::{
8            pos::{InUse, Pos},
9            PosVecRawAccess,
10        },
11    },
12    core::{
13        fmt::{Debug, Formatter},
14        iter::FusedIterator,
15    },
16    hashbrown::hash_map,
17};
18
19/// A mutable iterator over the entries of a `StableMap` in arbitrary order.
20/// The iterator element type is `(&'a K, &'a mut V)`.
21///
22/// This `struct` is created by the [`iter_mut`] method on [`StableMap`]. See its
23/// documentation for more.
24///
25/// [`iter_mut`]: crate::StableMap::iter_mut
26/// [`StableMap`]: crate::StableMap
27///
28/// # Examples
29///
30/// ```
31/// use stable_map::StableMap;
32///
33/// let mut map: StableMap<_, _> = [(1, "One".to_owned()), (2, "Two".into())].into();
34///
35/// let mut iter = map.iter_mut();
36/// iter.next().map(|(_, v)| v.push_str(" Mississippi"));
37/// iter.next().map(|(_, v)| v.push_str(" Mississippi"));
38///
39/// // It is fused iterator
40/// assert_eq!(iter.next(), None);
41/// assert_eq!(iter.next(), None);
42///
43/// assert_eq!(map.get(&1).unwrap(), &"One Mississippi".to_owned());
44/// assert_eq!(map.get(&2).unwrap(), &"Two Mississippi".to_owned());
45/// ```
46pub struct IterMut<'a, K, V> {
47    pub(crate) iter: hash_map::IterMut<'a, K, Pos<InUse>>,
48    pub(crate) entries: PosVecRawAccess<'a, V>,
49}
50
51impl<'a, K, V> Iterator for IterMut<'a, K, V> {
52    type Item = (&'a K, &'a mut V);
53
54    fn next(&mut self) -> Option<Self::Item> {
55        let (k, pos) = self.iter.next()?;
56        let value = unsafe { self.entries.get_unchecked_mut(pos) };
57        Some((k, value))
58    }
59
60    fn size_hint(&self) -> (usize, Option<usize>) {
61        self.iter.size_hint()
62    }
63}
64
65impl<'a, K, V, S> IntoIterator for &'a mut StableMap<K, V, S> {
66    type Item = (&'a K, &'a mut V);
67    type IntoIter = IterMut<'a, K, V>;
68
69    fn into_iter(self) -> Self::IntoIter {
70        self.iter_mut()
71    }
72}
73
74impl<K, V> Debug for IterMut<'_, K, V> {
75    fn fmt(&self, f: &mut Formatter<'_>) -> core::fmt::Result {
76        f.debug_struct("IterMut").finish_non_exhaustive()
77    }
78}
79
80impl<K, V> FusedIterator for IterMut<'_, K, V> {}
81
82impl<K, V> ExactSizeIterator for IterMut<'_, K, V> {
83    fn len(&self) -> usize {
84        self.iter.len()
85    }
86}
87
88// SAFETY:
89// - This impl is required because Pos<InUse>, Pos<Stored> allow for conflicting access
90//   but this API prevents this.
91unsafe impl<K, V> Send for IterMut<'_, K, V>
92where
93    K: Send,
94    V: Send,
95{
96}
97
98// SAFETY:
99// - This impl is required because Pos<InUse>, Pos<Stored> allow for conflicting access
100//   but this API prevents this.
101unsafe impl<K, V> Sync for IterMut<'_, K, V>
102where
103    K: Sync,
104    V: Sync,
105{
106}