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
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
//! The `init_once` crate provides a mechanic to attempt to read a value without
//! blocking the caller, in case it is being initialized concurrently. Such an
//! abstraction might be useful in cache implementations whose consumers might
//! not want to block on the cache to fill up with data.

#![cfg_attr(not(test), no_std)]
#![deny(missing_docs)]

use core::cell::UnsafeCell;
use core::future::{self, Future};
use core::hint::unreachable_unchecked;
use core::mem::{needs_drop, MaybeUninit};
use core::task::Poll;

use portable_atomic::{self as atomic, AtomicUsize};

mod init_once_state {
    pub const EMPTY: usize = 0;
    pub const INITIALIZING: usize = 1;
    pub const INITIALIZED: usize = 2;
}

/// Initialization state of an [`InitOnce`] instance.
#[derive(Debug)]
pub enum InitState<'a, T> {
    /// The inner value is currently being initialized by another caller.
    Initializing,
    /// The inner value is initialized.
    Initialized(&'a T),
    /// The inner value requires initialization via [`PollInit`].
    Polling(PollInit<'a, T>),
}

/// Lazily initialize a value of some arbitrary type `T`.
/// Reading the value doesn't block the caller, if it is
/// being initialized concurrently.
#[derive(Debug)]
pub struct InitOnce<T> {
    cell: UnsafeCell<MaybeUninit<T>>,
    state: AtomicUsize,
}

/// Polling mechanism to initialize a value contained in some
/// [`InitOnce`] instance.
#[derive(Debug)]
pub struct PollInit<'a, T> {
    init_once: &'a InitOnce<T>,
}

// SAFETY: should be safe to share between threads
// if `T` is also `Sync`. the atomic operations
// guarantee that every thread will see the same
// data.
unsafe impl<T: Sync> Sync for InitOnce<T> {}

impl<T> Drop for InitOnce<T> {
    // NB: it is guaranteed that at least one thread calls `Drop`, since
    // we must block to initialize from at least one thread
    fn drop(&mut self) {
        if needs_drop::<T>()
            && self.state.load(atomic::Ordering::SeqCst) == init_once_state::INITIALIZED
        {
            // SAFETY: the value is initialized, so we can drop it
            unsafe {
                self.cell.get_mut().assume_init_drop();
            }
        }
    }
}

impl<T> Default for InitOnce<T> {
    #[inline]
    fn default() -> Self {
        Self::new()
    }
}

impl<T> InitOnce<T> {
    /// Create an uninitialized [`InitOnce`].
    pub const fn new() -> Self {
        Self {
            cell: UnsafeCell::new(MaybeUninit::uninit()),
            state: AtomicUsize::new(init_once_state::EMPTY),
        }
    }

    #[cold]
    #[must_use]
    #[inline(never)]
    fn poll_init_begin(&self) -> PollInit<'_, T> {
        PollInit { init_once: self }
    }

    /// Query the state of an [`InitOnce`] instance.
    ///
    /// If the current state is [`InitState::Polling`], the caller is
    /// responsible for polling the init function to completion.
    #[must_use = "The state of an InitOnce (i.e. InitState) must always be consumed. If you do \
             not poll the value initializer to completion, the value will never be initialized."]
    #[inline]
    pub fn state(&self) -> InitState<'_, T> {
        self.state
            .compare_exchange(
                init_once_state::EMPTY,
                init_once_state::INITIALIZING,
                atomic::Ordering::SeqCst,
                atomic::Ordering::SeqCst,
            )
            .map_or_else(
                |current_value| match current_value {
                    init_once_state::INITIALIZING => InitState::Initializing,
                    init_once_state::INITIALIZED => {
                        InitState::Initialized({
                            // SAFETY: the data returned by the atomic load guarantees
                            // that the value has been initialized.
                            unsafe { (*self.cell.get()).assume_init_ref() }
                        })
                    }
                    _ => {
                        // SAFETY: we attempted to atomically swap `init_once_state::EMPTY`
                        // with `init_once_state::INITIALIZING` and failed. the safety of
                        // this `unreachable_unchecked` is guaranteed by the CAS, whose
                        // previous value couldn't have been `init_once_state::EMPTY`.
                        unsafe { unreachable_unchecked() }
                    }
                },
                |_| InitState::Polling(self.poll_init_begin()),
            )
    }

    /// Attempt to initialize this [`InitOnce`] with the value returned by the closure `init`.
    #[inline]
    pub fn try_init<F>(&self, mut init: F) -> Option<&T>
    where
        F: FnMut() -> T,
    {
        match self.state() {
            InitState::Initialized(value) => Some(value),
            InitState::Initializing => None,
            InitState::Polling(poller) => match poller.poll_init(|| Poll::Ready(init())) {
                Poll::Ready(value) => Some(value),
                Poll::Pending => {
                    // SAFETY: we pass `Poll::Ready` to `poll_init` above, therefore
                    // it is impossible to reach this `Poll::Pending` branch
                    unsafe { unreachable_unchecked() }
                }
            },
        }
    }

    /// Attempt to initialize this [`InitOnce`] with the value returned by the future `init`.
    pub async fn try_init_async<F>(&self, init: F) -> Option<&T>
    where
        F: Future<Output = T>,
    {
        match self.state() {
            InitState::Initialized(value) => Some(value),
            InitState::Initializing => None,
            InitState::Polling(poller) => Some(poller.init_async(init).await),
        }
    }

    /// Initialize this [`InitOnce`] with the value returned by the closure `init`.
    pub fn init<F>(&mut self, mut init: F) -> &mut T
    where
        F: FnMut() -> T,
    {
        let maybe_uninit = self.cell.get_mut();

        unlikely_if(
            *self.state.get_mut() != init_once_state::INITIALIZED,
            || {
                *self.state.get_mut() = init_once_state::INITIALIZED;
                maybe_uninit.write(init());
            },
        );

        // SAFETY: we hold the only reference to the `InitOnce` cell,
        // and we guarantee that it is always initialized with the
        // call above
        unsafe { maybe_uninit.assume_init_mut() }
    }

    /// Initialize this [`InitOnce`] with the value returned by the future `init`.
    pub async fn init_async<F>(&mut self, init: F) -> &mut T
    where
        F: Future<Output = T>,
    {
        let maybe_uninit = self.cell.get_mut();

        unlikely_if(
            *self.state.get_mut() != init_once_state::INITIALIZED,
            || async {
                *self.state.get_mut() = init_once_state::INITIALIZED;
                maybe_uninit.write(init.await);
            },
        )
        .await;

        // SAFETY: we hold the only reference to the `InitOnce` cell,
        // and we guarantee that it is always initialized with the
        // call above
        unsafe { maybe_uninit.assume_init_mut() }
    }
}

impl<'init_once, T> PollInit<'init_once, T> {
    /// Initialize the associated [`InitOnce`] with the given future `init`.
    pub async fn init_async<F>(&self, mut init: F) -> &'init_once T
    where
        F: Future<Output = T>,
    {
        let mut pinned_init = core::pin::pin!(init);
        future::poll_fn(|cx| self.poll_init(|| pinned_init.as_mut().poll(cx))).await
    }

    /// Check if the value returned by `init` is ready.
    ///
    /// While it is technically possible to initialize multiple different
    /// values with this method, the [`InitOnce`] abstraction's soundness
    /// is not affected.
    pub fn poll_init<F>(&self, mut init: F) -> Poll<&'init_once T>
    where
        F: FnMut() -> Poll<T>,
    {
        let value = core::task::ready!(init());

        // SAFETY: we CAS'd `init_once_state::EMPTY` with
        // `init_once_state::INITIALIZING`, therefore we
        // hold an exclusive reference to the `UnsafeCell`.
        let slot = unsafe { (*self.init_once.cell.get()).as_mut_ptr() };

        // SAFETY: same as above.
        unsafe {
            core::ptr::write(slot, value);
        }

        self.init_once
            .state
            .store(init_once_state::INITIALIZED, atomic::Ordering::SeqCst);

        Poll::Ready({
            // SAFETY: we atomically stored `init_once_state::INITIALIZED`
            // onto `state`, and initialized the value returned from `init`.
            unsafe { (*self.init_once.cell.get()).assume_init_ref() }
        })
    }
}

#[inline(always)]
fn unlikely_if<T, F: FnOnce() -> T>(cond: bool, f: F) -> T {
    #[cold]
    #[inline(never)]
    fn unlikely_call<T, F: FnOnce() -> T>(f: F) -> T {
        f()
    }

    if cond {
        unlikely_call(f)
    } else {
        f()
    }
}

#[cfg(test)]
mod tests {
    use std::sync::{Arc, Mutex};
    use std::thread;

    use super::*;

    struct TrackDrop {
        count: Arc<Mutex<usize>>,
    }

    impl Drop for TrackDrop {
        fn drop(&mut self) {
            *self.count.lock().unwrap() += 1;
        }
    }

    #[tokio::test]
    async fn dropped_once_if_init() {
        let mut init_once = Arc::new(InitOnce::new());
        let count = Arc::new(Mutex::new(0));

        assert_eq!(
            *Arc::get_mut(&mut init_once).unwrap().state.get_mut(),
            init_once_state::EMPTY
        );

        let tasks: Vec<_> = (0..10)
            .map(|_| {
                let init_once = Arc::clone(&init_once);
                let count = Arc::clone(&count);

                tokio::spawn(async move {
                    if let InitState::Polling(poller) = init_once.state() {
                        let fut = future::ready(TrackDrop { count });
                        let mut pinned_fut = std::pin::pin!(fut);

                        let TrackDrop {
                            count: current_count,
                        } = future::poll_fn(|cx| poller.poll_init(|| pinned_fut.as_mut().poll(cx)))
                            .await;

                        assert_eq!(*current_count.lock().unwrap(), 0);
                    }
                })
            })
            .collect();

        for handle in tasks {
            handle.await.unwrap();
        }

        assert_eq!(*count.lock().unwrap(), 0);
        assert_eq!(
            *Arc::get_mut(&mut init_once).unwrap().state.get_mut(),
            init_once_state::INITIALIZED
        );

        drop(init_once);
        assert_eq!(*count.lock().unwrap(), 1);
    }

    #[test]
    fn never_poll_init() {
        let mut init_once = Arc::new(InitOnce::<()>::new());
        let count = Arc::new(Mutex::new(0));

        assert_eq!(
            *Arc::get_mut(&mut init_once).unwrap().state.get_mut(),
            init_once_state::EMPTY
        );

        assert_eq!(*count.lock().unwrap(), 0);

        let threads: Vec<_> = (0..10)
            .map(|_| {
                let init_once = Arc::clone(&init_once);
                let count = Arc::clone(&count);

                thread::spawn(move || {
                    if matches!(init_once.state(), InitState::Polling(_)) {
                        drop(TrackDrop { count });
                    }
                })
            })
            .collect();

        for handle in threads {
            handle.join().unwrap();
        }

        assert_eq!(*count.lock().unwrap(), 1);

        assert_eq!(
            *Arc::get_mut(&mut init_once).unwrap().state.get_mut(),
            init_once_state::INITIALIZING
        );

        for _ in 0..50 {
            assert!(matches!(init_once.state(), InitState::Initializing));
        }

        drop(init_once);
    }
}