1
use std::cmp::Ordering;
2
use std::marker::PhantomData;
3

            
4
/// A lazy iterator that yields the difference of two sorted sequences. The elements are yielded in sorted order.
5
pub(crate) struct Difference<'a, T, I> {
6
    pub(crate) self_iter: I,
7
    pub(crate) other_iter: I,
8
    pub(crate) other_next: Option<&'a T>,
9
    pub(crate) marker: PhantomData<&'a T>,
10
}
11

            
12
impl<'a, T, I> Iterator for Difference<'a, T, I>
13
where
14
    I: Iterator<Item = &'a T>,
15
    T: Ord + PartialEq,
16
{
17
    type Item = &'a T;
18

            
19
4204
    fn next(&mut self) -> Option<Self::Item> {
20
4204
        if self.other_next.is_none() {
21
2942
            self.other_next = self.other_iter.next();
22
3408
        }
23

            
24
4471
        for self_val in self.self_iter.by_ref() {
25
            loop {
26
5064
                match self.other_next {
27
3469
                    Some(other_val) => {
28
3469
                        match self_val.cmp(other_val) {
29
                            Ordering::Equal => {
30
1250
                                self.other_next = self.other_iter.next();
31
1250
                                break;
32
                            }
33
957
                            Ordering::Greater => self.other_next = self.other_iter.next(),
34
1262
                            Ordering::Less => return Some(self_val), // self_val is smaller, yield it
35
                        }
36
                    }
37
1595
                    None => return Some(self_val), // other is exhausted, yield remaining elements of self
38
                }
39
            }
40
        }
41

            
42
1347
        None
43
4204
    }
44
}