resiter_dpc_tmp/
while_ok.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<O, E>>` to iter until an error is encountered.
8pub trait WhileOk<O, E>
9{
10    fn while_ok<F>(self, F) -> Result<(), E>
11        where F: FnMut(O) -> ();
12}
13
14impl<I, O, E> WhileOk<O, E> for I
15    where I: Iterator<Item = Result<O, E>>,
16{
17    fn while_ok<F>(self, mut f: F) -> Result<(), E>
18        where F: FnMut(O) -> ()
19    {
20        for res in self {
21            f(res?);
22        }
23        Ok(())
24    }
25}
26
27
28
29#[test]
30fn test_while_ok_ok() {
31    use std::str::FromStr;
32
33    let mut s = 0;
34
35    let res = ["1", "2", "3", "4", "5"]
36        .into_iter()
37        .map(|txt| usize::from_str(txt))
38        .while_ok(|i| s += i);
39
40    assert_eq!(s, 15);
41    assert!(res.is_ok());
42}
43
44#[test]
45fn test_while_ok_err() {
46    use std::str::FromStr;
47
48    let mut s = 0;
49
50    let res = ["1", "2", "a", "4", "5"]
51        .into_iter()
52        .map(|txt| usize::from_str(txt))
53        .while_ok(|i| s += i);
54
55    assert_eq!(s, 3);
56    assert!(res.is_err());
57}