poly_once/
lib.rs

1//! A collection of thread-safe, lock-free "once" cells for one-time initialization.
2//!
3//! This crate provides two main types for one-time initialization patterns:
4//!
5//! - [`Once<T>`]: A standard once cell that can be written to only once.
6//! - [`TOnce<P, T>`]: A parameterized once cell that stores a parameter and transforms it
7//!   into the final value on first access.
8//!
9//! Both types are thread-safe and use atomic operations with `parking_lot`'s futex-based
10//! synchronization for efficient blocking when necessary. They guarantee that initialization
11//! logic runs exactly once, even when multiple threads attempt concurrent initialization.
12//!
13//! # Features
14//!
15//! - **Lock-free fast path**: Reading initialized values requires no synchronization.
16//! - **Efficient blocking**: Uses futex-based parking when waiting for initialization.
17//! - **Async support**: Both types support async initialization with futures.
18//! - **Fallible initialization**: Support for initialization functions that can fail.
19//! - **No heap allocation**: Stack-based storage with no dynamic memory allocation.
20//!
21//! # Examples
22//!
23//! ## Basic Once Cell
24//!
25//! ```rust
26//! use poly_once::Once;
27//!
28//! static CONFIG: Once<String> = Once::new();
29//!
30//! // Initialize the value
31//! CONFIG.get_or_init(|| "production".to_string());
32//!
33//! // Subsequent calls return the same value without re-running the initializer
34//! assert_eq!(CONFIG.get(), Some(&"production".to_string()));
35//! ```
36//!
37//! ## Parameterized Once Cell
38//!
39//! ```rust
40//! use poly_once::TOnce;
41//!
42//! // Store a path, transform it to a loaded config on first access
43//! let config_cell = TOnce::new("/etc/app.conf");
44//!
45//! let config = config_cell.get_or_init(|path| {
46//!     // This runs only once, even if called from multiple threads
47//!     std::fs::read_to_string(path).unwrap_or_default()
48//! });
49//! ```
50
51/// Standard once cell implementation.
52mod once;
53
54/// Internal synchronization state management.
55mod state;
56
57/// Parameterized once cell implementation.
58mod transform_once;
59
60pub use once::Once;
61pub use transform_once::TOnce;