1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
use crate::{
di::{Asyncify, Injectable},
from_fn_with_description,
handler::core::Handler,
HandlerDescription,
};
use std::{ops::ControlFlow, sync::Arc};
#[must_use]
#[track_caller]
pub fn filter<'a, Pred, Input, Output, FnArgs, Descr>(
pred: Pred,
) -> Handler<'a, Input, Output, Descr>
where
Asyncify<Pred>: Injectable<Input, bool, FnArgs> + Send + Sync + 'a,
Input: Send + 'a,
Output: 'a,
Descr: HandlerDescription,
{
filter_with_description(Descr::filter(), pred)
}
#[must_use]
#[track_caller]
pub fn filter_async<'a, Pred, Input, Output, FnArgs, Descr>(
pred: Pred,
) -> Handler<'a, Input, Output, Descr>
where
Pred: Injectable<Input, bool, FnArgs> + Send + Sync + 'a,
Input: Send + 'a,
Output: 'a,
Descr: HandlerDescription,
{
filter_async_with_description(Descr::filter_async(), pred)
}
#[must_use]
pub fn filter_with_description<'a, Pred, Input, Output, FnArgs, Descr>(
description: Descr,
pred: Pred,
) -> Handler<'a, Input, Output, Descr>
where
Asyncify<Pred>: Injectable<Input, bool, FnArgs> + Send + Sync + 'a,
Input: Send + 'a,
Output: 'a,
{
filter_async_with_description(description, Asyncify(pred))
}
#[must_use]
pub fn filter_async_with_description<'a, Pred, Input, Output, FnArgs, Descr>(
description: Descr,
pred: Pred,
) -> Handler<'a, Input, Output, Descr>
where
Pred: Injectable<Input, bool, FnArgs> + Send + Sync + 'a,
Input: Send + 'a,
Output: 'a,
{
let pred = Arc::new(pred);
from_fn_with_description(description, move |event, cont| {
let pred = Arc::clone(&pred);
async move {
let pred = pred.inject(&event);
let cond = pred().await;
drop(pred);
if cond {
cont(event).await
} else {
ControlFlow::Continue(event)
}
}
})
}
#[cfg(test)]
mod tests {
use super::*;
use crate::{deps, help_inference};
#[tokio::test]
async fn test_filter() {
let input_value = 123;
let input = deps![input_value];
let output = 7;
let result = help_inference(filter_async(move |event: i32| async move {
assert_eq!(event, input_value);
true
}))
.endpoint(move |event: i32| async move {
assert_eq!(event, input_value);
output
})
.dispatch(input)
.await;
assert!(result == ControlFlow::Break(output));
}
#[tokio::test]
async fn test_and_then_filter() {
let input = 123;
let output = 7;
let result = help_inference(filter(move |event: i32| {
assert_eq!(event, input);
true
}))
.chain(
filter_async(move |event: i32| async move {
assert_eq!(event, input);
true
})
.endpoint(move |event: i32| async move {
assert_eq!(event, input);
output
}),
)
.dispatch(deps![input])
.await;
assert!(result == ControlFlow::Break(output));
}
}