| 1 |
use core::sync::atomic::{AtomicU8, Ordering::Relaxed}; |
| 2 |
|
| 3 |
/// Lazily caches a `bool` in an `AtomicU8`. |
| 4 |
/// |
| 5 |
/// Initialization is intentionally unsynchronized: concurrent callers may race |
| 6 |
/// and run `init` more than once. Once a value is produced, it is cached and |
| 7 |
/// reused by subsequent calls. |
| 8 |
/// |
| 9 |
/// Uses `Relaxed` ordering because this helper only publishes the cached |
| 10 |
/// value itself. |
| 11 |
pub(crate) struct LazyBool(AtomicU8); |
| 12 |
|
| 13 |
impl LazyBool { |
| 14 |
const UNINIT: u8 = u8::MAX; |
| 15 |
|
| 16 |
/// Create new `LazyBool`. |
| 17 |
pub const fn new() -> Self { |
| 18 |
Self(AtomicU8::new(Self::UNINIT)) |
| 19 |
} |
| 20 |
|
| 21 |
/// Call the `init` closure and return the result after caching it. |
| 22 |
#[cold] |
| 23 |
fn cold_init(&self, init: impl FnOnce() -> bool) -> bool { |
| 24 |
let val = u8::from(init()); |
| 25 |
self.0.store(val, Relaxed); |
| 26 |
val != 0 |
| 27 |
} |
| 28 |
|
| 29 |
/// Retrieve the cached value if it was already initialized or call the `init` closure |
| 30 |
/// and return the result after caching it. |
| 31 |
#[inline] |
| 32 |
pub fn unsync_init(&self, init: impl FnOnce() -> bool) -> bool { |
| 33 |
let val = self.0.load(Relaxed); |
| 34 |
if val == Self::UNINIT { |
| 35 |
return self.cold_init(init); |
| 36 |
} |
| 37 |
val != 0 |
| 38 |
} |
| 39 |
} |