1use futures::future::LocalBoxFuture;
2
3pub trait AsyncHandlerTrait<E> {
10 fn call_mut_boxed(&mut self, e: E) -> LocalBoxFuture<'_, ()>;
11}
12
13impl<E, F> AsyncHandlerTrait<E> for F
14where
15 F: AsyncFnMut(E),
16 E: Clone + 'static,
17{
18 fn call_mut_boxed(&mut self, e: E) -> LocalBoxFuture<'_, ()> {
19 Box::pin(async move { (*self)(e).await })
22 }
23}
24
25pub enum Handler<E> {
27 Sync(Box<dyn FnMut(E)>),
28 Async(Box<dyn AsyncHandlerTrait<E>>),
29}
30
31impl<E> Handler<E>
32where
33 E: Clone + 'static,
34{
35 pub fn new_sync<F>(f: F) -> Handler<E>
36 where
37 F: FnMut(E) + 'static,
38 {
39 Handler::Sync(Box::new(f))
40 }
41
42 pub fn new_sync_option<F>(mut f: F) -> Handler<E>
43 where
44 F: FnMut(E) -> Option<()> + 'static,
45 {
46 Handler::new_sync(move |e| {
47 f(e);
48 })
49 }
50
51 pub fn new_async<F>(f: F) -> Handler<E>
52 where
53 F: AsyncFnMut(E) + 'static,
54 {
55 Handler::Async(Box::new(f))
56 }
57
58 pub fn new_async_option<F>(mut f: F) -> Handler<E>
59 where
60 F: AsyncFnMut(E) -> Option<()> + 'static,
61 {
62 Handler::new_async(async move |e| {
63 f(e).await;
64 })
65 }
66}
67
68#[cfg(test)]
69mod test {
70 use crate::core::Handler;
71 #[test]
72 fn test_define() {
73 let _ = Handler::new_sync(move |v: usize| {
74 println!("{}", v);
75 });
76
77 let _ = Handler::new_async(async move |v: usize| {
78 println!("{}", v);
79 });
80 }
81}