lazyinit
Initialize a static value lazily.
The crate provides a type for initializing static values lazily in a thread-safe manner.
Unlike compile-time initialization or macro-based solutions like lazy_static
, this type allows runtime initialization with arbitrary logic while guaranteeing that initialization occurs exactly once across all threads.
The core abstraction is a struct that wraps a value and manages its initialization state through atomic operations. The value remains uninitialized until the first call to init_once
or call_once
, at which point it becomes permanently initialized and accessible.
Features
- Thread-Safe Initialization: Guarantees exactly one initialization across multiple threads
- Flexible Initialization: Supports both direct value initialization and closure-based initialization
- Safe Access Patterns: Provides both safe and unsafe access methods
- State Inspection: Allows checking initialization status without accessing the value
- Direct Access: Implements
Deref
andDerefMut
for transparent access after initialization - No-std Compatibility: Works in embedded and kernel environments without the standard library. No external dependencies.
Examples
use LazyInit;
static VALUE: = new;
assert!;
// println!("{}", *VALUE); // panic: use uninitialized value
assert_eq!;
VALUE.init_once;
// VALUE.init_once(666); // panic: already initialized
assert!;
assert_eq!;
assert_eq!;
Only one of the multiple initializations can succeed:
use LazyInit;
use Duration;
const N: usize = 16;
static VALUE: = new;
let threads =
.map
.;
let mut ok = 0;
for in threads.into_iter.enumerate
assert_eq!;