summaryrefslogtreecommitdiffstats
path: root/src/skip.rs
blob: 6c13d5dec62f3120423caffd05041fcffb9c3502 (plain)
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
//
// This Source Code Form is subject to the terms of the Mozilla Public
// License, v. 2.0. If a copy of the MPL was not distributed with this
// file, You can obtain one at http://mozilla.org/MPL/2.0/.
//


pub trait SkipWhileMap<O, E>: Iterator<Item = Result<O, E>> + Sized {

    /// Skip Elements while Ok(true) is returned.
    ///
    /// Same as Iterator::skip_while, but the predicate function is allowed to return an Err(E),
    /// which is then injected into the Iteration.
    fn skip_while_map<F>(self, F) -> SkipWhileMapOk<Self, F, O, E>
    where
        F: FnMut(&O) -> Result<bool, E>;
}

impl<O, E, I> SkipWhileMap<O, E> for I
    where I: Iterator<Item = Result<O, E>> + Sized
{

    fn skip_while_map<F>(self, f: F) -> SkipWhileMapOk<Self, F, O, E>
    where
        F: FnMut(&O) -> Result<bool, E>
    {
        SkipWhileMapOk {
            iter: self,
            func: f,
        }
    }
}

#[must_use = "iterator adaptors are lazy and do nothing unless consumed"]
pub struct SkipWhileMapOk<I, F, O, E>
    where
        F: FnMut(&O) -> Result<bool, E>,
        I: Iterator<Item = Result<O, E>> + Sized
{
    iter: I,
    func: F
}


impl<I, O, E, F> Iterator for SkipWhileMapOk<I, F, O, E>
where
    I: Iterator<Item = Result<O, E>>,
    F: FnMut(&O) -> Result<bool, E>,
{
    type Item = Result<O, E>;

    fn next(&mut self) -> Option<Self::Item> {
        loop {
            match self.iter.next() {
                Some(Ok(x)) => {
                    match (self.func)(&x) {
                        Ok(true) => return Some(Ok(x)),
                        Ok(false) => continue,
                        Err(e) => return Some(Err(e)),
                    }
                }
                Some(Err(e)) => return Some(Err(e)),
                None => return None,
            }
        }
    }

    #[inline]
    fn size_hint(&self) -> (usize, Option<usize>) {
        self.iter.size_hint()
    }
}