sized_chunks/sized_chunk/
iter.rs

1use core::iter::FusedIterator;
2
3use super::Chunk;
4
5/// A consuming iterator over the elements of a `Chunk`.
6pub struct Iter<A, const N: usize> {
7    pub(crate) chunk: Chunk<A, N>,
8}
9
10impl<A, const N: usize> Iterator for Iter<A, N> {
11    type Item = A;
12    fn next(&mut self) -> Option<Self::Item> {
13        if self.chunk.is_empty() {
14            None
15        } else {
16            Some(self.chunk.pop_front())
17        }
18    }
19
20    fn size_hint(&self) -> (usize, Option<usize>) {
21        (self.chunk.len(), Some(self.chunk.len()))
22    }
23}
24
25impl<A, const N: usize> DoubleEndedIterator for Iter<A, N> {
26    fn next_back(&mut self) -> Option<Self::Item> {
27        if self.chunk.is_empty() {
28            None
29        } else {
30            Some(self.chunk.pop_back())
31        }
32    }
33}
34
35impl<A, const N: usize> ExactSizeIterator for Iter<A, N> {}
36
37impl<A, const N: usize> FusedIterator for Iter<A, N> {}
38
39/// A draining iterator over the elements of a `Chunk`.
40///
41/// "Draining" means that as the iterator yields each element, it's removed from
42/// the `Chunk`. When the iterator terminates, the chunk will be empty. This is
43/// different from the consuming iterator `Iter` in that `Iter` will take
44/// ownership of the `Chunk` and discard it when you're done iterating, while
45/// `Drain` leaves you still owning the drained `Chunk`.
46pub struct Drain<'a, A, const N: usize> {
47    pub(crate) chunk: &'a mut Chunk<A, N>,
48}
49
50impl<'a, A, const N: usize> Iterator for Drain<'a, A, N>
51where
52    A: 'a,
53{
54    type Item = A;
55
56    fn next(&mut self) -> Option<Self::Item> {
57        if self.chunk.is_empty() {
58            None
59        } else {
60            Some(self.chunk.pop_front())
61        }
62    }
63
64    fn size_hint(&self) -> (usize, Option<usize>) {
65        (self.chunk.len(), Some(self.chunk.len()))
66    }
67}
68
69impl<'a, A, const N: usize> DoubleEndedIterator for Drain<'a, A, N>
70where
71    A: 'a,
72{
73    fn next_back(&mut self) -> Option<Self::Item> {
74        if self.chunk.is_empty() {
75            None
76        } else {
77            Some(self.chunk.pop_back())
78        }
79    }
80}
81
82impl<'a, A, const N: usize> ExactSizeIterator for Drain<'a, A, N> where A: 'a {}
83
84impl<'a, A, const N: usize> FusedIterator for Drain<'a, A, N> where A: 'a {}