rs_matter/utils/iter.rs
1/*
2 *
3 * Copyright (c) 2024 Project CHIP Authors
4 *
5 * Licensed under the Apache License, Version 2.0 (the "License");
6 * you may not use this file except in compliance with the License.
7 * You may obtain a copy of the License at
8 *
9 * http://www.apache.org/licenses/LICENSE-2.0
10 *
11 * Unless required by applicable law or agreed to in writing, software
12 * distributed under the License is distributed on an "AS IS" BASIS,
13 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14 * See the License for the specific language governing permissions and
15 * limitations under the License.
16 */
17
18/// An extension trait for `Iterator` implementing several utility methods.
19pub trait TryFindIterator<T, E>: Iterator<Item = Result<T, E>> + Sized {
20 /// Find the first element that satisfies the supplied `predicate`.
21 ///
22 /// Method name is `do_try_find` to avoid collissions with `Iterator::try_find`
23 /// once it gets stabilized.
24 fn do_try_find<P>(self, mut predicate: P) -> Result<Option<T>, E>
25 where
26 P: FnMut(&T) -> Result<bool, E>,
27 {
28 for val in self {
29 let val = val?;
30
31 let result = predicate(&val);
32 match result {
33 Ok(matches) => {
34 if matches {
35 return Ok(Some(val));
36 }
37 }
38 Err(err) => {
39 return Err(err);
40 }
41 }
42 }
43
44 Ok(None)
45 }
46}
47
48impl<T, I, E> TryFindIterator<T, E> for I where I: Iterator<Item = Result<T, E>> {}