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
macro_rules! impl_iter {
    (@item_identity, $i:item) => {
        $i
    };
    ($name:ident, ($($tparm:tt)*), $item:ty, $fun:expr, ($($wh_clause:tt)*)) => {
        impl_iter! {
            @item_identity,
            impl $($tparm)* Iterator for $name $($tparm)* $($wh_clause)* {
                type Item = $item;

                fn next(&mut self) -> Option<Self::Item> {
                    let item = (&mut self.inner).filter_map($fun).next();
                    if item.is_some() {
                        self.len -= 1;
                    }
                    item
                }

                fn count(self) -> usize {
                    self.len()
                }

                fn last(mut self) -> Option<Self::Item> {
                    self.next_back()
                }

                fn size_hint(&self) -> (usize, Option<usize>) {
                    (self.len, Some(self.len))
                }
            }
        }

        impl_iter! {
            @item_identity,
            impl $($tparm)* ExactSizeIterator for $name $($tparm)* $($wh_clause)* {
                fn len(&self) -> usize {
                    self.len
                }
            }
        }

        impl_iter! {
            @item_identity,
            impl $($tparm)* DoubleEndedIterator for $name $($tparm)* $($wh_clause)* {
                fn next_back(&mut self) -> Option<Self::Item> {
                    let item = (&mut self.inner).rev().filter_map($fun).next();
                    if item.is_some() {
                        self.len -= 1;
                    }
                    item
                }
            }
        }
    }
}