Skip to main content

tagged_vec/
index_iterator.rs

1/// An iterator over the indices of a `TaggedVec`.
2pub struct IndexIterator<Index> {
3    start_inclusive: usize,
4    end_exclusive: usize,
5    marker: std::marker::PhantomData<Index>,
6}
7
8impl<Index> IndexIterator<Index> {
9    /// Creates a new `IndexIterator` for the given range.
10    pub fn new(start_inclusive: usize, end_exclusive: usize) -> Self {
11        Self {
12            start_inclusive,
13            end_exclusive,
14            marker: std::marker::PhantomData,
15        }
16    }
17}
18
19impl<Index> Iterator for IndexIterator<Index>
20where
21    Index: From<usize>,
22{
23    type Item = Index;
24
25    fn next(&mut self) -> Option<Self::Item> {
26        if self.start_inclusive < self.end_exclusive {
27            let index = self.start_inclusive;
28            self.start_inclusive += 1;
29            Some(Index::from(index))
30        } else {
31            None
32        }
33    }
34
35    fn size_hint(&self) -> (usize, Option<usize>) {
36        let len = self.end_exclusive - self.start_inclusive;
37        (len, Some(len))
38    }
39}
40
41impl<Index> DoubleEndedIterator for IndexIterator<Index>
42where
43    Index: From<usize>,
44{
45    fn next_back(&mut self) -> Option<Self::Item> {
46        if self.start_inclusive < self.end_exclusive {
47            self.end_exclusive -= 1;
48            Some(Index::from(self.end_exclusive))
49        } else {
50            None
51        }
52    }
53}
54
55impl<Index> ExactSizeIterator for IndexIterator<Index> where Index: From<usize> {}