stele/append/
iter.rs

1use super::reader::ReadHandle;
2
3///An iterator that yields items by reference
4#[derive(Debug)]
5pub struct RefIterator<'rh, T> {
6    handle: &'rh ReadHandle<T>,
7    pos: usize,
8    len: usize,
9}
10
11impl<'rh, T> RefIterator<'rh, T> {
12    ///Creates a new [`RefIterator`], borrowing the handle until dropped
13    #[must_use]
14    pub fn new(handle: &'rh ReadHandle<T>) -> Self {
15        RefIterator {
16            handle,
17            pos: 0,
18            len: handle.len(),
19        }
20    }
21}
22
23impl<'rh, T> Iterator for RefIterator<'rh, T> {
24    type Item = &'rh T;
25
26    fn next(&mut self) -> Option<Self::Item> {
27        (self.len > self.pos).then(|| {
28            self.pos += 1;
29            self.handle.read(self.pos - 1)
30        })
31    }
32}
33
34///An iterator that yields items by value if the type implements copy
35#[derive(Debug)]
36pub struct CopyIterator<T: Copy> {
37    handle: ReadHandle<T>,
38    pos: usize,
39    len: usize,
40}
41
42impl<T: Copy> CopyIterator<T> {
43    ///Creates a new [`CopyIterator`], consuming the [`ReadHandle`]
44    #[must_use]
45    pub fn new(handle: ReadHandle<T>) -> Self {
46        let len = handle.len();
47        Self {
48            handle,
49            pos: 0,
50            len,
51        }
52    }
53}
54
55impl<T: Copy> Iterator for CopyIterator<T> {
56    type Item = T;
57
58    fn next(&mut self) -> Option<Self::Item> {
59        (self.len > self.pos).then(|| {
60            self.pos += 1;
61            self.handle.get(self.pos - 1)
62        })
63    }
64}