Skip to main content

orx_concurrent_option/common_traits/
iter.rs

1use crate::{ConcurrentOption, handle::Handle, states::SOME};
2use core::iter::FusedIterator;
3
4// INTO-ITER
5
6impl<'a, T> IntoIterator for &'a ConcurrentOption<T> {
7    type Item = &'a T;
8    type IntoIter = Iter<'a, T>;
9
10    fn into_iter(self) -> Self::IntoIter {
11        // hold the reservation for the lifetime of the iterator so that a concurrent mutation
12        // cannot race with the borrowed value while the iterator is alive.
13        match self.spin_get_handle(SOME, SOME) {
14            Some(handle) => Iter {
15                maybe: Some(unsafe { (*self.value.get()).assume_init_ref() }),
16                _handle: Some(handle),
17            },
18            None => Iter {
19                maybe: None,
20                _handle: None,
21            },
22        }
23    }
24}
25
26impl<'a, T> IntoIterator for &'a mut ConcurrentOption<T> {
27    type Item = &'a mut T;
28    type IntoIter = IterMut<'a, T>;
29
30    fn into_iter(self) -> Self::IntoIter {
31        self.exclusive_iter_mut()
32    }
33}
34
35impl<T> IntoIterator for ConcurrentOption<T> {
36    type Item = T;
37
38    type IntoIter = core::option::IntoIter<T>;
39
40    fn into_iter(mut self) -> Self::IntoIter {
41        self.exclusive_take().into_iter()
42    }
43}
44
45// ITER
46
47/// Iterator over the `ConcurrentOption` yielding at most one element.
48pub struct Iter<'a, T> {
49    pub(crate) maybe: Option<&'a T>,
50    /// keeps the option reserved for the lifetime of the iterator when constructed safely
51    pub(crate) _handle: Option<Handle<'a>>,
52}
53
54impl<'a, T> Iterator for Iter<'a, T> {
55    type Item = &'a T;
56
57    fn next(&mut self) -> Option<Self::Item> {
58        self.maybe.take()
59    }
60}
61
62impl<T> FusedIterator for Iter<'_, T> {}
63
64impl<T> ExactSizeIterator for Iter<'_, T> {
65    fn len(&self) -> usize {
66        match self.maybe.is_some() {
67            true => 1,
68            false => 0,
69        }
70    }
71}
72
73impl<T> DoubleEndedIterator for Iter<'_, T> {
74    fn next_back(&mut self) -> Option<Self::Item> {
75        self.next()
76    }
77}
78
79// ITER-MUT
80
81/// Mutable iterator over the `ConcurrentOption` yielding at most one element.
82pub struct IterMut<'a, T> {
83    pub(crate) maybe: Option<&'a mut T>,
84}
85
86impl<'a, T> Iterator for IterMut<'a, T> {
87    type Item = &'a mut T;
88
89    fn next(&mut self) -> Option<Self::Item> {
90        self.maybe.take()
91    }
92}
93
94impl<T> FusedIterator for IterMut<'_, T> {}
95
96impl<T> ExactSizeIterator for IterMut<'_, T> {
97    fn len(&self) -> usize {
98        match self.maybe.is_some() {
99            true => 1,
100            false => 0,
101        }
102    }
103}
104
105impl<T> DoubleEndedIterator for IterMut<'_, T> {
106    fn next_back(&mut self) -> Option<Self::Item> {
107        self.next()
108    }
109}