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
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
use core::cell::UnsafeCell;
use core::mem::MaybeUninit;
use core::ops::Deref;
use core::sync::atomic::{AtomicU8, Ordering};

/// Ressource that is initialized at most once.
pub struct Once<T: Send> {
    cell: UnsafeCell<MaybeUninit<T>>,
    state: AtomicU8,
}

unsafe impl<T: Send> Send for Once<T> {}
unsafe impl<T: Send> Sync for Once<T> {}

/// Error returned by `Once::set` if the value is already initialized.
#[derive(Debug, Clone, Copy)]
pub struct OnceError;

impl<T: Send> Once<T> {
    pub const fn new() -> Self {
        Self {
            cell: UnsafeCell::new(MaybeUninit::uninit()),
            state: AtomicU8::new(0),
        }
    }

    /// Set the value if it is not initialized already. This call succeeds only once.
    pub fn set(&self, value: T) -> Result<(), OnceError> {
        if self
            .state
            .compare_exchange(0, 1, Ordering::AcqRel, Ordering::Acquire)
            .is_ok()
        {
            let inner = unsafe { &mut *self.cell.get() };
            inner.write(value);
            let prev = self.state.fetch_add(1, Ordering::AcqRel);
            assert!(prev == 1);
            Ok(())
        } else {
            Err(OnceError)
        }
    }

    /// Get the value if it is initialized.
    pub fn get(&self) -> Option<&T> {
        if self.state.load(Ordering::Acquire) == 2 {
            let inner = unsafe { &*self.cell.get() };
            Some(unsafe { inner.assume_init_ref() })
        } else {
            None
        }
    }

    /// Get the value if it is initialized, otherwise initialize it.
    pub fn get_or_init(&self, f: impl FnOnce() -> T) -> &T {
        match self
            .state
            .compare_exchange(0, 1, Ordering::AcqRel, Ordering::Acquire)
        {
            Ok(0) => {
                let inner = unsafe { &mut *self.cell.get() };
                let value = inner.write(f());
                let prev = self.state.fetch_add(1, Ordering::AcqRel);
                assert!(prev == 1);
                value
            }
            Err(2) => unsafe { (*self.cell.get()).assume_init_ref() },
            _ => panic!("Unexpected lock state"),
        }
    }
}

impl<T: Send> Deref for Once<T> {
    type Target = T;

    #[track_caller]
    fn deref(&self) -> &Self::Target {
        self.get().expect("Not initialized")
    }
}

impl<T: Send> Drop for Once<T> {
    fn drop(&mut self) {
        if self.state.load(Ordering::Acquire) == 2 {
            let inner = unsafe { &mut *self.cell.get() };
            unsafe { inner.assume_init_drop() }
        }
    }
}

/// A lazy value that is initialized at most once.
pub struct Lazy<T: Send, F: FnOnce() -> T + Clone> {
    constructor: F,
    once: Once<T>,
}

impl<T: Send, F: FnOnce() -> T + Clone> Lazy<T, F> {
    pub const fn new(f: F) -> Self {
        Self {
            constructor: f,
            once: Once::new(),
        }
    }
}

impl<T: Send, F: FnOnce() -> T + Clone> Deref for Lazy<T, F> {
    type Target = T;

    #[track_caller]
    fn deref(&self) -> &Self::Target {
        self.once.get_or_init(self.constructor.clone())
    }
}