Skip to main content

dptree/handler/
try_map.rs

1use super::core::from_fn_with_flow;
2use crate::{
3    di::{Asyncify, Injectable},
4    send::{MaybeSend, MaybeSync},
5    Fallible, Handler, HandlerDescription, HandlerSignature, Type,
6};
7
8use std::{collections::BTreeSet, iter::FromIterator, ops::ControlFlow, sync::Arc};
9
10/// Constructs a fallible handler that passes a value of a new type further.
11///
12/// Like [`map`](crate::map), the result of invoking `proj` is added to the
13/// container and passed further down the chain, but `proj` returns
14/// [`Result<NewType, E>`]:
15///
16///  - `Ok(v)`: `v` is inserted into the container and the continuation
17///    is called.
18///  - `Err(e)`: the handler short-circuits and returns
19///    [`ControlFlow::Break`] with an error value built from `e`, without
20///    calling the continuation.
21///
22/// The handler `Output` must be fallible (i.e. implement [`Fallible`]); in
23/// practice this means it is a `Result<T, E>`, and `E` is the error type that
24/// `proj` returns on failure.
25///
26/// See also: [`try_filter_map`](crate::try_filter_map).
27#[must_use]
28#[track_caller]
29pub fn try_map<'a, Projection, Output, NewType, Args, Descr>(
30    proj: Projection,
31) -> Handler<'a, Output, Descr>
32where
33    Asyncify<Projection>:
34        Injectable<Result<NewType, Output::Error>, Args> + MaybeSend + MaybeSync + 'a,
35    Output: Fallible + 'a,
36    Output::Error: MaybeSend,
37    Descr: HandlerDescription,
38    NewType: Send + Sync + 'static,
39{
40    try_map_with_description(Descr::try_map(), proj)
41}
42
43/// The asynchronous version of [`try_map`].
44#[must_use]
45#[track_caller]
46pub fn try_map_async<'a, Projection, Output, NewType, Args, Descr>(
47    proj: Projection,
48) -> Handler<'a, Output, Descr>
49where
50    Projection: Injectable<Result<NewType, Output::Error>, Args> + MaybeSend + MaybeSync + 'a,
51    Output: Fallible + 'a,
52    Output::Error: MaybeSend,
53    Descr: HandlerDescription,
54    NewType: Send + Sync + 'static,
55{
56    try_map_async_with_description(Descr::try_map_async(), proj)
57}
58
59/// [`try_map`] with a custom description.
60#[must_use]
61#[track_caller]
62pub fn try_map_with_description<'a, Projection, Output, NewType, Args, Descr>(
63    description: Descr,
64    proj: Projection,
65) -> Handler<'a, Output, Descr>
66where
67    Asyncify<Projection>:
68        Injectable<Result<NewType, Output::Error>, Args> + MaybeSend + MaybeSync + 'a,
69    Output: Fallible + 'a,
70    Output::Error: MaybeSend,
71    NewType: Send + Sync + 'static,
72{
73    try_map_async_with_description(description, Asyncify(proj))
74}
75
76/// [`try_map_async`] with a custom description.
77#[must_use]
78#[track_caller]
79pub fn try_map_async_with_description<'a, Projection, Output, NewType, Args, Descr>(
80    description: Descr,
81    proj: Projection,
82) -> Handler<'a, Output, Descr>
83where
84    Projection: Injectable<Result<NewType, Output::Error>, Args> + MaybeSend + MaybeSync + 'a,
85    Output: Fallible + 'a,
86    Output::Error: MaybeSend,
87    NewType: Send + Sync + 'static,
88{
89    let proj = Arc::new(proj);
90
91    from_fn_with_flow(
92        description,
93        move |container, cont| {
94            let proj = Arc::clone(&proj);
95
96            async move {
97                let proj = proj.inject(&container);
98                let res = proj().await;
99                drop(proj);
100
101                match res {
102                    Ok(new_type) => {
103                        let mut intermediate = container.clone();
104                        intermediate.insert(new_type);
105                        match cont(intermediate).await {
106                            ControlFlow::Continue(_) => ControlFlow::Continue(container),
107                            ControlFlow::Break(result) => ControlFlow::Break(result),
108                        }
109                    }
110                    Err(err) => ControlFlow::Break(Output::from_error(err)),
111                }
112            }
113        },
114        HandlerSignature::Other {
115            obligations: Projection::obligations(),
116            guaranteed_outcomes: BTreeSet::from_iter(vec![Type::of::<NewType>()]),
117            conditional_outcomes: BTreeSet::new(),
118            continues: true,
119        },
120        false,
121    )
122}
123
124#[cfg(test)]
125mod tests {
126    use super::*;
127    use crate::{deps, help_inference};
128
129    type Out = Result<i32, &'static str>;
130
131    crate::cross_test! {
132        async fn ok_inserts_and_continues() {
133            let result = help_inference::<Out>(try_map(move || Ok(123)))
134                .endpoint(move |event: i32| async move {
135                    assert_eq!(event, 123);
136                    Ok(event)
137                })
138                .dispatch(deps![])
139                .await;
140
141            assert_eq!(result.break_value(), Some(Ok(123)));
142        }
143
144        async fn err_short_circuits_past_endpoint() {
145            let result = help_inference::<Out>(try_map(|| Err::<i32, _>("nope")))
146                .endpoint(|| async move { unreachable!() })
147                .dispatch(deps![])
148                .await;
149
150            assert_eq!(result.break_value(), Some(Err("nope")));
151        }
152
153        async fn async_variant() {
154            let result = help_inference::<Out>(try_map_async(move || async move { Ok(123) }))
155                .endpoint(move |event: i32| async move { Ok(event) })
156                .dispatch(deps![])
157                .await;
158
159            assert_eq!(result.break_value(), Some(Ok(123)));
160        }
161    }
162}