1use std::{
4 cell::Cell,
5 future::Future,
6 mem,
7 pin::Pin,
8 sync::{Mutex, MutexGuard},
9 task::{Context, Poll, Waker},
10};
11
12pub struct AsyncOnceCell<T> {
52 state: Mutex<State<T>>,
53}
54
55enum State<T> {
56 New,
58 Init { wakers: Vec<Waker> },
60 Ready(T),
62}
63
64unsafe impl<T: Send> Send for AsyncOnceCell<T> {}
69unsafe impl<T: Send + Sync> Sync for AsyncOnceCell<T> {}
70
71thread_local! {
72 static POLLING: Cell<usize> = const { Cell::new(0) };
78}
79
80struct 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 pub const fn new() -> Self {
93 Self {
94 state: Mutex::new(State::New),
95 }
96 }
97
98 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 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 #[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 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
161pub struct GetOrInit<'a, T, F, Fut> {
164 cell: &'a AsyncOnceCell<T>,
165 f: Option<F>,
167 fut: Option<Pin<Box<Fut>>>,
169}
170
171impl<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 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 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 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 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 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 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 Vec::new()
269 }
270 };
271 for waker in wakers {
272 waker.wake();
273 }
274 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 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 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 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 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); assert_eq!(runs.get(), 1);
384 assert_eq!(poll_unpin(&mut waiter, &mut waiter_cx), Poll::Pending); 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); let Poll::Ready(second) = poll_unpin(&mut waiter, &mut waiter_cx) else {
395 panic!("waiter resolved")
396 };
397 assert!(std::ptr::eq(first, second)); 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); assert_eq!(wake_count.load(Ordering::SeqCst), 1);
431
432 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 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); 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 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 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 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 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}