use std::{
cell::Cell,
future::Future,
mem,
pin::Pin,
sync::{Mutex, MutexGuard},
task::{Context, Poll, Waker},
};
pub struct AsyncOnceCell<T> {
state: Mutex<State<T>>,
}
enum State<T> {
New,
Init { wakers: Vec<Waker> },
Ready(T),
}
unsafe impl<T: Send> Send for AsyncOnceCell<T> {}
unsafe impl<T: Send + Sync> Sync for AsyncOnceCell<T> {}
thread_local! {
static POLLING: Cell<usize> = const { Cell::new(0) };
}
struct RestorePolling(usize);
impl Drop for RestorePolling {
fn drop(&mut self) {
POLLING.with(|p| p.set(self.0));
}
}
impl<T> AsyncOnceCell<T> {
pub const fn new() -> Self {
Self {
state: Mutex::new(State::New),
}
}
pub fn get_or_init<F, Fut>(&self, f: F) -> GetOrInit<'_, T, F, Fut>
where
F: FnOnce() -> Fut,
Fut: Future<Output = T>,
{
GetOrInit {
cell: self,
f: Some(f),
fut: None,
}
}
fn assert_not_reentrant(&self) {
let addr = std::ptr::from_ref::<Self>(self) as usize;
assert!(
POLLING.with(Cell::get) != addr,
"an async once fn was re-entered while it is initializing; this would deadlock"
);
}
#[allow(clippy::unused_self)]
unsafe fn ready_ref(&self, ptr: *const T) -> &T {
unsafe { &*ptr }
}
fn lock(&self) -> MutexGuard<'_, State<T>> {
self.state
.lock()
.unwrap_or_else(std::sync::PoisonError::into_inner)
}
}
impl<T> Default for AsyncOnceCell<T> {
fn default() -> Self {
Self::new()
}
}
pub struct GetOrInit<'a, T, F, Fut> {
cell: &'a AsyncOnceCell<T>,
f: Option<F>,
fut: Option<Pin<Box<Fut>>>,
}
impl<T, F, Fut> Unpin for GetOrInit<'_, T, F, Fut> {}
impl<'a, T, F, Fut> Future for GetOrInit<'a, T, F, Fut>
where
F: FnOnce() -> Fut,
Fut: Future<Output = T>,
{
type Output = &'a T;
fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
let this = self.get_mut();
{
let mut state = this.cell.lock();
match &mut *state {
State::Ready(v) => {
let ptr: *const T = v;
return Poll::Ready(unsafe { this.cell.ready_ref(ptr) });
},
State::New => *state = State::Init { wakers: Vec::new() },
State::Init { wakers } if this.fut.is_none() => {
this.cell.assert_not_reentrant();
if !wakers.last().is_some_and(|w| w.will_wake(cx.waker())) {
wakers.push(cx.waker().clone());
}
return Poll::Pending;
},
State::Init { .. } => {},
}
}
if this.fut.is_none() {
let f = this
.f
.take()
.expect("the initializer keeps its closure until the future is built");
this.fut = Some(Box::pin(f()));
}
let saved = POLLING.with(|p| p.replace(std::ptr::from_ref(this.cell) as usize));
let _restore = RestorePolling(saved);
let out = this
.fut
.as_mut()
.expect("initializer future")
.as_mut()
.poll(cx);
match out {
Poll::Pending => Poll::Pending,
Poll::Ready(v) => {
let (ptr, wakers): (*const T, Vec<Waker>) = {
let mut state = this.cell.lock();
let old = mem::replace(&mut *state, State::Ready(v));
let State::Ready(ptr) = &*state else {
unreachable!("`Ready` was just stored")
};
match old {
State::Init { wakers } => (ptr, wakers),
_ => unreachable!("only the initializer stores `Ready`"),
}
};
for waker in wakers {
waker.wake();
}
Poll::Ready(unsafe { this.cell.ready_ref(ptr) })
},
}
}
}
impl<T, F, Fut> Drop for GetOrInit<'_, T, F, Fut> {
fn drop(&mut self) {
if self.f.is_none() || self.fut.is_some() {
let wakers = {
let mut state = self.cell.lock();
if let State::Init { wakers } = &mut *state {
let taken = mem::take(wakers);
*state = State::New;
taken
} else {
Vec::new()
}
};
for waker in wakers {
waker.wake();
}
drop(self.fut.take());
}
}
}
#[cfg(test)]
mod tests {
use std::{
cell::Cell,
future::Future,
panic::{AssertUnwindSafe, catch_unwind},
rc::Rc,
sync::{
Arc,
atomic::{AtomicUsize, Ordering},
},
task::{Context, Poll, Wake, Waker},
};
use super::*;
struct Gate<T: Clone> {
open: Rc<Cell<bool>>,
value: T,
}
impl<T: Clone> Future for Gate<T> {
type Output = T;
fn poll(self: Pin<&mut Self>, _cx: &mut Context<'_>) -> Poll<T> {
if self.open.get() {
Poll::Ready(self.value.clone())
} else {
Poll::Pending
}
}
}
struct Boom;
impl Future for Boom {
type Output = u32;
fn poll(self: Pin<&mut Self>, _cx: &mut Context<'_>) -> Poll<u32> {
panic!("boom")
}
}
struct CountWaker(Arc<AtomicUsize>);
impl Wake for CountWaker {
fn wake(self: Arc<Self>) {
self.0.fetch_add(1, Ordering::SeqCst);
}
fn wake_by_ref(self: &Arc<Self>) {
self.0.fetch_add(1, Ordering::SeqCst);
}
}
fn panic_message(payload: &(dyn std::any::Any + Send)) -> String {
payload
.downcast_ref::<&str>()
.map(ToString::to_string)
.or_else(|| payload.downcast_ref::<String>().cloned())
.expect("panic payload is a string")
}
fn poll_unpin<F: Future + Unpin>(fut: &mut F, cx: &mut Context<'_>) -> Poll<F::Output> {
Pin::new(fut).poll(cx)
}
#[test]
fn initializer_and_waiter_share_one_run() {
let runs = Rc::new(Cell::new(0u32));
let open = Rc::new(Cell::new(false));
let cell = AsyncOnceCell::new();
let make_init = {
let runs = runs.clone();
let open = open.clone();
move || {
runs.set(runs.get() + 1);
Gate {
open: open.clone(),
value: 42,
}
}
};
let mut init = cell.get_or_init(make_init);
let mut waiter = cell.get_or_init(|| Gate {
open: Rc::new(Cell::new(true)),
value: 0,
});
let wake_count = Arc::new(AtomicUsize::new(0));
let waker = Waker::from(Arc::new(CountWaker(wake_count.clone())));
let mut waiter_cx = Context::from_waker(&waker);
let mut init_cx = Context::from_waker(Waker::noop());
assert_eq!(poll_unpin(&mut init, &mut init_cx), Poll::Pending); assert_eq!(runs.get(), 1);
assert_eq!(poll_unpin(&mut waiter, &mut waiter_cx), Poll::Pending); assert_eq!(wake_count.load(Ordering::SeqCst), 0);
open.set(true);
let Poll::Ready(first) = poll_unpin(&mut init, &mut init_cx) else {
panic!("initializer finished")
};
assert_eq!(*first, 42);
assert_eq!(wake_count.load(Ordering::SeqCst), 1);
let Poll::Ready(second) = poll_unpin(&mut waiter, &mut waiter_cx) else {
panic!("waiter resolved")
};
assert!(std::ptr::eq(first, second)); assert_eq!(runs.get(), 1);
}
#[test]
fn dropping_the_initializer_rolls_back_and_wakes() {
let runs = Rc::new(Cell::new(0u32));
let open = Rc::new(Cell::new(false));
let cell = AsyncOnceCell::new();
let make = {
let runs = runs.clone();
let open = open.clone();
move || {
runs.set(runs.get() + 1);
Gate {
open: open.clone(),
value: 42,
}
}
};
let wake_count = Arc::new(AtomicUsize::new(0));
let waker = Waker::from(Arc::new(CountWaker(wake_count.clone())));
let mut cx = Context::from_waker(&waker);
let mut init = cell.get_or_init(make.clone());
let mut waiter = cell.get_or_init(make.clone());
let mut noop_cx = Context::from_waker(Waker::noop());
assert_eq!(poll_unpin(&mut init, &mut noop_cx), Poll::Pending);
assert_eq!(poll_unpin(&mut waiter, &mut cx), Poll::Pending);
assert_eq!(runs.get(), 1);
drop(init); assert_eq!(wake_count.load(Ordering::SeqCst), 1);
assert_eq!(poll_unpin(&mut waiter, &mut cx), Poll::Pending);
assert_eq!(runs.get(), 2);
open.set(true);
let Poll::Ready(v) = poll_unpin(&mut waiter, &mut cx) else {
panic!("waiter finished its own initialization")
};
assert_eq!(*v, 42);
let mut late = cell.get_or_init(make);
let Poll::Ready(late_v) = poll_unpin(&mut late, &mut cx) else {
panic!("late caller resolved")
};
assert!(std::ptr::eq(v, late_v));
assert_eq!(runs.get(), 2);
}
#[test]
fn panic_in_the_initializer_is_retryable() {
let runs = Rc::new(Cell::new(0u32));
let cell = AsyncOnceCell::new();
let mut first = {
let runs = runs.clone();
cell.get_or_init(move || {
runs.set(runs.get() + 1);
Boom
})
};
let mut cx = Context::from_waker(Waker::noop());
let panicked = catch_unwind(AssertUnwindSafe(|| poll_unpin(&mut first, &mut cx)));
assert!(panicked.is_err());
drop(first); assert_eq!(runs.get(), 1);
let mut second = {
let runs = runs.clone();
cell.get_or_init(move || {
runs.set(runs.get() + 1);
Gate {
open: Rc::new(Cell::new(true)),
value: 7,
}
})
};
let Poll::Ready(v) = poll_unpin(&mut second, &mut cx) else {
panic!("second attempt succeeded")
};
assert_eq!(*v, 7);
assert_eq!(runs.get(), 2);
}
#[test]
fn panicking_initializer_closure_is_retryable() {
let runs = Rc::new(Cell::new(0u32));
let cell = AsyncOnceCell::new();
let mut first = {
let runs = runs.clone();
cell.get_or_init(move || -> Gate<u32> {
runs.set(runs.get() + 1);
panic!("closure boom");
})
};
let mut cx = Context::from_waker(Waker::noop());
let panicked = catch_unwind(AssertUnwindSafe(|| poll_unpin(&mut first, &mut cx)));
assert!(panicked.is_err());
drop(first);
assert_eq!(runs.get(), 1);
let mut second = cell.get_or_init(|| Gate {
open: Rc::new(Cell::new(true)),
value: 5,
});
let Poll::Ready(v) = poll_unpin(&mut second, &mut cx) else {
panic!("second attempt succeeded")
};
assert_eq!(*v, 5);
}
#[test]
fn reentering_the_cell_panics() {
struct Reenter<'a> {
cell: &'a AsyncOnceCell<u32>,
}
impl Future for Reenter<'_> {
type Output = u32;
fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<u32> {
let mut inner = self.cell.get_or_init(|| Gate {
open: Rc::new(Cell::new(true)),
value: 1,
});
let _ = poll_unpin(&mut inner, cx);
Poll::Ready(0)
}
}
let cell = AsyncOnceCell::new();
let mut init = cell.get_or_init(|| Reenter { cell: &cell });
let mut cx = Context::from_waker(Waker::noop());
let payload = catch_unwind(AssertUnwindSafe(|| poll_unpin(&mut init, &mut cx)))
.expect_err("must panic");
let message = panic_message(&*payload);
assert!(
message.contains("re-entered while it is initializing"),
"unexpected message: {message}"
);
drop(init);
}
#[test]
fn polling_distinct_cells_never_panics() {
let a = AsyncOnceCell::new();
let b = AsyncOnceCell::new();
let open = Rc::new(Cell::new(false));
let make = {
let open = open.clone();
move || Gate {
open: open.clone(),
value: 3,
}
};
let mut fa = a.get_or_init(make.clone());
let mut fb = b.get_or_init(make);
let mut cx = Context::from_waker(Waker::noop());
assert_eq!(poll_unpin(&mut fa, &mut cx), Poll::Pending);
assert_eq!(poll_unpin(&mut fb, &mut cx), Poll::Pending);
assert_eq!(poll_unpin(&mut fa, &mut cx), Poll::Pending);
assert_eq!(poll_unpin(&mut fb, &mut cx), Poll::Pending);
open.set(true);
let Poll::Ready(va) = poll_unpin(&mut fa, &mut cx) else {
panic!("a resolved")
};
let Poll::Ready(vb) = poll_unpin(&mut fb, &mut cx) else {
panic!("b resolved")
};
assert_eq!((*va, *vb), (3, 3));
}
#[test]
fn initializing_another_cell_from_an_initializer_is_allowed() {
struct Nested<'b> {
inner: &'b AsyncOnceCell<u32>,
}
impl Future for Nested<'_> {
type Output = u32;
fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<u32> {
let mut inner = self.inner.get_or_init(|| Gate {
open: Rc::new(Cell::new(true)),
value: 9,
});
let Poll::Ready(v) = poll_unpin(&mut inner, cx) else {
return Poll::Pending;
};
Poll::Ready(v + 1)
}
}
let outer = AsyncOnceCell::new();
let inner = AsyncOnceCell::new();
let mut fut = outer.get_or_init(|| Nested { inner: &inner });
let mut cx = Context::from_waker(Waker::noop());
let Poll::Ready(v) = poll_unpin(&mut fut, &mut cx) else {
panic!("nested initialization completed inline")
};
assert_eq!(*v, 10);
assert!(matches!(*inner.lock(), State::Ready(9)));
}
}