1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
use std::sync::atomic::{AtomicUsize, Ordering};
#[derive(Debug)]
pub(crate) struct Lazy(AtomicUsize);
impl Lazy {
const UNINIT: usize = usize::MAX;
pub(crate) const fn new() -> Self {
Self(AtomicUsize::new(Self::UNINIT))
}
pub(crate) fn get_or_init<F>(&self, f: F) -> usize
where
F: FnOnce() -> usize,
{
self.get().unwrap_or_else(|| {
let mut val = f();
assert_ne!(val, Self::UNINIT);
let exchange =
self.0
.compare_exchange(Self::UNINIT, val, Ordering::AcqRel, Ordering::Acquire);
if let Err(old) = exchange {
val = old;
}
debug_assert_ne!(val, Self::UNINIT);
val
})
}
fn get(&self) -> Option<usize> {
let val = self.0.load(Ordering::Acquire);
if val == Self::UNINIT {
None
} else {
Some(val)
}
}
}
impl Default for Lazy {
fn default() -> Self {
Lazy::new()
}
}