stable_map/into_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 owning iterator over the values of a `StableMap` in arbitrary order.
17/// The iterator element type is `V`.
18///
19/// This `struct` is created by the [`into_values`] method on [`StableMap`].
20/// See its documentation for more. The map cannot be used after calling that method.
21///
22/// [`into_values`]: crate::StableMap::into_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.into_values();
33/// let mut vec = vec![values.next(), values.next(), values.next()];
34///
35/// // The `IntoValues` iterator produces values in arbitrary order, so
36/// // the 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 IntoValues<K, V> {
45 pub(crate) iter: hash_map::IntoValues<K, Pos<InUse>>,
46 pub(crate) storage: LinearStorage<V>,
47}
48
49impl<K, V> Iterator for IntoValues<K, V> {
50 type Item = V;
51
52 fn next(&mut self) -> Option<Self::Item> {
53 let pos = self.iter.next()?;
54 let value = unsafe { self.storage.take_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> Debug for IntoValues<K, V> {
64 fn fmt(&self, f: &mut Formatter<'_>) -> core::fmt::Result {
65 f.debug_struct("IntoValues").finish_non_exhaustive()
66 }
67}
68
69impl<K, V> FusedIterator for IntoValues<K, V> {}
70
71impl<K, V> ExactSizeIterator for IntoValues<K, V> {
72 fn len(&self) -> usize {
73 self.iter.len()
74 }
75}
76
77impl<K, V> Default for IntoValues<K, V> {
78 fn default() -> Self {
79 Self {
80 iter: Default::default(),
81 storage: LinearStorage::with_capacity(0),
82 }
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> Send for IntoValues<K, V>
90where
91 K: Send,
92 V: Send,
93{
94}
95
96// SAFETY:
97// - This impl is required because Pos<InUse>, Pos<Stored> allow for conflicting access
98// but this API prevents this.
99unsafe impl<K, V> Sync for IntoValues<K, V>
100where
101 K: Sync,
102 V: Sync,
103{
104}