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
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
pub trait TryToNext: Sized {
    fn try_to_next(&self) -> Option<Self>;
}

pub struct Gamo<T> {
    current: Option<T>,
    end: T,
    inclusive: bool,
}

impl<T: TryToNext> Gamo<T> {
    pub fn new(start: T, end: T) -> Self {
        Self {
            current: Some(start),
            end,
            inclusive: false,
        }
    }
    pub fn new_inclusive(start: T, end: T) -> Self {
        Self {
            current: Some(start),
            end,
            inclusive: true,
        }
    }
}

impl<T> Iterator for Gamo<T>
where
    T: TryToNext + PartialOrd,
{
    type Item = T;

    fn next(&mut self) -> Option<Self::Item> {
        let Some(v) = self.current.take() else {
            return None;
        };

        if v < self.end || (self.inclusive && v == self.end) {
            self.current = v.try_to_next();
            Some(v)
        } else {
            None
        }
    }
}

#[cfg(test)]
mod tests {
    use super::{Gamo, TryToNext};

    #[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord)]
    struct TimeSlot(usize);

    impl TryToNext for TimeSlot {
        fn try_to_next(&self) -> Option<Self> {
            Some(Self(self.0 + 1))
        }
    }

    #[test]
    fn test_gamo() {
        let mut r = Gamo::new(TimeSlot(0), TimeSlot(5));
        assert_eq!(r.next(), Some(TimeSlot(0)));
        assert_eq!(r.next(), Some(TimeSlot(1)));
        assert_eq!(r.next(), Some(TimeSlot(2)));
        assert_eq!(r.next(), Some(TimeSlot(3)));
        assert_eq!(r.next(), Some(TimeSlot(4)));
        assert_eq!(r.next(), None);

        let mut r = Gamo::new(TimeSlot(5), TimeSlot(5));
        assert_eq!(r.next(), None);

        let mut r = Gamo::new(TimeSlot(5), TimeSlot(4));
        assert_eq!(r.next(), None);
    }

    #[test]
    fn test_gamo_inclusive() {
        let mut r = Gamo::new_inclusive(TimeSlot(0), TimeSlot(5));
        assert_eq!(r.next(), Some(TimeSlot(0)));
        assert_eq!(r.next(), Some(TimeSlot(1)));
        assert_eq!(r.next(), Some(TimeSlot(2)));
        assert_eq!(r.next(), Some(TimeSlot(3)));
        assert_eq!(r.next(), Some(TimeSlot(4)));
        assert_eq!(r.next(), Some(TimeSlot(5)));
        assert_eq!(r.next(), None);

        let mut r = Gamo::new_inclusive(TimeSlot(5), TimeSlot(5));
        assert_eq!(r.next(), Some(TimeSlot(5)));
        assert_eq!(r.next(), None);

        let mut r = Gamo::new(TimeSlot(5), TimeSlot(4));
        assert_eq!(r.next(), None);
    }
}