Skip to main content

dptree/handler/
filter.rs

1use crate::{
2    di::{Asyncify, Injectable},
3    from_fn_with_description,
4    handler::core::Handler,
5    send::{MaybeSend, MaybeSync},
6    HandlerDescription, HandlerSignature,
7};
8
9use std::{collections::BTreeSet, ops::ControlFlow, sync::Arc};
10
11/// Constructs a handler that filters input with the predicate `pred`.
12///
13/// `pred` has an access to all values that are stored in the input container.
14/// If it returns `true`, a continuation of the handler will be called,
15/// otherwise the handler returns [`ControlFlow::Continue`].
16#[must_use]
17#[track_caller]
18pub fn filter<'a, Pred, Output, FnArgs, Descr>(pred: Pred) -> Handler<'a, Output, Descr>
19where
20    Asyncify<Pred>: Injectable<bool, FnArgs> + MaybeSend + MaybeSync + 'a,
21    Output: 'a,
22    Descr: HandlerDescription,
23{
24    filter_with_description(Descr::filter(), pred)
25}
26
27/// The asynchronous version of [`filter`].
28#[must_use]
29#[track_caller]
30pub fn filter_async<'a, Pred, Output, FnArgs, Descr>(pred: Pred) -> Handler<'a, Output, Descr>
31where
32    Pred: Injectable<bool, FnArgs> + MaybeSend + MaybeSync + 'a,
33    Output: 'a,
34    Descr: HandlerDescription,
35{
36    filter_async_with_description(Descr::filter_async(), pred)
37}
38
39/// [`filter`] with a custom description.
40#[must_use]
41#[track_caller]
42pub fn filter_with_description<'a, Pred, Output, FnArgs, Descr>(
43    description: Descr,
44    pred: Pred,
45) -> Handler<'a, Output, Descr>
46where
47    Asyncify<Pred>: Injectable<bool, FnArgs> + MaybeSend + MaybeSync + 'a,
48    Output: 'a,
49{
50    filter_async_with_description(description, Asyncify(pred))
51}
52
53/// [`filter_async`] with a custom description.
54#[must_use]
55#[track_caller]
56pub fn filter_async_with_description<'a, Pred, Output, FnArgs, Descr>(
57    description: Descr,
58    pred: Pred,
59) -> Handler<'a, Output, Descr>
60where
61    Pred: Injectable<bool, FnArgs> + MaybeSend + MaybeSync + 'a,
62    Output: 'a,
63{
64    let pred = Arc::new(pred);
65
66    from_fn_with_description(
67        description,
68        move |event, cont| {
69            let pred = Arc::clone(&pred);
70
71            async move {
72                let pred = pred.inject(&event);
73                let cond = pred().await;
74                drop(pred);
75
76                if cond {
77                    cont(event).await
78                } else {
79                    ControlFlow::Continue(event)
80                }
81            }
82        },
83        HandlerSignature::Other {
84            obligations: Pred::obligations(),
85            guaranteed_outcomes: BTreeSet::default(),
86            conditional_outcomes: BTreeSet::default(),
87            continues: true,
88        },
89    )
90}
91
92#[cfg(test)]
93mod tests {
94    use super::*;
95    use crate::{deps, help_inference};
96
97    crate::cross_test! {
98        async fn test_filter() {
99            let input_value = 123;
100            let input = deps![input_value];
101            let output = 7;
102
103            let result = help_inference(filter_async(move |event: i32| async move {
104                assert_eq!(event, input_value);
105                true
106            }))
107            .endpoint(move |event: i32| async move {
108                assert_eq!(event, input_value);
109                output
110            })
111            .dispatch(input)
112            .await;
113
114            assert_eq!(result.break_value(), Some(output));
115        }
116
117        async fn test_and_then_filter() {
118            let input = 123;
119            let output = 7;
120
121            let result = help_inference(filter(move |event: i32| {
122                assert_eq!(event, input);
123                true
124            }))
125            .chain(
126                filter_async(move |event: i32| async move {
127                    assert_eq!(event, input);
128                    true
129                })
130                .endpoint(move |event: i32| async move {
131                    assert_eq!(event, input);
132                    output
133                }),
134            )
135            .dispatch(deps![input])
136            .await;
137
138            assert_eq!(result.break_value(), Some(output));
139        }
140    }
141}