async_func/macro.rs
1/// Creates an asynchronous function that takes a closure with parameters and executes it asynchronously.
2///
3/// This macro generates an asynchronous closure that captures external variables by cloning them, and
4/// allows the closure to be invoked with the specified parameters. The body of the closure is executed
5/// inside an asynchronous block.
6///
7/// # Parameters
8/// - `$($var:ident),*` : A list of variables from the outer scope to be captured and cloned inside the closure.
9/// - `$($closure_param:ident),*` : A list of parameters for the closure. These parameters are used when calling the closure.
10/// - `{ $($closure_body:tt)* }` : The body of the closure that is executed asynchronously.
11///
12/// # Returns
13/// A closure that takes the specified parameters and returns a `Pin<Box<dyn Future<Output = ()> + Send>>`
14/// which is an asynchronous task that can be awaited.
15///
16/// This macro allows you to encapsulate external state (captured via cloning) and run an asynchronous
17/// task with a specified closure.
18#[macro_export]
19macro_rules! async_func {
20 ($($var:ident),*, { $($closure_body:tt)* }) => {
21 || {
22 #[allow(unused_parens)]
23 let ($($var),*) = ($($var.clone()),*);
24 async move {
25 $($closure_body)*
26 }
27 }
28 };
29
30 ($($var:ident),*, |$($closure_param:ident),*| { $($closure_body:tt)* }) => {
31 move |$($closure_param),*| {
32 #[allow(unused_parens)]
33 let ($($var),*) = ($($var.clone()),*);
34 async move {
35 $($closure_body)*
36 }
37 }
38 };
39}