exotic_iter/
alternate.rs

1/// An iterator that iterates over two iterators alternately.
2#[derive(Clone, Debug)]
3#[must_use = "iterators are lazy and do nothing unless consumed"]
4pub struct Alternate<A, B> {
5    a: A,
6    b: B,
7    odd: bool,
8    done: bool,
9}
10
11impl<
12    A: Iterator<Item = T>, 
13    B: Iterator<Item = T>, 
14    T
15    > Alternate<A, B> {
16    pub(crate) fn new(a: A, b: B) -> Self {
17        Self {
18            a,
19            b,
20            odd: false,
21            done: false,
22        }
23    }
24}
25
26impl<A: Iterator<Item = T>, B: Iterator<Item = T>, T> Iterator for Alternate<A, B> {
27    type Item = T;
28    fn next(&mut self) -> Option<Self::Item> {
29        if self.done { return None }
30
31        let item = if self.odd {
32            self.b.next()
33        } else {
34            self.a.next()
35        };
36
37        if item.is_none() {
38            self.done = true;
39        }
40        
41        self.odd = !self.odd;
42        item
43    }
44}