Debian Codegraph @

lib/src/iter_util.rs

raw
1 // Copyright 2025 The Jujutsu Authors
2 //
3 // Licensed under the Apache License, Version 2.0 (the "License");
4 // you may not use this file except in compliance with the License.
5 // You may obtain a copy of the License at
6 //
7 // https://www.apache.org/licenses/LICENSE-2.0
8 //
9 // Unless required by applicable law or agreed to in writing, software
10 // distributed under the License is distributed on an "AS IS" BASIS,
11 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 // See the License for the specific language governing permissions and
13 // limitations under the License.
14
15 //! Iterator helpers.
16
17 /// Returns `Ok(true)` if any element satisfies the fallible predicate,
18 /// `Ok(false)` if none do. Returns `Err` on the first error encountered.
19 pub async fn fallible_any<T, E>(
20 iter: impl IntoIterator<Item = T>,
21 mut predicate: impl AsyncFnMut(T) -> Result<bool, E>,
22 ) -> Result<bool, E> {
23 for item in iter {
24 if predicate(item).await? {
25 return Ok(true);
26 }
27 }
28 Ok(false)
29 }
30
31 /// Returns `Ok(Some(item))` for the first element where the predicate returns
32 /// `Ok(true)`, `Ok(None)` if no element satisfies it, or `Err` on the first
33 /// error.
34 pub async fn fallible_find<T, E>(
35 iter: impl IntoIterator<Item = T>,
36 mut predicate: impl AsyncFnMut(&T) -> Result<bool, E>,
37 ) -> Result<Option<T>, E> {
38 for item in iter {
39 if predicate(&item).await? {
40 return Ok(Some(item));
41 }
42 }
43 Ok(None)
44 }
45
46 /// Returns `Ok(Some(index))` for the first element where the predicate returns
47 /// `Ok(true)`, `Ok(None)` if no element satisfies it, or `Err` on the first
48 /// error.
49 pub async fn fallible_position<T, E>(
50 iter: impl IntoIterator<Item = T>,
51 mut predicate: impl AsyncFnMut(T) -> Result<bool, E>,
52 ) -> Result<Option<usize>, E> {
53 for (index, item) in iter.into_iter().enumerate() {
54 if predicate(item).await? {
55 return Ok(Some(index));
56 }
57 }
58 Ok(None)
59 }