Crates.io | function-wrapper |
lib.rs | function-wrapper |
version | 0.1.7 |
source | src |
created_at | 2024-09-04 23:48:25.938474 |
updated_at | 2024-09-28 01:08:16.642391 |
description | Rust attribute macro library that makes it easy to wrap functions in code that runs before and / or after a function executes. |
homepage | |
repository | https://github.com/ChandlerJayCalkins/function-wrapper |
max_upload_size | |
id | 1363988 |
size | 18,278 |
Rust attribute macro library that makes it easy to wrap functions in code that runs before and / or after a function executes.
This function
#[wrap]
fn hello() -> bool
{
println!("Hello there!");
println!("This is some code.");
true
}
which is being wrapped by this attribute
use function_wrapper::WrappedFn;
extern crate proc_macro;
extern crate proc_macro2;
use syn::parse_macro_input;
use quote::quote;
// Adds print statements before and after a function executes.
#[proc_macro_attribute]
pub fn wrap(_: proc_macro::TokenStream, item: proc_macro::TokenStream) -> proc_macro::TokenStream
{
// Parse input as a WrappedFn object from the function-wrapper crate.
let mut function = parse_macro_input!(item as WrappedFn);
// Put a print statement in the code that gets run before the function.
function.set_pre_code(quote!{ println!("Hi at the start :)"); });
// Put a print statement in the code that gets run after the function.
function.set_post_code(quote!{ println!("Hi at the end :)"); });
// Convert the function into a TokenStream and return it.
proc_macro2::TokenStream::from(function).into()
}
will turn into this after being compiled.
fn hello() -> bool
{
println!("Hi at the start :)");
let mut wrapper = ||
{
println!("Hello there!");
println!("This is some code.");
true
};
let result = wrapper();
println!("Hi at the end :)");
result
}
If only pre-code is added, a wrapper closure and extra return expression won't be added since they are unecessary in this case. If only post-code is added, the wrapper closure and return expression will still need to be added.