aboutsummaryrefslogtreecommitdiff
path: root/src/iter.rs
blob: 650dceb178da4ea07841dfeedd7e4b4b8977beed (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
use std::fmt::Debug;
use std::iter::Peekable;

pub trait IteratorExt: Sized + Iterator
{
    /// Returns an iterator over overlapping item tuples.
    fn windows(self) -> Windows<Self>;
}

impl<Iter: Iterator> IteratorExt for Iter
where
    Iter::Item: Clone,
{
    fn windows(self) -> Windows<Self>
    {
        Windows {
            iter: self.peekable(),
        }
    }
}

pub struct Windows<Iter: Iterator>
{
    iter: Peekable<Iter>,
}

impl<Iter: Iterator> Iterator for Windows<Iter>
where
    Iter::Item: Clone + Debug,
{
    type Item = (Iter::Item, Option<Iter::Item>);

    fn next(&mut self) -> Option<Self::Item>
    {
        let opt_first = self.iter.next();
        let opt_second = self.iter.peek();

        let Some(first) = opt_first else {
            return None;
        };

        Some((first, opt_second.cloned()))
    }
}

#[cfg(test)]
mod tests
{
    use pretty_assertions::assert_eq;

    use super::*;

    #[test]
    fn windows_works()
    {
        let mut windows = (0..6).windows();

        assert_eq!(windows.next(), Some((0, Some(1))));
        assert_eq!(windows.next(), Some((1, Some(2))));
        assert_eq!(windows.next(), Some((2, Some(3))));
        assert_eq!(windows.next(), Some((3, Some(4))));
        assert_eq!(windows.next(), Some((4, Some(5))));
        assert_eq!(windows.next(), Some((5, None)));
    }
}