Skip to main content

stable_map/
values_mut.rs

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