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
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
//! Helpers to convert iterators of results into results of collections
//! preserving all errors, instead of just the first as `FromIterator` for
//! `Result` does
use std::iter::FromIterator;

/// A newtype implementing FromIterator to collect into a result preserving all
/// error values, instead of just the first as `FromIterator` for `Result` does
///
/// ```
/// # use gatherr::Gatherr;
/// let v = vec![Ok("a"), Err(1), Ok("b"), Err(2)];
///
/// let Gatherr(result): Gatherr<Vec<&str>, Vec<u32>>
///     = v.into_iter().collect();
///
/// assert_eq!(result, Err(vec![1, 2]));
/// ```
///
/// Using this directly can be awkward due to the necessary additional type
/// annotation. Consider using [the extension trait method](trait.IterExt.html#method.gatherr)
/// or the [freestanding gatherr function](fn.gatherr.html) instead
pub struct Gatherr<T, E>(pub Result<T, E>);

impl<A, B, T: FromIterator<A>, E: FromIterator<B>> FromIterator<Result<A, B>> for Gatherr<T, E> {
    fn from_iter<I: IntoIterator<Item = Result<A, B>>>(iter: I) -> Self {
        let mut iter = iter.into_iter();
        let mut first_err = None;
        let ok = (&mut iter)
            .scan((), |_, i| match i {
                Ok(v) => Some(v),
                Err(e) => {
                    first_err = Some(e);
                    None
                }
            })
            .collect();
        Gatherr(if let Some(first_err) = first_err {
            drop(ok);
            Err(std::iter::once(first_err)
                .chain(iter.filter_map(|r| r.err()))
                .collect())
        } else {
            Ok(ok)
        })
    }
}


/// An extension trait for iterators of `Result`s to easily collect without the
/// extra newtype
pub trait IterExt<A, B>: Iterator<Item = Result<A, B>> + Sized {
    /// Collect all Ok or Err values from this iterator into a single `Result`
    // of collections
    ///
    /// ```
    /// use gatherr::IterExt;
    /// let v = vec![Ok("a"), Err(1), Ok("b"), Err(2)];
    ///
    /// let result: Result<Vec<&str>, Vec<u32>> = v.into_iter().gatherr();
    ///
    /// assert_eq!(result, Err(vec![1, 2]));
    /// ```
    fn gatherr<T: FromIterator<A>, E: FromIterator<B>>(self) -> Result<T, E> {
        let Gatherr(result) = self.collect();
        result
    }
}

impl<A, B, I: Iterator<Item = Result<A, B>> + Sized> IterExt<A, B> for I {}

/// Collect all Ok or Err values from an iterator into a single `Result` of
/// collections
///
/// ```
/// # use gatherr::gatherr;
/// let v = vec![Ok("a"), Err(1), Ok("b"), Err(2)];
///
/// let result: Result<Vec<&str>, Vec<u32>> = gatherr(v);
///
/// assert_eq!(result, Err(vec![1, 2]));
/// ```
pub fn gatherr<
    A,
    B,
    T: FromIterator<A>,
    E: FromIterator<B>,
    I: IntoIterator<Item = Result<A, B>>,
>(
    iter: I,
) -> Result<T, E> {
    let Gatherr(result) = iter.into_iter().collect();
    result
}

#[cfg(test)]
mod test {
    use super::*;
    #[test]
    fn ok_gather() {
        let v: Vec<Result<_, String>> = vec![
            Ok("Hello".to_owned()),
            Ok("World".to_owned()),
            Ok("!".to_owned()),
        ];
        let result: Result<Vec<_>, Vec<_>> = v.into_iter().gatherr();

        assert_eq!(&result.unwrap(), &["Hello", "World", "!"]);
    }
    #[test]
    fn err_gather() {
        let v: Vec<Result<String, _>> = vec![
            Err("Goodbye".to_owned()),
            Err("cruel".to_owned()),
            Err("world".to_owned()),
        ];
        let result: Result<Vec<_>, Vec<_>> = v.into_iter().gatherr();

        assert_eq!(&result.unwrap_err(), &["Goodbye", "cruel", "world"]);
    }
    #[test]
    fn mixed_gather_initial_ok() {
        let v: Vec<Result<String, _>> = vec![
            Ok("Hello".to_owned()),
            Ok("World".to_owned()),
            Err("Goodbye".to_owned()),
            Ok("!".to_owned()),
            Err("cruel".to_owned()),
            Err("world".to_owned()),
        ];
        let result: Result<Vec<_>, Vec<_>> = v.into_iter().gatherr();

        assert_eq!(&result.unwrap_err(), &["Goodbye", "cruel", "world"]);
    }
    #[test]
    fn mixed_gather_initial_err() {
        let v: Vec<Result<String, _>> = vec![
            Err("Goodbye".to_owned()),
            Ok("Hello".to_owned()),
            Err("cruel".to_owned()),
            Err("world".to_owned()),
            Ok("World".to_owned()),
            Ok("!".to_owned()),
        ];
        let result: Result<Vec<_>, Vec<_>> = v.into_iter().gatherr();

        assert_eq!(&result.unwrap_err(), &["Goodbye", "cruel", "world"]);
    }

    #[test]
    fn empty_gather() {
        let result: Result<Vec<String>, Vec<String>> = std::iter::empty().gatherr();
        assert_eq!(result, Ok(Vec::new()));
    }
}