Expand description
§Context Manager
Library offering an easy access Python like decorators in rust
Via this library we can easily alter the content of a defined function, by injecting code to be executed before/after the original function, without altering the original function itself.
For example, let’s assume that we are interested on logging the duration of the execution of a function.
fn function_to_be_decorated() -> usize {
do_something_expensive()
}
In order to achieve so we would need to manually modify it similarly to
fn function_to_be_decorated() -> usize {
let start = std::time::Instant::now();
let return_value = do_something_expensive();
println!("Duration of function_to_be_decorated is: {}ms", start.elapsed().as_millis());
return_value
}
As far as this could be very simple, it is tedious and requires to actually modify the original function. While having a simple decorator that would do it for us would be much more convenient. Leading to something like
#[context_manager::wrap(PrintDuration)]
fn function_to_be_wrapped() -> usize {
do_something_expensive()
}
§How does the library work internally?
The library exposes 2 main traits that allows users to customize the wrapping logic
SyncWrapContext
for synchronous context management (which is supported for decorating sync and async functions)AsyncWrapContext
for asynchronous context management (which is supported ONLY for async functions)
and 2 main attribute macros (wrap
and async_wrap
) that allow an easy plug-and-play of the logic into the code
§License
Licensed under either of Apache License, Version 2.0 or MIT license at your option.Unless you explicitly state otherwise, any contribution intentionally submitted for inclusion in this crate by you, as defined in the Apache-2.0 license, shall be dual licensed as above, without any additional terms or conditions.
§Changelog
§0.1.3 (2025-01-28)
- Update
CallerContext
APIs to be const andCallerContext::fn_name
returns&'static str
§0.1.2 (2025-01-21)
- Define
CallerContext
to provideAsyncWrapContext
andSyncWrapContext
the ability to have more details on the wrapped function - Improve documentation of
context_manager_macro
crate to avoid misleading content on crates.io (before, after)
§0.1.1 (2025-01-21)
- Minor update of package documentation (no code changes)
§0.1.0 (2025-01-21)
Initial release
The library provides a simple access point to #[wrap(_)]
and #[async_wrap(_)]
macros to enable end-users to wrap a function with custom logic.
Structs§
- Caller
Context - Context about the caller propagated into the context.
Traits§
- Async
Wrap Context - Context Manager definition (async hooks)
- Sync
Wrap Context - Context Manager definition (sync hooks)
Attribute Macros§
- async_
wrap - Procedural macro that will decorate the incoming async function with the provided context.
- wrap
- Procedural macro that will decorate the incoming function with the provided context.