Skip to main content

dptree/handler/
filter_map.rs

1use crate::{
2    di::{Asyncify, Injectable},
3    from_fn_with_description,
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 optionally passes a value of a new type further.
11///
12/// If the `proj` function returns `Some(v)` then `v` will be added to the
13/// container and passed further in a handler chain. If the function returns
14/// `None`, then the handler will return [`ControlFlow::Continue`] with the old
15/// container.
16#[must_use]
17#[track_caller]
18pub fn filter_map<'a, Projection, Output, NewType, Args, Descr>(
19    proj: Projection,
20) -> Handler<'a, Output, Descr>
21where
22    Asyncify<Projection>: Injectable<Option<NewType>, Args> + MaybeSend + MaybeSync + 'a,
23    Output: 'a,
24    Descr: HandlerDescription,
25    NewType: Send + Sync + 'static,
26{
27    filter_map_with_description(Descr::filter_map(), proj)
28}
29
30/// The asynchronous version of [`filter_map`].
31#[must_use]
32#[track_caller]
33pub fn filter_map_async<'a, Projection, Output, NewType, Args, Descr>(
34    proj: Projection,
35) -> Handler<'a, Output, Descr>
36where
37    Projection: Injectable<Option<NewType>, Args> + MaybeSend + MaybeSync + 'a,
38    Output: 'a,
39    Descr: HandlerDescription,
40    NewType: Send + Sync + 'static,
41{
42    filter_map_async_with_description(Descr::filter_map_async(), proj)
43}
44
45/// [`filter_map`] with a custom description.
46#[must_use]
47#[track_caller]
48pub fn filter_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<Option<NewType>, Args> + MaybeSend + MaybeSync + 'a,
54    Output: 'a,
55    NewType: Send + Sync + 'static,
56{
57    filter_map_async_with_description(description, Asyncify(proj))
58}
59
60/// [`filter_map_async`] with a custom description.
61#[must_use]
62#[track_caller]
63pub fn filter_map_async_with_description<'a, Projection, Output, NewType, Args, Descr>(
64    description: Descr,
65    proj: Projection,
66) -> Handler<'a, Output, Descr>
67where
68    Projection: Injectable<Option<NewType>, Args> + MaybeSend + MaybeSync + 'a,
69    Output: 'a,
70    NewType: Send + Sync + 'static,
71{
72    let proj = Arc::new(proj);
73
74    from_fn_with_description(
75        description,
76        move |container, cont| {
77            let proj = Arc::clone(&proj);
78
79            async move {
80                let proj = proj.inject(&container);
81                let res = proj().await;
82                drop(proj);
83
84                match res {
85                    Some(new_type) => {
86                        let mut intermediate = container.clone();
87                        intermediate.insert(new_type);
88                        match cont(intermediate).await {
89                            ControlFlow::Continue(_) => ControlFlow::Continue(container),
90                            ControlFlow::Break(result) => ControlFlow::Break(result),
91                        }
92                    }
93                    None => ControlFlow::Continue(container),
94                }
95            }
96        },
97        HandlerSignature::Other {
98            obligations: Projection::obligations(),
99            guaranteed_outcomes: BTreeSet::from_iter(vec![Type::of::<NewType>()]),
100            conditional_outcomes: BTreeSet::default(),
101            continues: true,
102        },
103    )
104}
105
106#[cfg(test)]
107mod tests {
108    use super::*;
109    use crate::{deps, help_inference};
110
111    crate::cross_test! {
112        async fn test_some() {
113            let value = 123;
114
115            let result = help_inference(filter_map(move || Some(value)))
116                .endpoint(move |event: i32| async move {
117                    assert_eq!(event, value);
118                    value
119                })
120                .dispatch(deps![])
121                .await;
122
123            assert_eq!(result.break_value(), Some(value));
124        }
125
126        async fn test_none() {
127            let result = help_inference(filter_map(|| None::<i32>))
128                .endpoint(|| async move { unreachable!() })
129                .dispatch(deps![])
130                .await;
131
132            assert!(matches!(result, ControlFlow::Continue(deps) if deps.same_types(&crate::deps![])));
133        }
134    }
135}