Skip to main content

dptree/handler/
map.rs

1use super::core::from_fn_with_flow;
2use crate::{
3    di::{Asyncify, Injectable},
4    send::{MaybeSend, MaybeSync},
5    Handler, HandlerDescription, HandlerSignature, Type,
6};
7
8use std::{collections::BTreeSet, iter::FromIterator, ops::ControlFlow, sync::Arc};
9
10/// Constructs a handler that passes a value of a new type further.
11///
12/// The result of invoking `proj` will be added to the container and passed
13/// further in a handler chain.
14///
15/// See also: [`crate::filter_map`].
16#[must_use]
17#[track_caller]
18pub fn map<'a, Projection, Output, NewType, Args, Descr>(
19    proj: Projection,
20) -> Handler<'a, Output, Descr>
21where
22    Asyncify<Projection>: Injectable<NewType, Args> + MaybeSend + MaybeSync + 'a,
23    Output: 'a,
24    Descr: HandlerDescription,
25    NewType: Send + Sync + 'static,
26{
27    map_with_description(Descr::map(), proj)
28}
29
30/// The asynchronous version of [`map`].
31#[must_use]
32#[track_caller]
33pub fn map_async<'a, Projection, Output, NewType, Args, Descr>(
34    proj: Projection,
35) -> Handler<'a, Output, Descr>
36where
37    Projection: Injectable<NewType, Args> + MaybeSend + MaybeSync + 'a,
38    Output: 'a,
39    Descr: HandlerDescription,
40    NewType: Send + Sync + 'static,
41{
42    map_async_with_description(Descr::map_async(), proj)
43}
44
45/// [`map`] with a custom description.
46#[must_use]
47#[track_caller]
48pub fn map_with_description<'a, Projection, Output, NewType, Args, Descr>(
49    description: Descr,
50    proj: Projection,
51) -> Handler<'a, Output, Descr>
52where
53    Asyncify<Projection>: Injectable<NewType, Args> + MaybeSend + MaybeSync + 'a,
54    Output: 'a,
55    Descr: HandlerDescription,
56    NewType: Send + Sync + 'static,
57{
58    map_async_with_description(description, Asyncify(proj))
59}
60
61/// [`map_async`] with a custom description.
62#[must_use]
63#[track_caller]
64pub fn map_async_with_description<'a, Projection, Output, NewType, Args, Descr>(
65    description: Descr,
66    proj: Projection,
67) -> Handler<'a, Output, Descr>
68where
69    Projection: Injectable<NewType, Args> + MaybeSend + MaybeSync + 'a,
70    Output: 'a,
71    Descr: HandlerDescription,
72    NewType: Send + Sync + 'static,
73{
74    let proj = Arc::new(proj);
75
76    from_fn_with_flow(
77        description,
78        move |container, cont| {
79            let proj = Arc::clone(&proj);
80
81            async move {
82                let proj = proj.inject(&container);
83                let res = proj().await;
84                drop(proj);
85
86                let mut intermediate = container.clone();
87                intermediate.insert(res);
88                match cont(intermediate).await {
89                    ControlFlow::Continue(_) => ControlFlow::Continue(container),
90                    ControlFlow::Break(result) => ControlFlow::Break(result),
91                }
92            }
93        },
94        HandlerSignature::Other {
95            obligations: Projection::obligations(),
96            guaranteed_outcomes: BTreeSet::from_iter(vec![Type::of::<NewType>()]),
97            conditional_outcomes: BTreeSet::new(),
98            continues: true,
99        },
100        false,
101    )
102}
103
104#[cfg(test)]
105mod tests {
106    use super::*;
107    use crate::{deps, help_inference};
108
109    crate::cross_test! {
110        async fn test_map() {
111            let value = 123;
112
113            let result = help_inference(map(move || value))
114                .endpoint(move |event: i32| async move {
115                    assert_eq!(event, value);
116                    value
117                })
118                .dispatch(deps![])
119                .await;
120
121            assert_eq!(result.break_value(), Some(value));
122        }
123    }
124}