Skip to content

Instantly share code, notes, and snippets.

@vjancik
Created January 17, 2021 13:50
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save vjancik/0ae810289b763e8b717a393ea6525685 to your computer and use it in GitHub Desktop.
Save vjancik/0ae810289b763e8b717a393ea6525685 to your computer and use it in GitHub Desktop.
A rust macro for generating inline functions (useful for inlining async functions)
#![allow(unused_macros)]
macro_rules! with_dollar_sign {
($($body:tt)*) => {
macro_rules! __with_escape { $($body)* }
__with_escape!($);
}
}
macro_rules! inline_fn {
( $func:ident, $( $par_name:ident $(: $par_type:ty )?,)* $func_body:block) => {
paste::paste! {
with_dollar_sign! { ($d:tt) => {
macro_rules! $func {
( $( $par_name = $d [< $par_name _par_val >]:expr ),* ) => {{
$(
let $par_name $(: $par_type)? = $d [< $par_name _par_val >];
)*
$func_body
}}
}
}}
}
};
}
#[cfg(test)]
mod tests {
use tokio::runtime;
inline_fn!(some_func, some_var: &mut u32, some_var2, {
*some_var -= 1;
assert_eq!(*some_var, 4);
assert_eq!(some_var2, 6);
});
#[test]
fn inline_test() {
let mut captured = 5;
some_func!(some_var = &mut captured, some_var2 = 6);
}
inline_fn!(inline_async, {
(async {
println!("Executed asynchronously");
return 0u8
}).await
});
async fn async_routine() -> u8 {
inline_async!()
}
#[test]
fn inline_async_test() {
let runtime = runtime::Builder::new_current_thread().build().unwrap();
runtime.block_on(async_routine());
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment