Skip to main content

stable_map/
values.rs

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