stable_map/
keys.rs

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