list_fn/
iter.rs

1use super::*;
2use take_mut::take;
3
4/// Any `&mut Iterator` is a `ListFn<End = Self>`.
5impl<I: Iterator> ListFn for &mut I {
6    type Item = I::Item;
7    type End = Self;
8    /// Converts an iterator into a list.
9    fn next(self) -> ListState<Self> {
10        match self.next() {
11            Option::None => ListState::End(self),
12            Option::Some(first) => ListState::some(first, self),
13        }
14    }
15}
16
17impl<I: Iterator> ResultFn for &mut I {
18    type Result = ();
19    fn result(self) {}
20}
21
22pub struct ListIterator<S: ListFn<End = S>>(S);
23
24impl<S: ListFn<End = S>> Iterator for ListIterator<S> {
25    type Item = S::Item;
26    fn next(&mut self) -> Option<Self::Item> {
27        let mut result = None;
28        take(&mut self.0, |list| match list.next() {
29            ListState::End(end) => end,
30            ListState::Some(some) => {
31                result = Some(some.first);
32                some.next
33            }
34        });
35        result
36    }
37}
38
39/// Note: we can't use the standard std::iter::IntoIterator because it has
40/// a conflicting implementation.
41pub trait Iter: ListFn<End = Self> {
42    /// Converts a list to an iterator.
43    fn iter(self) -> ListIterator<Self> {
44        ListIterator(self)
45    }
46}
47
48impl<S: ListFn<End = Self>> Iter for S {}
49
50pub enum ListIteratorWrap<L: ListFn> {
51    List(L),
52    End(L::End),
53}
54
55impl<L: ListFn> Iterator for ListIteratorWrap<L> {
56    type Item = L::Item;
57    fn next(&mut self) -> Option<Self::Item> {
58        let mut result = None;
59        take(self, |wrap| match wrap {
60            ListIteratorWrap::List(list) => match list.next() {
61                ListState::End(end) => ListIteratorWrap::End(end),
62                ListState::Some(some) => {
63                    result = Some(some.first);
64                    ListIteratorWrap::List(some.next)
65                }
66            },
67            end => end,
68        });
69        result
70    }
71}
72
73pub trait IterWrap: ListFn {
74    fn iter_wrap(self) -> ListIteratorWrap<Self> {
75        ListIteratorWrap::List(self)
76    }
77}
78
79impl<L: ListFn> IterWrap for L {}