arc-handle
A Rust procedural macro crate for generating Arc-based handle wrappers for traits, enabling easy trait object sharing across threads.
Overview
The #[arc_handle] attribute macro transforms a trait definition into a thread-safe handle struct that wraps trait implementations in Arc<dyn Trait + Send + Sync>. This pattern is useful when you need to share trait objects across multiple threads or async tasks.
Features
- Thread-safe sharing: Generated handles implement
Clone,Send, andSync - Async/await support: Properly handles both sync and async trait methods
- Zero-cost abstraction: Minimal overhead over direct Arc usage
- Easy integration: Simple attribute macro application
Installation
Add this to your Cargo.toml:
[]
= "1.0.0"
Usage
Basic Example
use arc_handle;
// Implementation
;
// Usage
Async Example
use arc_handle;
use async_trait;
async
Default Method Implementations
Trait methods with default bodies are supported. The handle delegates to the trait object, so implementors may override the default and the handle will dispatch to their override:
use arc_handle;
;
How It Works
When you apply #[arc_handle] to a trait:
- Trait Transformation: The original trait is renamed to
TraitImpl - Handle Generation: A new struct with the original trait name is created
- Method Delegation: All trait methods are implemented on the handle, delegating to the inner
Arc<dyn TraitImpl + Send + Sync> - Constructor Methods:
new()andfrom_boxed()methods are generated for easy instantiation
Generated Code Structure
For a trait named MyTrait, the macro generates:
// Original trait renamed
// Generated handle struct
Requirements
- Rust 2024 edition or later
- For async traits, use with
#[async_trait]from theasync-traitcrate
License
Licensed under either of
- Apache License, Version 2.0 (LICENSE-APACHE or http://www.apache.org/licenses/LICENSE-2.0)
- MIT license (LICENSE-MIT or http://opensource.org/licenses/MIT)
at your option.
Contributing
Contributions are welcome! Please feel free to submit a Pull Request.