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
#[must_use = "iterator adaptors are lazy and do nothing unless consumed"]
pub struct UnwrapWith<I, O, E, F>(I, F)
where I: Iterator<Item = Result<O, E>>,
F: FnMut(E) -> Option<O>;
impl<I, O, E, F> Iterator for UnwrapWith<I, O, E, F>
where I: Iterator<Item = Result<O, E>>,
F: FnMut(E) -> Option<O>
{
type Item = O;
fn next(&mut self) -> Option<Self::Item> {
while let Some(o) = self.0.next() {
match o {
Ok(t) => return Some(t),
Err(e) => if let Some(t) = (self.1)(e) {
return Some(t);
},
}
}
None
}
}
pub trait UnwrapWithExt<I, O, E, F>
where I: Iterator<Item = Result<O, E>>,
F: FnMut(E) -> Option<O>
{
fn unwrap_with(self, F) -> UnwrapWith<I, O, E, F>;
}
impl<I, O, E, F> UnwrapWithExt<I, O, E, F> for I
where I: Iterator<Item = Result<O, E>>,
F: FnMut(E) -> Option<O>
{
fn unwrap_with(self, f: F) -> UnwrapWith<I, O, E, F> {
UnwrapWith(self, f)
}
}
#[test]
fn test_compile_1() {
use std::str::FromStr;
let _ : Vec<usize> = ["1", "2", "3", "4", "5"]
.into_iter()
.map(|e| usize::from_str(e))
.unwrap_with(|_| None)
.collect();
}