| 1 |
use core::{ |
| 2 |
convert::Infallible, |
| 3 |
ptr::{self, NonNull}, |
| 4 |
sync::atomic::{AtomicPtr, Ordering::Relaxed}, |
| 5 |
}; |
| 6 |
|
| 7 |
/// Lazily caches a non-null pointer in an `AtomicPtr`. |
| 8 |
/// |
| 9 |
/// Initialization is intentionally unsynchronized: concurrent callers may race |
| 10 |
/// and run `init` more than once. Once a value is produced, it is cached and |
| 11 |
/// reused by subsequent calls. |
| 12 |
/// |
| 13 |
/// For fallible initialization (`try_unsync_init`), only successful values are |
| 14 |
/// cached; errors are returned to the caller and are not cached. |
| 15 |
/// |
| 16 |
/// Uses `Ordering::Relaxed` because this helper only publishes the cached |
| 17 |
/// pointer value. Callers must not rely on this mechanism to synchronize |
| 18 |
/// unrelated memory side effects performed by `init`. |
| 19 |
pub(crate) struct LazyPtr<T>(AtomicPtr<T>); |
| 20 |
|
| 21 |
impl<T> LazyPtr<T> { |
| 22 |
/// Create new `LazyPtr`. |
| 23 |
pub const fn new() -> Self { |
| 24 |
Self(AtomicPtr::new(ptr::null_mut())) |
| 25 |
} |
| 26 |
|
| 27 |
/// Call the `init` closure and return the result after caching it in the case of success. |
| 28 |
#[cold] |
| 29 |
fn cold_init<E>(&self, init: impl FnOnce() -> Result<NonNull<T>, E>) -> Result<NonNull<T>, E> { |
| 30 |
let val = init()?; |
| 31 |
self.0.store(val.as_ptr(), Relaxed); |
| 32 |
Ok(val) |
| 33 |
} |
| 34 |
|
| 35 |
/// Retrieve the cached value if it was already initialized or call the potentially fallible |
| 36 |
/// `init` closure and return the result after caching it in the case of success. |
| 37 |
#[inline] |
| 38 |
pub fn try_unsync_init<E>( |
| 39 |
&self, |
| 40 |
init: impl FnOnce() -> Result<NonNull<T>, E>, |
| 41 |
) -> Result<NonNull<T>, E> { |
| 42 |
let p = self.0.load(Relaxed); |
| 43 |
match NonNull::new(p) { |
| 44 |
Some(val) => Ok(val), |
| 45 |
None => self.cold_init(init), |
| 46 |
} |
| 47 |
} |
| 48 |
|
| 49 |
/// Retrieve the cached value if it was already initialized or call the `init` closure |
| 50 |
/// and return the result after caching it. |
| 51 |
#[inline] |
| 52 |
#[allow(dead_code, reason = "Some modules use only `try_unsync_init`")] |
| 53 |
pub fn unsync_init(&self, init: impl FnOnce() -> NonNull<T>) -> NonNull<T> { |
| 54 |
let Ok(p): Result<_, Infallible> = self.try_unsync_init(|| Ok(init())); |
| 55 |
p |
| 56 |
} |
| 57 |
} |