bidir_iter/
iterate.rs

1use crate::bidir_iterator::BidirIterator;
2
3pub trait BidirIterate {
4    type Item;
5    type BidirIter: BidirIterator<Item = Self::Item>;
6
7    fn bidir_iter(&self) -> Self::BidirIter;
8}
9
10pub struct BiIter<'a, T> {
11    next: usize,
12    slice: &'a [T],
13}
14
15impl<'a, T> BidirIterator for BiIter<'a, T> {
16    type Item = &'a T;
17    fn next(&mut self) -> Option<&'a T> {
18        let x = self.slice.get(self.next);
19        self.next += 1;
20        x
21    }
22
23    fn prev(&mut self) -> Option<&'a T> {
24        if self.next <= 1 {
25            self.next = 0;
26            None
27        } else {
28            self.next -= 1;
29            self.slice.get(self.next - 1)
30        }
31    }
32}
33
34impl<'a, T> BidirIterate for &'a [T] {
35    type Item = &'a T;
36    type BidirIter = BiIter<'a, T>;
37
38    fn bidir_iter(&self) -> Self::BidirIter {
39        BiIter {
40            next: 0,
41            slice: self,
42        }
43    }
44}