QSingleton
A Rust procedural macro library for implementing thread-safe singleton patterns with minimal boilerplate.
Features
- Thread-safe: Uses
std::sync::OnceLockfor safe concurrent access - Flexible return types: Choose between
&'static SelforArc<Self> - Simple API: Just two methods -
init()andglobal() - Zero runtime overhead: All safety guarantees are compile-time
Installation
Add this to your Cargo.toml:
[]
= "0.1.0"
Usage
Basic Singleton (returns &'static Self)
use singleton;
Arc-based Singleton (returns &'static Arc<Self>)
use singleton;
API
init(instance: Self)
Initializes the singleton with the provided instance. Panics if called more than once.
global() -> &'static Self or global() -> &'static Arc<Self>
Returns a reference to the global singleton instance. Panics if called before init().
Thread Safety
All generated code is thread-safe and uses std::sync::OnceLock internally to ensure:
- Only one initialization can succeed
- Multiple threads can safely access the singleton
- No data races or undefined behavior
License
This project is licensed under the MIT License - see the LICENSE file for details.