poly-once
A thread-safe cell providing initialization primitives similar to std::sync::OnceLock but with a lock model that works with both sync and async code.
poly-once provides two types for safe, one-time initialization of values:
Once<T>: Basic one-time initialization cellTOnce<P, T>: Parameterized initialization cell that transforms a parameterPinto valueT
Both types ensure that initialization logic runs only once, even under concurrent access from multiple threads or async tasks. They leverage parking_lot_core for efficient blocking synchronization.
Features
- Thread-Safe: Safely initialize and access values from multiple threads.
- Sync Initialization: Initialize values using standard closures (
get_or_init,get_or_try_init). - Async Initialization: Initialize values using
async fnorFutures (get_or_init_async,get_or_try_init_async). - Lazy Initialization: Values are initialized only when first accessed.
- Fallible Initialization: Supports initialization functions that can return
Result. - Efficient Blocking: Uses
parking_lot_corefor low-overhead synchronization when blocking is necessary. - Small footprint: The overhead is only 4 bytes per instance due to the use of parking lot, making it suitable for entities that are created used very frequently.
no_stdCompatibility: Can be used inno_stdenvironments (requires disabling default features iftokiodependency is not desired).
Usage
Add poly-once to your Cargo.toml:
[]
= "1" # Use the latest version
Basic Sync Initialization
use Once;
use ;
static COUNTER: AtomicUsize = new;
static DATA: = new;
Async Initialization
use Once;
use ;
use ;
static COUNTER: AtomicUsize = new;
static ASYNC_DATA: = new;
async
async
Fallible Initialization
Handles cases where initialization might fail.
use Once;
static MAYBE_DATA: = new;
Parameterized Initialization with TOnce
TOnce<P, T> allows you to store a parameter value that will be transformed into the final value on first access.
use TOnce;
// Store configuration that will be used to create a connection
static CONNECTION: = new;
Async Initialization with TOnce
use TOnce;
use ;
static ASYNC_CONFIG: = new;
async
async
async
Cargo Features
poly-once uses feature flags to enable asynchronous support and configure dependencies.
-
async-tokio:- Enables async initialization methods.
- Compatible with any
tokioruntime, dropping the requirement oftokio::task::block_in_placein exchange for a less efficient implementation.
-
async-tokio-mt:- Enables async initialization methods.
- Uses the multi-threaded
tokioruntime. Requirestokiowith thertandrt-multi-threadfeatures.
no_std Usage:
To use poly-once in a no_std environment without requiring tokio, disable the default features:
[]
= { = "1", = false }
This will provide less efficient asyncronous methods without the support of the runtime.
License
Licensed under the MIT License. See the LICENSE file for details.
Contributing
Contributions are welcome! Please feel free to submit pull requests or open issues on the repository.