orx_split_vec/common_traits/iterator/
iter.rs

1use super::reductions;
2use crate::{fragment::fragment_struct::Fragment, Growth, SplitVec};
3use core::iter::FusedIterator;
4
5impl<'a, T, G: Growth> IntoIterator for &'a SplitVec<T, G> {
6    type Item = &'a T;
7    type IntoIter = Iter<'a, T>;
8
9    fn into_iter(self) -> Self::IntoIter {
10        Self::IntoIter::new(&self.fragments)
11    }
12}
13
14/// Iterator over the `SplitVec`.
15///
16/// This struct is created by `SplitVec::iter()` method.
17#[derive(Debug)]
18#[must_use = "iterators are lazy and do nothing unless consumed"]
19pub struct Iter<'a, T> {
20    outer: core::slice::Iter<'a, Fragment<T>>,
21    inner: core::slice::Iter<'a, T>,
22}
23
24impl<'a, T> Iter<'a, T> {
25    pub(crate) fn new(fragments: &'a [Fragment<T>]) -> Self {
26        let mut outer = fragments.iter();
27        let inner = outer.next().map(|x| x.iter()).unwrap_or([].iter());
28        Self { outer, inner }
29    }
30
31    fn next_fragment(&mut self) -> Option<&'a T> {
32        match self.outer.next() {
33            Some(f) => {
34                self.inner = f.iter();
35                self.next()
36            }
37            None => None,
38        }
39    }
40}
41
42impl<T> Clone for Iter<'_, T> {
43    fn clone(&self) -> Self {
44        Self {
45            outer: self.outer.clone(),
46            inner: self.inner.clone(),
47        }
48    }
49}
50
51impl<'a, T> Iterator for Iter<'a, T> {
52    type Item = &'a T;
53
54    #[inline(always)]
55    fn next(&mut self) -> Option<Self::Item> {
56        let next_element = self.inner.next();
57        if next_element.is_some() {
58            next_element
59        } else {
60            self.next_fragment()
61        }
62    }
63
64    // reductions
65    fn all<F>(&mut self, f: F) -> bool
66    where
67        Self: Sized,
68        F: FnMut(Self::Item) -> bool,
69    {
70        reductions::all(&mut self.outer, &mut self.inner, f)
71    }
72
73    fn any<F>(&mut self, f: F) -> bool
74    where
75        Self: Sized,
76        F: FnMut(Self::Item) -> bool,
77    {
78        reductions::any(&mut self.outer, &mut self.inner, f)
79    }
80
81    fn fold<B, F>(mut self, init: B, f: F) -> B
82    where
83        Self: Sized,
84        F: FnMut(B, Self::Item) -> B,
85    {
86        reductions::fold(&mut self.outer, &mut self.inner, init, f)
87    }
88}
89
90impl<T> FusedIterator for Iter<'_, T> {}