stable_map/
iter.rs

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