diff rust/hg-core/src/utils.rs @ 50035:f5b168979626

rust: move `filter_map_results` to public util This is a useful general-purpose function. It will be used in the next changesets.
author Rapha?l Gom?s <rgomes@octobus.net>
date Wed, 11 Jan 2023 17:27:19 +0100
parents 83437ad8fe3d
children a6b8b1ab9116
line wrap: on
line diff
--- a/rust/hg-core/src/utils.rs	Wed Jan 11 15:44:21 2023 +0100
+++ b/rust/hg-core/src/utils.rs	Wed Jan 11 17:27:19 2023 +0100
@@ -477,3 +477,23 @@
         Ok(())
     }
 }
+
+/// Like `Iterator::filter_map`, but over a fallible iterator of `Result`s.
+///
+/// The callback is only called for incoming `Ok` values. Errors are passed
+/// through as-is. In order to let it use the `?` operator the callback is
+/// expected to return a `Result` of `Option`, instead of an `Option` of
+/// `Result`.
+pub fn filter_map_results<'a, I, F, A, B, E>(
+    iter: I,
+    f: F,
+) -> impl Iterator<Item = Result<B, E>> + 'a
+where
+    I: Iterator<Item = Result<A, E>> + 'a,
+    F: Fn(A) -> Result<Option<B>, E> + 'a,
+{
+    iter.filter_map(move |result| match result {
+        Ok(node) => f(node).transpose(),
+        Err(e) => Some(Err(e)),
+    })
+}