async_iter_ext/
result.rs

1/// An extension trait for `Result<T, E>` providing asynchronous combinators.
2pub trait AsyncResultTools<T, E> {
3    /// Asynchronously evaluates whether the result is `Ok` and satisfies a given predicate.
4    ///
5    /// If the result is `Ok`, the provided asynchronous predicate `f` is applied to the inner value.
6    /// Returns `true` if the predicate resolves to `true`, otherwise returns `false`.
7    /// If the result is `Err`, returns `false` without calling the predicate.
8    ///
9    /// # Example
10    ///
11    /// ```rust
12    /// use async_iter_ext::AsyncResultTools;
13    /// use async_std::task::block_on;
14    ///
15    /// async fn check_even(n: u32) -> bool {
16    ///   n % 2 == 0
17    /// }
18    ///
19    /// let res: Result<u32, ()> = Ok(4);
20    /// assert!(block_on(async { res.is_ok_and_async(check_even).await }));
21    /// ```
22    #[allow(clippy::wrong_self_convention)]
23    fn is_ok_and_async<F, Fut>(self, f: F) -> impl Future<Output = bool>
24    where
25        F: FnOnce(T) -> Fut,
26        Fut: Future<Output = bool>;
27
28    /// Applies an asynchronous transformation to the `Ok` value, if present.
29    ///
30    /// If the result is `Ok`, the provided asynchronous function `f` is applied to the inner value,
31    /// and the result is wrapped in `Ok`. If the result is `Err`, it is returned unchanged.
32    ///
33    /// # Example
34    ///
35    /// ```rust
36    /// use async_iter_ext::AsyncResultTools;
37    /// use async_std::task::block_on;
38    ///
39    /// async fn double(x: u32) -> u32 {
40    ///   x * 2
41    /// }
42    ///
43    /// let res: Result<u32, &str> = Ok(3);
44    /// let doubled = block_on(async { res.map_async(double).await });
45    /// assert_eq!(doubled, Ok(6));
46    /// ```
47    fn map_async<B, F, Fut>(self, f: F) -> impl Future<Output = Result<B, E>>
48    where
49        F: FnOnce(T) -> Fut,
50        Fut: Future<Output = B>;
51}
52
53impl<T, E> AsyncResultTools<T, E> for Result<T, E> {
54    async fn is_ok_and_async<F, Fut>(self, f: F) -> bool
55    where
56        F: FnOnce(T) -> Fut,
57        Fut: Future<Output = bool>,
58    {
59        if let Ok(x) = self { f(x).await } else { false }
60    }
61
62    async fn map_async<B, F, Fut>(self, f: F) -> Result<B, E>
63    where
64        F: FnOnce(T) -> Fut,
65        Fut: Future<Output = B>,
66    {
67        match self {
68            Ok(x) => Ok(f(x).await),
69            Err(e) => Err(e),
70        }
71    }
72}