Skip to main content

once_fn/
async_once_cell.rs

1//! A runtime-agnostic asynchronous once cell.
2
3use std::{
4    cell::Cell,
5    future::Future,
6    mem,
7    pin::Pin,
8    sync::{Mutex, MutexGuard},
9    task::{Context, Poll, Waker},
10};
11
12/// An asynchronous once cell: the first future returned by
13/// [`get_or_init`](AsyncOnceCell::get_or_init) to be polled runs its
14/// initializer to completion and caches the output; every other poll of any
15/// future created for the cell waits for that value and resolves to a shared
16/// reference to it.
17///
18/// Unlike [`std::sync::OnceLock`], initialization happens inside the polling
19/// task: the initializer future is polled in the context of the first caller,
20/// so no thread blocks, no task is spawned and no runtime is required.
21///
22/// # Cancellation and panics
23///
24/// If the initializing future is dropped before it finishes (the awaiting task
25/// was cancelled) or its poll panics, the cell rolls back to empty and the
26/// next call runs the initializer again, so a body passed to `get_or_init` may
27/// run more than once. This matches the retry semantics of
28/// [`std::sync::OnceLock`].
29///
30/// # Reentrancy
31///
32/// A future that re-enters the same cell's `get_or_init` while that cell is
33/// initializing would wait for itself; such a call panics with a clear message
34/// instead of deadlocking. Initializing a different cell from inside an
35/// initializer is supported.
36///
37/// # Examples
38///
39/// ```
40/// use once_fn::AsyncOnceCell;
41///
42/// static CELL: AsyncOnceCell<u32> = AsyncOnceCell::new();
43///
44/// #[tokio::main]
45/// async fn main() {
46///     let a = CELL.get_or_init(|| async { 7 }).await;
47///     let b = CELL.get_or_init(|| async { unreachable!() }).await;
48///     assert_eq!((a, b), (&7, &7));
49/// }
50/// ```
51pub struct AsyncOnceCell<T> {
52    state: Mutex<State<T>>,
53}
54
55enum State<T> {
56    /// No initializer has run; the next poll claims initialization.
57    New,
58    /// An initializer future exists and is being driven to completion.
59    Init { wakers: Vec<Waker> },
60    /// Terminal state: the value is cached and never written again.
61    Ready(T),
62}
63
64// SAFETY: `Send`: a cell may move to another thread, carrying a stored `T`.
65// `Sync`: `get_or_init` hands `&T` out through `&self` to arbitrary threads,
66// which requires `T: Sync`, and initialization moves a `T` produced on one
67// thread into state shared by all of them, which requires `T: Send`.
68unsafe impl<T: Send> Send for AsyncOnceCell<T> {}
69unsafe impl<T: Send + Sync> Sync for AsyncOnceCell<T> {}
70
71thread_local! {
72    /// Address of the cell whose user future is being polled on this thread
73    /// (`0` = none). Addresses are only compared, never dereferenced. A stored
74    /// address is observable only while the initializer's poll is on this
75    /// thread's stack, and two live cells never share an address, so distinct
76    /// cells cannot be confused here.
77    static POLLING: Cell<usize> = const { Cell::new(0) };
78}
79
80/// Restores [`POLLING`] on scope exit, including on unwind: a panic escaping
81/// a user future's poll must not leave a stale address behind.
82struct RestorePolling(usize);
83
84impl Drop for RestorePolling {
85    fn drop(&mut self) {
86        POLLING.with(|p| p.set(self.0));
87    }
88}
89
90impl<T> AsyncOnceCell<T> {
91    /// Create an empty cell.
92    pub const fn new() -> Self {
93        Self {
94            state: Mutex::new(State::New),
95        }
96    }
97
98    /// Return a future that resolves to a reference to the cached value,
99    /// initializing the cell with `f` if needed.
100    ///
101    /// The first future to be polled calls `f` and polls the returned future
102    /// in the caller's task context; futures polled while initialization is in
103    /// flight park as waiters and are woken once the value is stored.
104    ///
105    /// # Panics
106    ///
107    /// Panics if the cell is re-entered from inside its own initializer, which
108    /// would otherwise deadlock waiting for itself.
109    pub fn get_or_init<F, Fut>(&self, f: F) -> GetOrInit<'_, T, F, Fut>
110    where
111        F: FnOnce() -> Fut,
112        Fut: Future<Output = T>,
113    {
114        GetOrInit {
115            cell: self,
116            f: Some(f),
117            fut: None,
118        }
119    }
120
121    /// Waiter-side reentrancy check: panics if this cell's initializer is on
122    /// the current thread's stack, meaning the caller would wait for itself.
123    fn assert_not_reentrant(&self) {
124        let addr = std::ptr::from_ref::<Self>(self) as usize;
125        assert!(
126            POLLING.with(Cell::get) != addr,
127            "an async once fn was re-entered while it is initializing; this would deadlock"
128        );
129    }
130
131    /// # Safety
132    ///
133    /// `ptr` must point to the `Ready` payload stored in this cell. `Ready` is
134    /// terminal: this type exposes no take or reset, so once stored the value
135    /// is never moved, mutated or dropped while the cell lives, and the lock
136    /// pair that stored it happens-before any later lock, so readers observe a
137    /// fully initialized value. This is the only way a reference may outlive
138    /// the state lock it was taken under.
139    // the receiver is unused on purpose: it binds the returned reference's
140    // lifetime and the pointer's provenance to this cell
141    #[allow(clippy::unused_self)]
142    unsafe fn ready_ref(&self, ptr: *const T) -> &T {
143        unsafe { &*ptr }
144    }
145
146    fn lock(&self) -> MutexGuard<'_, State<T>> {
147        // a poisoned lock means an initializer panicked; the state is still
148        // consistent, so keep going like `OnceLock` does
149        self.state
150            .lock()
151            .unwrap_or_else(std::sync::PoisonError::into_inner)
152    }
153}
154
155impl<T> Default for AsyncOnceCell<T> {
156    fn default() -> Self {
157        Self::new()
158    }
159}
160
161/// Future returned by [`AsyncOnceCell::get_or_init`]; resolves to a shared
162/// reference to the cached value.
163pub struct GetOrInit<'a, T, F, Fut> {
164    cell: &'a AsyncOnceCell<T>,
165    /// The initializer; taken when this future claims initialization.
166    f: Option<F>,
167    /// The user future; `Some` once this future is the initializer.
168    fut: Option<Pin<Box<Fut>>>,
169}
170
171// SAFETY: no field is structurally pinned. The user future is polled through
172// `Pin<Box<Fut>>`, and moving this wrapper only moves the box, not the pinned
173// allocation; `f` is only ever taken by value, never pinned. `poll` therefore
174// does not rely on the caller keeping this future at a stable address.
175impl<T, F, Fut> Unpin for GetOrInit<'_, T, F, Fut> {}
176
177impl<'a, T, F, Fut> Future for GetOrInit<'a, T, F, Fut>
178where
179    F: FnOnce() -> Fut,
180    Fut: Future<Output = T>,
181{
182    type Output = &'a T;
183
184    fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
185        // `Self: Unpin`, so no pin projection is needed.
186        let this = self.get_mut();
187
188        {
189            let mut state = this.cell.lock();
190            match &mut *state {
191                State::Ready(v) => {
192                    let ptr: *const T = v;
193                    return Poll::Ready(unsafe { this.cell.ready_ref(ptr) });
194                },
195                State::New => *state = State::Init { wakers: Vec::new() },
196                State::Init { wakers } if this.fut.is_none() => {
197                    this.cell.assert_not_reentrant();
198                    // the last waiter may already hold an equivalent waker
199                    if !wakers.last().is_some_and(|w| w.will_wake(cx.waker())) {
200                        wakers.push(cx.waker().clone());
201                    }
202                    return Poll::Pending;
203                },
204                State::Init { .. } => {},
205            }
206        }
207        // the lock is released before any user code runs
208
209        if this.fut.is_none() {
210            let f = this
211                .f
212                .take()
213                .expect("the initializer keeps its closure until the future is built");
214            this.fut = Some(Box::pin(f()));
215        }
216
217        // Poll the user future in the caller's context: the waker it registers
218        // drives this future to completion, so a `Pending` result needs no
219        // bookkeeping of our own.
220        let saved = POLLING.with(|p| p.replace(std::ptr::from_ref(this.cell) as usize));
221        let _restore = RestorePolling(saved);
222        let out = this
223            .fut
224            .as_mut()
225            .expect("initializer future")
226            .as_mut()
227            .poll(cx);
228        match out {
229            Poll::Pending => Poll::Pending,
230            Poll::Ready(v) => {
231                // Store the value and collect the waiters in one critical
232                // section, then wake only after releasing the lock: a woken
233                // task re-enters `poll` immediately and must not block on it.
234                let (ptr, wakers): (*const T, Vec<Waker>) = {
235                    let mut state = this.cell.lock();
236                    let old = mem::replace(&mut *state, State::Ready(v));
237                    let State::Ready(ptr) = &*state else {
238                        unreachable!("`Ready` was just stored")
239                    };
240                    match old {
241                        State::Init { wakers } => (ptr, wakers),
242                        _ => unreachable!("only the initializer stores `Ready`"),
243                    }
244                };
245                for waker in wakers {
246                    waker.wake();
247                }
248                Poll::Ready(unsafe { this.cell.ready_ref(ptr) })
249            },
250        }
251    }
252}
253
254impl<T, F, Fut> Drop for GetOrInit<'_, T, F, Fut> {
255    fn drop(&mut self) {
256        // This future owns the `Init` state it claimed if it built the user
257        // future, or if `f()` panicked after `f` was taken. A pure waiter
258        // (`f` untouched, no future) owns nothing.
259        if self.f.is_none() || self.fut.is_some() {
260            let wakers = {
261                let mut state = self.cell.lock();
262                if let State::Init { wakers } = &mut *state {
263                    let taken = mem::take(wakers);
264                    *state = State::New;
265                    taken
266                } else {
267                    // `Ready`: initialization completed through this future.
268                    Vec::new()
269                }
270            };
271            for waker in wakers {
272                waker.wake();
273            }
274            // Drop the user future after the rollback and after waking: its
275            // destructor may call back into this cell and must find `New`, not
276            // an initializer that will never run again.
277            drop(self.fut.take());
278        }
279    }
280}
281
282#[cfg(test)]
283mod tests {
284    use std::{
285        cell::Cell,
286        future::Future,
287        panic::{AssertUnwindSafe, catch_unwind},
288        rc::Rc,
289        sync::{
290            Arc,
291            atomic::{AtomicUsize, Ordering},
292        },
293        task::{Context, Poll, Wake, Waker},
294    };
295
296    use super::*;
297
298    /// A future that stays `Pending` until the shared flag is set. It ignores
299    /// the passed waker: the tests decide when to poll again.
300    struct Gate<T: Clone> {
301        open: Rc<Cell<bool>>,
302        value: T,
303    }
304
305    impl<T: Clone> Future for Gate<T> {
306        type Output = T;
307
308        fn poll(self: Pin<&mut Self>, _cx: &mut Context<'_>) -> Poll<T> {
309            if self.open.get() {
310                Poll::Ready(self.value.clone())
311            } else {
312                Poll::Pending
313            }
314        }
315    }
316
317    /// A future whose poll always panics.
318    struct Boom;
319
320    impl Future for Boom {
321        type Output = u32;
322
323        fn poll(self: Pin<&mut Self>, _cx: &mut Context<'_>) -> Poll<u32> {
324            panic!("boom")
325        }
326    }
327
328    /// A waker that counts how many times it was woken.
329    struct CountWaker(Arc<AtomicUsize>);
330
331    impl Wake for CountWaker {
332        fn wake(self: Arc<Self>) {
333            self.0.fetch_add(1, Ordering::SeqCst);
334        }
335
336        fn wake_by_ref(self: &Arc<Self>) {
337            self.0.fetch_add(1, Ordering::SeqCst);
338        }
339    }
340
341    fn panic_message(payload: &(dyn std::any::Any + Send)) -> String {
342        payload
343            .downcast_ref::<&str>()
344            .map(ToString::to_string)
345            .or_else(|| payload.downcast_ref::<String>().cloned())
346            .expect("panic payload is a string")
347    }
348
349    /// Poll an `Unpin` future in place.
350    fn poll_unpin<F: Future + Unpin>(fut: &mut F, cx: &mut Context<'_>) -> Poll<F::Output> {
351        Pin::new(fut).poll(cx)
352    }
353
354    #[test]
355    fn initializer_and_waiter_share_one_run() {
356        let runs = Rc::new(Cell::new(0u32));
357        let open = Rc::new(Cell::new(false));
358        let cell = AsyncOnceCell::new();
359        let make_init = {
360            let runs = runs.clone();
361            let open = open.clone();
362            move || {
363                runs.set(runs.get() + 1);
364                Gate {
365                    open: open.clone(),
366                    value: 42,
367                }
368            }
369        };
370
371        let mut init = cell.get_or_init(make_init);
372        let mut waiter = cell.get_or_init(|| Gate {
373            open: Rc::new(Cell::new(true)),
374            value: 0,
375        });
376
377        let wake_count = Arc::new(AtomicUsize::new(0));
378        let waker = Waker::from(Arc::new(CountWaker(wake_count.clone())));
379        let mut waiter_cx = Context::from_waker(&waker);
380        let mut init_cx = Context::from_waker(Waker::noop());
381
382        assert_eq!(poll_unpin(&mut init, &mut init_cx), Poll::Pending); // body started, gate closed
383        assert_eq!(runs.get(), 1);
384        assert_eq!(poll_unpin(&mut waiter, &mut waiter_cx), Poll::Pending); // parked as waiter
385        assert_eq!(wake_count.load(Ordering::SeqCst), 0);
386
387        open.set(true);
388        let Poll::Ready(first) = poll_unpin(&mut init, &mut init_cx) else {
389            panic!("initializer finished")
390        };
391        assert_eq!(*first, 42);
392        assert_eq!(wake_count.load(Ordering::SeqCst), 1); // waiter was woken
393
394        let Poll::Ready(second) = poll_unpin(&mut waiter, &mut waiter_cx) else {
395            panic!("waiter resolved")
396        };
397        assert!(std::ptr::eq(first, second)); // both share the cached value
398        assert_eq!(runs.get(), 1);
399    }
400
401    #[test]
402    fn dropping_the_initializer_rolls_back_and_wakes() {
403        let runs = Rc::new(Cell::new(0u32));
404        let open = Rc::new(Cell::new(false));
405        let cell = AsyncOnceCell::new();
406        let make = {
407            let runs = runs.clone();
408            let open = open.clone();
409            move || {
410                runs.set(runs.get() + 1);
411                Gate {
412                    open: open.clone(),
413                    value: 42,
414                }
415            }
416        };
417
418        let wake_count = Arc::new(AtomicUsize::new(0));
419        let waker = Waker::from(Arc::new(CountWaker(wake_count.clone())));
420        let mut cx = Context::from_waker(&waker);
421
422        let mut init = cell.get_or_init(make.clone());
423        let mut waiter = cell.get_or_init(make.clone());
424        let mut noop_cx = Context::from_waker(Waker::noop());
425        assert_eq!(poll_unpin(&mut init, &mut noop_cx), Poll::Pending);
426        assert_eq!(poll_unpin(&mut waiter, &mut cx), Poll::Pending);
427        assert_eq!(runs.get(), 1);
428
429        drop(init); // cancelled: the cell rolls back and wakes the waiter
430        assert_eq!(wake_count.load(Ordering::SeqCst), 1);
431
432        // the waiter claims initialization and runs the body again
433        assert_eq!(poll_unpin(&mut waiter, &mut cx), Poll::Pending);
434        assert_eq!(runs.get(), 2);
435
436        open.set(true);
437        let Poll::Ready(v) = poll_unpin(&mut waiter, &mut cx) else {
438            panic!("waiter finished its own initialization")
439        };
440        assert_eq!(*v, 42);
441
442        // Ready is terminal: a later caller gets the value without a new run
443        let mut late = cell.get_or_init(make);
444        let Poll::Ready(late_v) = poll_unpin(&mut late, &mut cx) else {
445            panic!("late caller resolved")
446        };
447        assert!(std::ptr::eq(v, late_v));
448        assert_eq!(runs.get(), 2);
449    }
450
451    #[test]
452    fn panic_in_the_initializer_is_retryable() {
453        let runs = Rc::new(Cell::new(0u32));
454        let cell = AsyncOnceCell::new();
455        let mut first = {
456            let runs = runs.clone();
457            cell.get_or_init(move || {
458                runs.set(runs.get() + 1);
459                Boom
460            })
461        };
462        let mut cx = Context::from_waker(Waker::noop());
463
464        let panicked = catch_unwind(AssertUnwindSafe(|| poll_unpin(&mut first, &mut cx)));
465        assert!(panicked.is_err());
466        drop(first); // the aborted initializer rolls the cell back
467        assert_eq!(runs.get(), 1);
468
469        let mut second = {
470            let runs = runs.clone();
471            cell.get_or_init(move || {
472                runs.set(runs.get() + 1);
473                Gate {
474                    open: Rc::new(Cell::new(true)),
475                    value: 7,
476                }
477            })
478        };
479        let Poll::Ready(v) = poll_unpin(&mut second, &mut cx) else {
480            panic!("second attempt succeeded")
481        };
482        assert_eq!(*v, 7);
483        assert_eq!(runs.get(), 2);
484    }
485
486    #[test]
487    fn panicking_initializer_closure_is_retryable() {
488        // the closure itself panicking (between claiming `Init` and building
489        // the future) must roll the cell back too
490        let runs = Rc::new(Cell::new(0u32));
491        let cell = AsyncOnceCell::new();
492        let mut first = {
493            let runs = runs.clone();
494            cell.get_or_init(move || -> Gate<u32> {
495                runs.set(runs.get() + 1);
496                panic!("closure boom");
497            })
498        };
499        let mut cx = Context::from_waker(Waker::noop());
500
501        let panicked = catch_unwind(AssertUnwindSafe(|| poll_unpin(&mut first, &mut cx)));
502        assert!(panicked.is_err());
503        drop(first);
504        assert_eq!(runs.get(), 1);
505
506        let mut second = cell.get_or_init(|| Gate {
507            open: Rc::new(Cell::new(true)),
508            value: 5,
509        });
510        let Poll::Ready(v) = poll_unpin(&mut second, &mut cx) else {
511            panic!("second attempt succeeded")
512        };
513        assert_eq!(*v, 5);
514    }
515
516    #[test]
517    fn reentering_the_cell_panics() {
518        struct Reenter<'a> {
519            cell: &'a AsyncOnceCell<u32>,
520        }
521
522        impl Future for Reenter<'_> {
523            type Output = u32;
524
525            fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<u32> {
526                // re-enter the same cell while its initializer is on the stack
527                let mut inner = self.cell.get_or_init(|| Gate {
528                    open: Rc::new(Cell::new(true)),
529                    value: 1,
530                });
531                let _ = poll_unpin(&mut inner, cx);
532                Poll::Ready(0)
533            }
534        }
535
536        let cell = AsyncOnceCell::new();
537        let mut init = cell.get_or_init(|| Reenter { cell: &cell });
538        let mut cx = Context::from_waker(Waker::noop());
539
540        let payload = catch_unwind(AssertUnwindSafe(|| poll_unpin(&mut init, &mut cx)))
541            .expect_err("must panic");
542        // `&*` must be explicit: `&payload` would unsizing-coerce the `Box`
543        // itself into the trait object, so every downcast inside would miss
544        let message = panic_message(&*payload);
545        assert!(
546            message.contains("re-entered while it is initializing"),
547            "unexpected message: {message}"
548        );
549        drop(init);
550    }
551
552    #[test]
553    fn polling_distinct_cells_never_panics() {
554        let a = AsyncOnceCell::new();
555        let b = AsyncOnceCell::new();
556        let open = Rc::new(Cell::new(false));
557        let make = {
558            let open = open.clone();
559            move || Gate {
560                open: open.clone(),
561                value: 3,
562            }
563        };
564
565        let mut fa = a.get_or_init(make.clone());
566        let mut fb = b.get_or_init(make);
567        let mut cx = Context::from_waker(Waker::noop());
568
569        // interleaved polls of two initializing cells under a noop waker
570        assert_eq!(poll_unpin(&mut fa, &mut cx), Poll::Pending);
571        assert_eq!(poll_unpin(&mut fb, &mut cx), Poll::Pending);
572        assert_eq!(poll_unpin(&mut fa, &mut cx), Poll::Pending);
573        assert_eq!(poll_unpin(&mut fb, &mut cx), Poll::Pending);
574
575        open.set(true);
576        let Poll::Ready(va) = poll_unpin(&mut fa, &mut cx) else {
577            panic!("a resolved")
578        };
579        let Poll::Ready(vb) = poll_unpin(&mut fb, &mut cx) else {
580            panic!("b resolved")
581        };
582        assert_eq!((*va, *vb), (3, 3));
583    }
584
585    #[test]
586    fn initializing_another_cell_from_an_initializer_is_allowed() {
587        struct Nested<'b> {
588            inner: &'b AsyncOnceCell<u32>,
589        }
590
591        impl Future for Nested<'_> {
592            type Output = u32;
593
594            fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<u32> {
595                let mut inner = self.inner.get_or_init(|| Gate {
596                    open: Rc::new(Cell::new(true)),
597                    value: 9,
598                });
599                let Poll::Ready(v) = poll_unpin(&mut inner, cx) else {
600                    return Poll::Pending;
601                };
602                Poll::Ready(v + 1)
603            }
604        }
605
606        let outer = AsyncOnceCell::new();
607        let inner = AsyncOnceCell::new();
608        let mut fut = outer.get_or_init(|| Nested { inner: &inner });
609        let mut cx = Context::from_waker(Waker::noop());
610
611        let Poll::Ready(v) = poll_unpin(&mut fut, &mut cx) else {
612            panic!("nested initialization completed inline")
613        };
614        assert_eq!(*v, 10);
615        assert!(matches!(*inner.lock(), State::Ready(9)));
616    }
617}