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