| 1 |
//! Helpers built around pointer-sized atomics. |
| 2 |
use core::sync::atomic::{AtomicUsize, Ordering}; |
| 3 |
|
| 4 |
// This structure represents a lazily initialized static usize value. Useful |
| 5 |
// when it is preferable to just rerun initialization instead of locking. |
| 6 |
// unsync_init will invoke an init() function until it succeeds, then return the |
| 7 |
// cached value for future calls. |
| 8 |
// |
| 9 |
// unsync_init supports init() "failing". If the init() method returns UNINIT, |
| 10 |
// that value will be returned as normal, but will not be cached. |
| 11 |
// |
| 12 |
// Users should only depend on the _value_ returned by init() functions. |
| 13 |
// Specifically, for the following init() function: |
| 14 |
// fn init() -> usize { |
| 15 |
// a(); |
| 16 |
// let v = b(); |
| 17 |
// c(); |
| 18 |
// v |
| 19 |
// } |
| 20 |
// the effects of c() or writes to shared memory will not necessarily be |
| 21 |
// observed and additional synchronization methods may be needed. |
| 22 |
struct LazyUsize(AtomicUsize); |
| 23 |
|
| 24 |
impl LazyUsize { |
| 25 |
// The initialization is not completed. |
| 26 |
const UNINIT: usize = usize::MAX; |
| 27 |
|
| 28 |
const fn new() -> Self { |
| 29 |
Self(AtomicUsize::new(Self::UNINIT)) |
| 30 |
} |
| 31 |
|
| 32 |
// Runs the init() function at most once, returning the value of some run of |
| 33 |
// init(). Multiple callers can run their init() functions in parallel. |
| 34 |
// init() should always return the same value, if it succeeds. |
| 35 |
fn unsync_init(&self, init: impl FnOnce() -> usize) -> usize { |
| 36 |
#[cold] |
| 37 |
fn do_init(this: &LazyUsize, init: impl FnOnce() -> usize) -> usize { |
| 38 |
let val = init(); |
| 39 |
this.0.store(val, Ordering::Relaxed); |
| 40 |
val |
| 41 |
} |
| 42 |
|
| 43 |
// Relaxed ordering is fine, as we only have a single atomic variable. |
| 44 |
let val = self.0.load(Ordering::Relaxed); |
| 45 |
if val != Self::UNINIT { |
| 46 |
val |
| 47 |
} else { |
| 48 |
do_init(self, init) |
| 49 |
} |
| 50 |
} |
| 51 |
} |
| 52 |
|
| 53 |
// Identical to LazyUsize except with bool instead of usize. |
| 54 |
pub(crate) struct LazyBool(LazyUsize); |
| 55 |
|
| 56 |
impl LazyBool { |
| 57 |
pub const fn new() -> Self { |
| 58 |
Self(LazyUsize::new()) |
| 59 |
} |
| 60 |
|
| 61 |
pub fn unsync_init(&self, init: impl FnOnce() -> bool) -> bool { |
| 62 |
self.0.unsync_init(|| usize::from(init())) != 0 |
| 63 |
} |
| 64 |
} |