async-deferred 0.4.0

A lightweight utility for spawning async tasks with fire-and-forget semantics and deferred result retrieval.
Documentation
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
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
//! The heap-based [`Deferred`].

use alloc::string::String;
use alloc::sync::Arc;
use core::future::{Future, IntoFuture};
use core::pin::Pin;
use core::sync::atomic::{AtomicU8, Ordering};
use core::task::{Context, Poll};

use futures_channel::oneshot;
use futures_util::future::{AbortHandle, Abortable};

#[cfg(feature = "tokio")]
use crate::Tokio;
use crate::{BeginError, Error, LocalSpawner, SpawnError, Spawner, State};

/// What the task sends back: the value and the callback's panic message, or the task's
/// panic message.
type Outcome<T> = Result<(T, Option<String>), String>;

#[derive(Debug)]
enum Inner<T> {
    NotStarted,
    Running {
        receiver: oneshot::Receiver<Outcome<T>>,
        abort: AbortHandle,
        /// Set by the task once it has finished; see [`TaskStatus`].
        status: Arc<AtomicU8>,
    },
    Done {
        value: T,
        callback_panic: Option<String>,
    },
    Panicked(String),
    Cancelled,
}

/// A background task whose result you can check or collect later.
///
/// Tasks run on any async runtime through a [`Spawner`]. With the default `tokio`
/// feature, [`start`](Self::start) and [`begin`](Self::begin) spawn on the current
/// Tokio runtime.
///
/// The result is kept until you [`take`](Self::take) it or drop the `Deferred`.
/// Dropping a `Deferred` does not stop its task; use [`cancel`](Self::cancel) for that.
///
/// # Examples
///
/// ```rust
/// use async_deferred::Deferred;
///
/// # tokio_test::block_on(async {
/// let mut deferred = Deferred::start(async { 42 });
///
/// // ... do other work ...
///
/// assert_eq!(deferred.join().await, Ok(&42));
/// # })
/// ```
#[derive(Debug)]
pub struct Deferred<T> {
    inner: Inner<T>,
}

impl<T> Deferred<T> {
    /// Creates a `Deferred` with no task. Start one with [`begin_on`](Self::begin_on).
    pub fn new() -> Self {
        Self {
            inner: Inner::NotStarted,
        }
    }

    /// Spawns `future` with `spawner` and returns its `Deferred`.
    ///
    /// Returns an error if the runtime could not start the task, for example because its
    /// task pool is full. See [`Spawner`] for using your own runtime.
    ///
    /// ```rust
    /// use async_deferred::Deferred;
    ///
    /// // Start a task from outside a Tokio runtime
    /// let runtime = tokio::runtime::Runtime::new().unwrap();
    /// let mut deferred = Deferred::start_on(runtime.handle(), async { 42 }).unwrap();
    /// assert_eq!(runtime.block_on(deferred.join()), Ok(&42));
    /// ```
    pub fn start_on<S, F>(spawner: &S, future: F) -> Result<Self, SpawnError>
    where
        S: Spawner,
        F: Future<Output = T> + Send + 'static,
        T: Send + 'static,
    {
        let mut deferred = Self::new();
        deferred
            .begin_on(spawner, future)
            .map_err(BeginError::into_spawn_error)?;
        Ok(deferred)
    }

    /// Like [`start_on`](Self::start_on), and runs `callback` with the result once
    /// `future` finishes.
    ///
    /// The callback is not run if `future` panics, or if the task is cancelled or dropped by
    /// the runtime.
    pub fn start_with_callback_on<S, F, C>(
        spawner: &S,
        future: F,
        callback: C,
    ) -> Result<Self, SpawnError>
    where
        S: Spawner,
        F: Future<Output = T> + Send + 'static,
        C: FnOnce(&T) + Send + 'static,
        T: Send + 'static,
    {
        let mut deferred = Self::new();
        deferred
            .begin_with_callback_on(spawner, future, callback)
            .map_err(BeginError::into_spawn_error)?;
        Ok(deferred)
    }

    /// Spawns `future` with `spawner`.
    ///
    /// Returns an error and does nothing if a task is running or its result has not been
    /// taken, or if the runtime could not start the task. A task that panicked or was
    /// dropped by the runtime does not prevent starting a new one.
    pub fn begin_on<S, F>(&mut self, spawner: &S, future: F) -> Result<(), BeginError>
    where
        S: Spawner,
        F: Future<Output = T> + Send + 'static,
        T: Send + 'static,
    {
        self.begin_with_callback_on(spawner, future, |_: &T| {})
    }

    /// Like [`begin_on`](Self::begin_on), and runs `callback` with the result once
    /// `future` finishes.
    ///
    /// The callback is not run if `future` panics, or if the task is cancelled or dropped by
    /// the runtime.
    pub fn begin_with_callback_on<S, F, C>(
        &mut self,
        spawner: &S,
        future: F,
        callback: C,
    ) -> Result<(), BeginError>
    where
        S: Spawner,
        F: Future<Output = T> + Send + 'static,
        C: FnOnce(&T) + Send + 'static,
        T: Send + 'static,
    {
        if self.is_busy() {
            return Err(BeginError::AlreadyStarted);
        }
        let (task, running) = task(future, callback);
        spawner.spawn(task)?;
        self.inner = running;
        Ok(())
    }

    /// Like [`start_on`](Self::start_on), for futures that are not `Send`.
    pub fn start_local_on<S, F>(spawner: &S, future: F) -> Result<Self, SpawnError>
    where
        S: LocalSpawner,
        F: Future<Output = T> + 'static,
        T: 'static,
    {
        let mut deferred = Self::new();
        deferred
            .begin_local_on(spawner, future)
            .map_err(BeginError::into_spawn_error)?;
        Ok(deferred)
    }

    /// Like [`start_with_callback_on`](Self::start_with_callback_on), for futures that
    /// are not `Send`.
    pub fn start_with_callback_local_on<S, F, C>(
        spawner: &S,
        future: F,
        callback: C,
    ) -> Result<Self, SpawnError>
    where
        S: LocalSpawner,
        F: Future<Output = T> + 'static,
        C: FnOnce(&T) + 'static,
        T: 'static,
    {
        let mut deferred = Self::new();
        deferred
            .begin_with_callback_local_on(spawner, future, callback)
            .map_err(BeginError::into_spawn_error)?;
        Ok(deferred)
    }

    /// Like [`begin_on`](Self::begin_on), for futures that are not `Send`.
    pub fn begin_local_on<S, F>(&mut self, spawner: &S, future: F) -> Result<(), BeginError>
    where
        S: LocalSpawner,
        F: Future<Output = T> + 'static,
        T: 'static,
    {
        self.begin_with_callback_local_on(spawner, future, |_: &T| {})
    }

    /// Like [`begin_with_callback_on`](Self::begin_with_callback_on), for futures that
    /// are not `Send`.
    pub fn begin_with_callback_local_on<S, F, C>(
        &mut self,
        spawner: &S,
        future: F,
        callback: C,
    ) -> Result<(), BeginError>
    where
        S: LocalSpawner,
        F: Future<Output = T> + 'static,
        C: FnOnce(&T) + 'static,
        T: 'static,
    {
        if self.is_busy() {
            return Err(BeginError::AlreadyStarted);
        }
        let (task, running) = task(future, callback);
        spawner.spawn_local(task)?;
        self.inner = running;
        Ok(())
    }

    /// Whether a task is running or its result is waiting to be taken.
    fn is_busy(&mut self) -> bool {
        self.poll_task();
        matches!(self.inner, Inner::Running { .. } | Inner::Done { .. })
    }

    /// If the task has finished, stores its outcome. Never waits.
    fn poll_task(&mut self) {
        let Inner::Running { receiver, .. } = &mut self.inner else {
            return;
        };
        match receiver.try_recv() {
            Ok(None) => {}
            Ok(Some(outcome)) => self.inner = Inner::finished(Some(outcome)),
            Err(oneshot::Canceled) => self.inner = Inner::finished(None),
        }
    }

    /// Waits for the task to finish and returns its result.
    ///
    /// Returns immediately if the task already finished. If the task finished but its
    /// callback panicked, the result is still returned; check [`state`](Self::state)
    /// to detect that.
    ///
    /// ```rust
    /// use async_deferred::{Deferred, Error};
    ///
    /// # tokio_test::block_on(async {
    /// let mut deferred: Deferred<u32> = Deferred::start(async { panic!("boom") });
    /// assert_eq!(deferred.join().await, Err(Error::Panicked("boom".into())));
    /// # })
    /// ```
    pub async fn join(&mut self) -> Result<&T, Error> {
        if let Inner::Running { receiver, .. } = &mut self.inner {
            let outcome = receiver.await.ok();
            self.inner = Inner::finished(outcome);
        }
        match &self.inner {
            Inner::Done { value, .. } => Ok(value),
            Inner::Panicked(msg) => Err(Error::Panicked(msg.clone())),
            Inner::Cancelled => Err(Error::Cancelled),
            Inner::NotStarted => Err(Error::NotStarted),
            Inner::Running { .. } => unreachable!("the task was awaited above"),
        }
    }

    /// Waits for the task to finish and returns its result, consuming the `Deferred`.
    ///
    /// Same as `.await` on the `Deferred`. If the task finished but its callback panicked,
    /// the result is still returned. Dropping the returned future before it finishes does
    /// not stop the task.
    ///
    /// ```rust
    /// use async_deferred::Deferred;
    ///
    /// # tokio_test::block_on(async {
    /// let deferred = Deferred::start(async { String::from("done") });
    /// let value: String = deferred.into_result().await.unwrap();
    /// assert_eq!(value, "done");
    ///
    /// // `.await` on a `Deferred` does the same
    /// let deferred = Deferred::start(async { 42 });
    /// assert_eq!(deferred.await, Ok(42));
    /// # })
    /// ```
    pub fn into_result(self) -> IntoResult<T> {
        IntoResult { deferred: self }
    }

    /// Returns the current [`State`] without waiting.
    ///
    /// The state is a snapshot: a task that has just finished may still show as
    /// [`State::Pending`] for an instant. Once it shows as finished, its result is
    /// available to [`try_get`](Self::try_get), [`take`](Self::take) and
    /// [`join`](Self::join).
    pub fn state(&self) -> State {
        match &self.inner {
            Inner::NotStarted => State::NotStarted,
            Inner::Running { status, .. } => TaskStatus::load(status),
            Inner::Done {
                callback_panic: None,
                ..
            } => State::Completed,
            Inner::Done {
                callback_panic: Some(_),
                ..
            } => State::CallbackPanicked,
            Inner::Panicked(_) => State::TaskPanicked,
            Inner::Cancelled => State::Cancelled,
        }
    }

    /// Returns the panic message if the task or its callback panicked.
    ///
    /// Catching a panic does not silence it: the panic hook still reports it, as for any
    /// other panic.
    pub fn panic_message(&mut self) -> Option<&str> {
        self.poll_task();
        match &self.inner {
            Inner::Panicked(msg)
            | Inner::Done {
                callback_panic: Some(msg),
                ..
            } => Some(msg),
            _ => None,
        }
    }

    /// Returns the result if the task has finished, without waiting.
    pub fn try_get(&mut self) -> Option<&T> {
        self.poll_task();
        match &self.inner {
            Inner::Done { value, .. } => Some(value),
            _ => None,
        }
    }

    /// Moves the result out if the task has finished, without waiting.
    ///
    /// On success, the `Deferred` is reset and can start a new task.
    ///
    /// ```rust
    /// use async_deferred::{Deferred, State};
    ///
    /// # tokio_test::block_on(async {
    /// let mut deferred = Deferred::start(async { vec![1, 2, 3] });
    /// deferred.join().await.unwrap();
    /// assert_eq!(deferred.take(), Some(vec![1, 2, 3]));
    /// assert_eq!(deferred.state(), State::NotStarted);
    /// # })
    /// ```
    pub fn take(&mut self) -> Option<T> {
        self.poll_task();
        if !matches!(self.inner, Inner::Done { .. }) {
            return None;
        }
        match core::mem::replace(&mut self.inner, Inner::NotStarted) {
            Inner::Done { value, .. } => Some(value),
            _ => unreachable!("checked above"),
        }
    }

    /// Stops a running task and resets the `Deferred` so it can start a new one.
    ///
    /// The task may still be using its runtime resources, such as an embassy task pool slot,
    /// when this returns. To start a new task right away in a full task pool, use
    /// [`cancel_and_wait`](Self::cancel_and_wait) instead.
    /// Returns `false` and does nothing if no task is running.
    ///
    /// Cancelling is cooperative: the task stops at its next `.await`. Code that blocks
    /// without awaiting keeps running until it reaches one.
    ///
    /// If the task finishes just as `cancel` runs, its result is discarded and `cancel`
    /// still returns `true`. To keep a result that has already arrived, call
    /// [`take`](Self::take) first.
    ///
    /// ```rust
    /// use async_deferred::{Deferred, State};
    ///
    /// # tokio_test::block_on(async {
    /// let mut deferred = Deferred::start(std::future::pending::<u32>());
    /// assert!(deferred.cancel());
    /// assert_eq!(deferred.state(), State::NotStarted);
    /// # })
    /// ```
    pub fn cancel(&mut self) -> bool {
        self.poll_task();
        let Inner::Running { abort, .. } = &self.inner else {
            return false;
        };
        abort.abort();
        self.inner = Inner::NotStarted;
        true
    }

    /// Like [`cancel`](Self::cancel), and waits until the task has stopped.
    ///
    /// On a single-threaded executor such as embassy, its task pool slot is free when this
    /// returns, so a new task can start right away even in a full pool. The task only stops
    /// while its runtime is running, so don't await this from code that blocks the runtime.
    /// Returns `false` and does nothing if no task is running.
    ///
    /// ```rust
    /// use async_deferred::{Deferred, State};
    ///
    /// # tokio_test::block_on(async {
    /// let mut deferred = Deferred::start(std::future::pending::<u32>());
    /// assert!(deferred.cancel_and_wait().await);
    /// assert_eq!(deferred.state(), State::NotStarted);
    /// # })
    /// ```
    pub async fn cancel_and_wait(&mut self) -> bool {
        self.poll_task();
        if !matches!(self.inner, Inner::Running { .. }) {
            return false;
        }
        let Inner::Running {
            receiver, abort, ..
        } = core::mem::replace(&mut self.inner, Inner::NotStarted)
        else {
            unreachable!("checked above")
        };
        abort.abort();
        // The task sends its outcome or drops the sender as it stops.
        let _ = receiver.await;
        true
    }

    /// Returns `true` if the result is available, even if the callback panicked.
    pub fn is_ready(&self) -> bool {
        matches!(self.state(), State::Completed | State::CallbackPanicked)
    }

    /// Returns `true` if the task and its callback finished without panicking.
    pub fn is_complete(&self) -> bool {
        self.state() == State::Completed
    }

    /// Returns `true` if the task is still running.
    pub fn is_pending(&self) -> bool {
        self.state() == State::Pending
    }

    /// Returns `true` if no task has been started, or its result was taken.
    pub fn is_not_started(&self) -> bool {
        self.state() == State::NotStarted
    }

    /// Returns `true` if the task panicked.
    pub fn has_task_panicked(&self) -> bool {
        self.state() == State::TaskPanicked
    }

    /// Returns `true` if the task finished but its callback panicked.
    pub fn has_callback_panicked(&self) -> bool {
        self.state() == State::CallbackPanicked
    }

    /// Returns `true` if the runtime dropped the task before it finished.
    ///
    /// A task stopped with [`cancel`](Self::cancel) is not reported here: cancelling resets
    /// the `Deferred` to [`State::NotStarted`].
    pub fn is_cancelled(&self) -> bool {
        self.state() == State::Cancelled
    }
}

#[cfg(feature = "tokio")]
impl<T> Deferred<T> {
    /// Spawns `future` on the current Tokio runtime and returns its `Deferred`.
    ///
    /// # Panics
    ///
    /// Panics if called outside a Tokio runtime. Use [`start_on`](Self::start_on) with a
    /// [`tokio::runtime::Handle`] there.
    pub fn start<F>(future: F) -> Self
    where
        F: Future<Output = T> + Send + 'static,
        T: Send + 'static,
    {
        Self::start_on(&Tokio, future)
            .expect("`Deferred::start` was called outside a Tokio runtime")
    }

    /// Like [`start`](Self::start), and runs `callback` with the result once `future` finishes.
    ///
    /// The callback is not run if `future` panics, or if the task is cancelled or dropped by
    /// the runtime.
    ///
    /// # Panics
    ///
    /// Panics if called outside a Tokio runtime. Use
    /// [`start_with_callback_on`](Self::start_with_callback_on) with a
    /// [`tokio::runtime::Handle`] there.
    ///
    /// ```rust
    /// use async_deferred::Deferred;
    ///
    /// # tokio_test::block_on(async {
    /// let deferred = Deferred::start_with_callback(
    ///     async { 42 },
    ///     |result| println!("computed {result}"),
    /// );
    /// # })
    /// ```
    pub fn start_with_callback<F, C>(future: F, callback: C) -> Self
    where
        F: Future<Output = T> + Send + 'static,
        C: FnOnce(&T) + Send + 'static,
        T: Send + 'static,
    {
        Self::start_with_callback_on(&Tokio, future, callback)
            .expect("`Deferred::start_with_callback` was called outside a Tokio runtime")
    }

    /// Spawns `future` on the current Tokio runtime.
    ///
    /// Returns [`BeginError::AlreadyStarted`] and does nothing if a task is running or its
    /// result has not been taken. A task that panicked or was dropped by the runtime does
    /// not prevent starting a new one.
    ///
    /// Outside a Tokio runtime, returns [`BeginError::Spawn`].
    ///
    /// ```rust
    /// use async_deferred::Deferred;
    ///
    /// # tokio_test::block_on(async {
    /// let mut deferred = Deferred::new();
    /// assert!(deferred.begin(async { 42 }).is_ok());
    /// assert!(deferred.begin(async { 24 }).is_err());
    /// # })
    /// ```
    pub fn begin<F>(&mut self, future: F) -> Result<(), BeginError>
    where
        F: Future<Output = T> + Send + 'static,
        T: Send + 'static,
    {
        self.begin_on(&Tokio, future)
    }

    /// Like [`begin`](Self::begin), and runs `callback` with the result once `future` finishes.
    ///
    /// The callback is not run if `future` panics, or if the task is cancelled or dropped by
    /// the runtime.
    pub fn begin_with_callback<F, C>(&mut self, future: F, callback: C) -> Result<(), BeginError>
    where
        F: Future<Output = T> + Send + 'static,
        C: FnOnce(&T) + Send + 'static,
        T: Send + 'static,
    {
        self.begin_with_callback_on(&Tokio, future, callback)
    }
}

impl<T> IntoFuture for Deferred<T> {
    type Output = Result<T, Error>;
    type IntoFuture = IntoResult<T>;

    /// Same as [`Deferred::into_result`].
    fn into_future(self) -> IntoResult<T> {
        self.into_result()
    }
}

/// The future returned by [`Deferred::into_result`] and by `.await` on a [`Deferred`].
#[derive(Debug)]
#[must_use = "futures do nothing unless you `.await` or poll them"]
pub struct IntoResult<T> {
    deferred: Deferred<T>,
}

// The value is never pinned: it is only moved out once the task has finished.
impl<T> Unpin for IntoResult<T> {}

impl<T> Future for IntoResult<T> {
    type Output = Result<T, Error>;

    fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
        let inner = &mut self.get_mut().deferred.inner;
        if let Inner::Running { receiver, .. } = inner {
            match Pin::new(receiver).poll(cx) {
                Poll::Pending => return Poll::Pending,
                Poll::Ready(outcome) => *inner = Inner::finished(outcome.ok()),
            }
        }
        Poll::Ready(match core::mem::replace(inner, Inner::NotStarted) {
            Inner::Done { value, .. } => Ok(value),
            Inner::Panicked(msg) => Err(Error::Panicked(msg)),
            Inner::Cancelled => Err(Error::Cancelled),
            Inner::NotStarted => Err(Error::NotStarted),
            Inner::Running { .. } => unreachable!("the task was polled above"),
        })
    }
}

impl<T> Default for Deferred<T> {
    /// Same as [`Deferred::new`].
    fn default() -> Self {
        Self::new()
    }
}

impl<T> Inner<T> {
    /// `None` means the task was dropped before sending its outcome.
    fn finished(outcome: Option<Outcome<T>>) -> Self {
        match outcome {
            Some(Ok((value, callback_panic))) => Inner::Done {
                value,
                callback_panic,
            },
            Some(Err(msg)) => Inner::Panicked(msg),
            None => Inner::Cancelled,
        }
    }
}

/// Builds the task to spawn, and the `Running` state that tracks it.
///
/// The task is `Send` whenever `F`, `C` and `T` are.
fn task<T, F, C>(future: F, callback: C) -> (impl Future<Output = ()>, Inner<T>)
where
    F: Future<Output = T> + 'static,
    C: FnOnce(&T) + 'static,
    T: 'static,
{
    let (sender, receiver) = oneshot::channel();
    let (abort, abort_registration) = AbortHandle::new_pair();
    let status = Arc::new(AtomicU8::new(TaskStatus::PENDING));
    // Created now, so it also reports a task the runtime drops before ever running it.
    let reporter = Reporter {
        sender: Some(sender),
        status: status.clone(),
    };
    let task = Abortable::new(
        async move {
            let outcome = match catch_unwind(future).await {
                Ok(value) => {
                    // Catch a callback panic so the computed value is not lost with it.
                    let callback_panic = call_catching_panic(callback, &value).err();
                    Ok((value, callback_panic))
                }
                Err(msg) => Err(msg),
            };
            reporter.finish(outcome);
        },
        abort_registration,
    );
    let task = async move {
        let _ = task.await;
    };
    (
        task,
        Inner::Running {
            receiver,
            abort,
            status,
        },
    )
}

/// The values of the status flag a running task shares with its `Deferred`.
///
/// The flag lets [`Deferred::state`] work through `&self`. The task stores it after
/// sending its outcome, so once the flag says the task has finished, the outcome is in
/// the channel.
struct TaskStatus;

impl TaskStatus {
    const PENDING: u8 = 0;
    const COMPLETED: u8 = 1;
    const CALLBACK_PANICKED: u8 = 2;
    const TASK_PANICKED: u8 = 3;
    const CANCELLED: u8 = 4;

    fn load(status: &AtomicU8) -> State {
        match status.load(Ordering::Acquire) {
            Self::PENDING => State::Pending,
            Self::COMPLETED => State::Completed,
            Self::CALLBACK_PANICKED => State::CallbackPanicked,
            Self::TASK_PANICKED => State::TaskPanicked,
            _ => State::Cancelled,
        }
    }
}

/// Owned by the task: sends its outcome and sets the status flag.
///
/// If the task is dropped before finishing, it closes the channel and then marks the
/// task cancelled, in that order, so the flag never runs ahead of the channel.
struct Reporter<T> {
    sender: Option<oneshot::Sender<Outcome<T>>>,
    status: Arc<AtomicU8>,
}

impl<T> Reporter<T> {
    fn finish(mut self, outcome: Outcome<T>) {
        let status = match &outcome {
            Ok((_, None)) => TaskStatus::COMPLETED,
            Ok((_, Some(_))) => TaskStatus::CALLBACK_PANICKED,
            Err(_) => TaskStatus::TASK_PANICKED,
        };
        if let Some(sender) = self.sender.take() {
            // The `Deferred` may have been dropped; the result is then discarded.
            let _ = sender.send(outcome);
        }
        self.status.store(status, Ordering::Release);
    }
}

impl<T> Drop for Reporter<T> {
    fn drop(&mut self) {
        if let Some(sender) = self.sender.take() {
            drop(sender);
            self.status.store(TaskStatus::CANCELLED, Ordering::Release);
        }
    }
}

/// Awaits `future`, turning a panic into its message.
#[cfg(feature = "std")]
async fn catch_unwind<F: Future>(future: F) -> Result<F::Output, String> {
    use futures_util::FutureExt;
    std::panic::AssertUnwindSafe(future)
        .catch_unwind()
        .await
        .map_err(|payload| panic_message(&*payload))
}

/// Awaits `future`. Without `std`, panics cannot be caught.
#[cfg(not(feature = "std"))]
async fn catch_unwind<F: Future>(future: F) -> Result<F::Output, String> {
    Ok(future.await)
}

/// Calls `callback`, turning a panic into its message.
#[cfg(feature = "std")]
fn call_catching_panic<T, C: FnOnce(&T)>(callback: C, value: &T) -> Result<(), String> {
    std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| callback(value)))
        .map_err(|payload| panic_message(&*payload))
}

/// Calls `callback`. Without `std`, panics cannot be caught.
#[cfg(not(feature = "std"))]
fn call_catching_panic<T, C: FnOnce(&T)>(callback: C, value: &T) -> Result<(), String> {
    callback(value);
    Ok(())
}

/// Extracts a readable message from a panic payload.
#[cfg(feature = "std")]
fn panic_message(payload: &(dyn std::any::Any + Send)) -> String {
    if let Some(s) = payload.downcast_ref::<&str>() {
        s.to_string()
    } else if let Some(s) = payload.downcast_ref::<String>() {
        s.clone()
    } else {
        "unknown panic payload".to_string()
    }
}