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
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
//
// 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/.
//

/// Extension for `Iterator<Item = Result<O, E>>` to filter the Ok(_) and leaving the Err(_) as
/// is, but allowing the filter to return a `Result<bool, E>` itself
pub trait TryFilter<O, E>: Sized {
    /// Filters every `Ok`-value with a function that can return an Err.
    /// Useful when the filter condition uses functions that can fail.
    ///
    ///```
    /// use resiter::try_filter::TryFilter;
    /// use std::str::FromStr;
    ///
    /// let v = ["1", "2", "4", "a", "5"]
    ///     .iter()
    ///     .map(Ok)
    ///     .try_filter_ok(|e| usize::from_str(e).map(|n| n < 3))
    ///     .collect::<Vec<Result<_, _>>>();
    ///
    /// assert_eq!(v.len(), 3);
    /// assert_eq!(v.iter().filter(|x| x.is_ok()).count(), 2);
    /// assert_eq!(v.iter().filter(|x| x.is_err()).count(), 1);
    ///```
    fn try_filter_ok<F>(self, _: F) -> TryFilterOk<Self, F>
    where
        F: FnMut(&O) -> Result<bool, E>;

    /// Filters every `Err`-value with a function that can return an Err.
    /// Useful when the filter condition uses functions that can fail.
    ///
    /// ```
    /// use resiter::try_filter::TryFilter;
    /// use std::num::ParseIntError;
    /// use std::str::FromStr;
    ///
    /// let v = ["1", "2", "4", "a", "5"]
    ///     .iter()
    ///     .map(|txt| usize::from_str(txt))
    ///     .try_filter_err(|_:&ParseIntError| Ok(false))
    ///     .collect::<Vec<Result<_, _>>>();
    ///
    /// assert_eq!(v.iter().filter(|x| x.is_ok()).count(), 4);
    /// assert_eq!(v.iter().filter(|x| x.is_err()).count(), 0);
    /// ```
    fn try_filter_err<F>(self, _: F) -> TryFilterErr<Self, F>
    where
        F: FnMut(&E) -> Result<bool, E>;
}

impl<I, O, E> TryFilter<O, E> for I
where
    I: Iterator<Item = Result<O, E>> + Sized,
{
    #[inline]
    fn try_filter_ok<F>(self, f: F) -> TryFilterOk<Self, F>
    where
        F: FnMut(&O) -> Result<bool, E>,
    {
        TryFilterOk { iter: self, f }
    }

    #[inline]
    fn try_filter_err<F>(self, f: F) -> TryFilterErr<Self, F>
    where
        F: FnMut(&E) -> Result<bool, E>,
    {
        TryFilterErr { iter: self, f }
    }
}

#[must_use = "iterator adaptors are lazy and do nothing unless consumed"]
pub struct TryFilterOk<I, F> {
    iter: I,
    f: F,
}

#[must_use = "iterator adaptors are lazy and do nothing unless consumed"]
pub struct TryFilterErr<I, F> {
    iter: I,
    f: F,
}

impl<I, O, E, F> Iterator for TryFilterOk<I, F>
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 {
            return match self.iter.next() {
                Some(Ok(x)) => match (self.f)(&x) {
                    Ok(true) => Some(Ok(x)),
                    Ok(false) => continue,
                    Err(e) => Some(Err(e)),
                },
                other => other,
            };
        }
    }

    #[inline]
    fn size_hint(&self) -> (usize, Option<usize>) {
        let hint_sup = self.iter.size_hint().1;
        (0, hint_sup)
    }
}

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

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

    #[inline]
    fn size_hint(&self) -> (usize, Option<usize>) {
        let hint_sup = self.iter.size_hint().1;
        (0, hint_sup)
    }
}