resiter_dpc_tmp/
unwrap.rs

1//
2// This Source Code Form is subject to the terms of the Mozilla Public
3// License, v. 2.0. If a copy of the MPL was not distributed with this
4// file, You can obtain one at http://mozilla.org/MPL/2.0/.
5//
6
7/// Extension trait for `Iterator<Item = Result<T, E>>` to unwrap everything.
8///
9/// Errors can be unwraped as well. If the closure `F` returns `Some(O)`, that `O` will be inserted
10/// instead of the `E` into the resulting iterator.
11/// If the closure returns `None`, the error will be dropped (equally to
12/// `iter.filter_map(Result::ok)`.
13///
14#[must_use = "iterator adaptors are lazy and do nothing unless consumed"]
15pub struct UnwrapWith<I, O, E, F>(I, F)
16    where I: Iterator<Item = Result<O, E>>,
17          F: FnMut(E) -> Option<O>;
18
19impl<I, O, E, F> Iterator for UnwrapWith<I, O, E, F>
20    where I: Iterator<Item = Result<O, E>>,
21          F: FnMut(E) -> Option<O>
22{
23    type Item = O;
24
25    fn next(&mut self) -> Option<Self::Item> {
26        while let Some(o) = self.0.next() {
27            match o {
28                Ok(t)  => return Some(t),
29                Err(e) => if let Some(t) = (self.1)(e) {
30                    return Some(t);
31                },
32            }
33        }
34
35        None
36    }
37}
38
39pub trait UnwrapWithExt<I, O, E, F>
40    where I: Iterator<Item = Result<O, E>>,
41          F: FnMut(E) -> Option<O>
42{
43    fn unwrap_with(self, F) -> UnwrapWith<I, O, E, F>;
44}
45
46impl<I, O, E, F> UnwrapWithExt<I, O, E, F> for I
47    where I: Iterator<Item = Result<O, E>>,
48          F: FnMut(E) -> Option<O>
49{
50    fn unwrap_with(self, f: F) -> UnwrapWith<I, O, E, F> {
51        UnwrapWith(self, f)
52    }
53}
54
55#[test]
56fn test_compile_1() {
57    use std::str::FromStr;
58
59    let _ : Vec<usize> = ["1", "2", "3", "4", "5"]
60        .into_iter()
61        .map(|e| usize::from_str(e))
62        .unwrap_with(|_| None) // ignore errors
63        .collect();
64}
65