Skip to main content

async_deferred/
deferred.rs

1//! The heap-based [`Deferred`].
2
3use alloc::string::String;
4use alloc::sync::Arc;
5use core::future::{Future, IntoFuture};
6use core::pin::Pin;
7use core::sync::atomic::{AtomicU8, Ordering};
8use core::task::{Context, Poll};
9
10use futures_channel::oneshot;
11use futures_util::future::{AbortHandle, Abortable};
12
13#[cfg(feature = "tokio")]
14use crate::Tokio;
15use crate::{BeginError, Error, LocalSpawner, SpawnError, Spawner, State};
16
17/// What the task sends back: the value and the callback's panic message, or the task's
18/// panic message.
19type Outcome<T> = Result<(T, Option<String>), String>;
20
21#[derive(Debug)]
22enum Inner<T> {
23    NotStarted,
24    Running {
25        receiver: oneshot::Receiver<Outcome<T>>,
26        abort: AbortHandle,
27        /// Set by the task once it has finished; see [`TaskStatus`].
28        status: Arc<AtomicU8>,
29    },
30    Done {
31        value: T,
32        callback_panic: Option<String>,
33    },
34    Panicked(String),
35    Cancelled,
36}
37
38/// A background task whose result you can check or collect later.
39///
40/// Tasks run on any async runtime through a [`Spawner`]. With the default `tokio`
41/// feature, [`start`](Self::start) and [`begin`](Self::begin) spawn on the current
42/// Tokio runtime.
43///
44/// The result is kept until you [`take`](Self::take) it or drop the `Deferred`.
45/// Dropping a `Deferred` does not stop its task; use [`cancel`](Self::cancel) for that.
46///
47/// # Examples
48///
49/// ```rust
50/// use async_deferred::Deferred;
51///
52/// # tokio_test::block_on(async {
53/// let mut deferred = Deferred::start(async { 42 });
54///
55/// // ... do other work ...
56///
57/// assert_eq!(deferred.join().await, Ok(&42));
58/// # })
59/// ```
60#[derive(Debug)]
61pub struct Deferred<T> {
62    inner: Inner<T>,
63}
64
65impl<T> Deferred<T> {
66    /// Creates a `Deferred` with no task. Start one with [`begin_on`](Self::begin_on).
67    pub fn new() -> Self {
68        Self {
69            inner: Inner::NotStarted,
70        }
71    }
72
73    /// Spawns `future` with `spawner` and returns its `Deferred`.
74    ///
75    /// Returns an error if the runtime could not start the task, for example because its
76    /// task pool is full. See [`Spawner`] for using your own runtime.
77    ///
78    /// ```rust
79    /// use async_deferred::Deferred;
80    ///
81    /// // Start a task from outside a Tokio runtime
82    /// let runtime = tokio::runtime::Runtime::new().unwrap();
83    /// let mut deferred = Deferred::start_on(runtime.handle(), async { 42 }).unwrap();
84    /// assert_eq!(runtime.block_on(deferred.join()), Ok(&42));
85    /// ```
86    pub fn start_on<S, F>(spawner: &S, future: F) -> Result<Self, SpawnError>
87    where
88        S: Spawner,
89        F: Future<Output = T> + Send + 'static,
90        T: Send + 'static,
91    {
92        let mut deferred = Self::new();
93        deferred
94            .begin_on(spawner, future)
95            .map_err(BeginError::into_spawn_error)?;
96        Ok(deferred)
97    }
98
99    /// Like [`start_on`](Self::start_on), and runs `callback` with the result once
100    /// `future` finishes.
101    ///
102    /// The callback is not run if `future` panics, or if the task is cancelled or dropped by
103    /// the runtime.
104    pub fn start_with_callback_on<S, F, C>(
105        spawner: &S,
106        future: F,
107        callback: C,
108    ) -> Result<Self, SpawnError>
109    where
110        S: Spawner,
111        F: Future<Output = T> + Send + 'static,
112        C: FnOnce(&T) + Send + 'static,
113        T: Send + 'static,
114    {
115        let mut deferred = Self::new();
116        deferred
117            .begin_with_callback_on(spawner, future, callback)
118            .map_err(BeginError::into_spawn_error)?;
119        Ok(deferred)
120    }
121
122    /// Spawns `future` with `spawner`.
123    ///
124    /// Returns an error and does nothing if a task is running or its result has not been
125    /// taken, or if the runtime could not start the task. A task that panicked or was
126    /// dropped by the runtime does not prevent starting a new one.
127    pub fn begin_on<S, F>(&mut self, spawner: &S, future: F) -> Result<(), BeginError>
128    where
129        S: Spawner,
130        F: Future<Output = T> + Send + 'static,
131        T: Send + 'static,
132    {
133        self.begin_with_callback_on(spawner, future, |_: &T| {})
134    }
135
136    /// Like [`begin_on`](Self::begin_on), and runs `callback` with the result once
137    /// `future` finishes.
138    ///
139    /// The callback is not run if `future` panics, or if the task is cancelled or dropped by
140    /// the runtime.
141    pub fn begin_with_callback_on<S, F, C>(
142        &mut self,
143        spawner: &S,
144        future: F,
145        callback: C,
146    ) -> Result<(), BeginError>
147    where
148        S: Spawner,
149        F: Future<Output = T> + Send + 'static,
150        C: FnOnce(&T) + Send + 'static,
151        T: Send + 'static,
152    {
153        if self.is_busy() {
154            return Err(BeginError::AlreadyStarted);
155        }
156        let (task, running) = task(future, callback);
157        spawner.spawn(task)?;
158        self.inner = running;
159        Ok(())
160    }
161
162    /// Like [`start_on`](Self::start_on), for futures that are not `Send`.
163    pub fn start_local_on<S, F>(spawner: &S, future: F) -> Result<Self, SpawnError>
164    where
165        S: LocalSpawner,
166        F: Future<Output = T> + 'static,
167        T: 'static,
168    {
169        let mut deferred = Self::new();
170        deferred
171            .begin_local_on(spawner, future)
172            .map_err(BeginError::into_spawn_error)?;
173        Ok(deferred)
174    }
175
176    /// Like [`start_with_callback_on`](Self::start_with_callback_on), for futures that
177    /// are not `Send`.
178    pub fn start_with_callback_local_on<S, F, C>(
179        spawner: &S,
180        future: F,
181        callback: C,
182    ) -> Result<Self, SpawnError>
183    where
184        S: LocalSpawner,
185        F: Future<Output = T> + 'static,
186        C: FnOnce(&T) + 'static,
187        T: 'static,
188    {
189        let mut deferred = Self::new();
190        deferred
191            .begin_with_callback_local_on(spawner, future, callback)
192            .map_err(BeginError::into_spawn_error)?;
193        Ok(deferred)
194    }
195
196    /// Like [`begin_on`](Self::begin_on), for futures that are not `Send`.
197    pub fn begin_local_on<S, F>(&mut self, spawner: &S, future: F) -> Result<(), BeginError>
198    where
199        S: LocalSpawner,
200        F: Future<Output = T> + 'static,
201        T: 'static,
202    {
203        self.begin_with_callback_local_on(spawner, future, |_: &T| {})
204    }
205
206    /// Like [`begin_with_callback_on`](Self::begin_with_callback_on), for futures that
207    /// are not `Send`.
208    pub fn begin_with_callback_local_on<S, F, C>(
209        &mut self,
210        spawner: &S,
211        future: F,
212        callback: C,
213    ) -> Result<(), BeginError>
214    where
215        S: LocalSpawner,
216        F: Future<Output = T> + 'static,
217        C: FnOnce(&T) + 'static,
218        T: 'static,
219    {
220        if self.is_busy() {
221            return Err(BeginError::AlreadyStarted);
222        }
223        let (task, running) = task(future, callback);
224        spawner.spawn_local(task)?;
225        self.inner = running;
226        Ok(())
227    }
228
229    /// Whether a task is running or its result is waiting to be taken.
230    fn is_busy(&mut self) -> bool {
231        self.poll_task();
232        matches!(self.inner, Inner::Running { .. } | Inner::Done { .. })
233    }
234
235    /// If the task has finished, stores its outcome. Never waits.
236    fn poll_task(&mut self) {
237        let Inner::Running { receiver, .. } = &mut self.inner else {
238            return;
239        };
240        match receiver.try_recv() {
241            Ok(None) => {}
242            Ok(Some(outcome)) => self.inner = Inner::finished(Some(outcome)),
243            Err(oneshot::Canceled) => self.inner = Inner::finished(None),
244        }
245    }
246
247    /// Waits for the task to finish and returns its result.
248    ///
249    /// Returns immediately if the task already finished. If the task finished but its
250    /// callback panicked, the result is still returned; check [`state`](Self::state)
251    /// to detect that.
252    ///
253    /// ```rust
254    /// use async_deferred::{Deferred, Error};
255    ///
256    /// # tokio_test::block_on(async {
257    /// let mut deferred: Deferred<u32> = Deferred::start(async { panic!("boom") });
258    /// assert_eq!(deferred.join().await, Err(Error::Panicked("boom".into())));
259    /// # })
260    /// ```
261    pub async fn join(&mut self) -> Result<&T, Error> {
262        if let Inner::Running { receiver, .. } = &mut self.inner {
263            let outcome = receiver.await.ok();
264            self.inner = Inner::finished(outcome);
265        }
266        match &self.inner {
267            Inner::Done { value, .. } => Ok(value),
268            Inner::Panicked(msg) => Err(Error::Panicked(msg.clone())),
269            Inner::Cancelled => Err(Error::Cancelled),
270            Inner::NotStarted => Err(Error::NotStarted),
271            Inner::Running { .. } => unreachable!("the task was awaited above"),
272        }
273    }
274
275    /// Waits for the task to finish and returns its result, consuming the `Deferred`.
276    ///
277    /// Same as `.await` on the `Deferred`. If the task finished but its callback panicked,
278    /// the result is still returned. Dropping the returned future before it finishes does
279    /// not stop the task.
280    ///
281    /// ```rust
282    /// use async_deferred::Deferred;
283    ///
284    /// # tokio_test::block_on(async {
285    /// let deferred = Deferred::start(async { String::from("done") });
286    /// let value: String = deferred.into_result().await.unwrap();
287    /// assert_eq!(value, "done");
288    ///
289    /// // `.await` on a `Deferred` does the same
290    /// let deferred = Deferred::start(async { 42 });
291    /// assert_eq!(deferred.await, Ok(42));
292    /// # })
293    /// ```
294    pub fn into_result(self) -> IntoResult<T> {
295        IntoResult { deferred: self }
296    }
297
298    /// Returns the current [`State`] without waiting.
299    ///
300    /// The state is a snapshot: a task that has just finished may still show as
301    /// [`State::Pending`] for an instant. Once it shows as finished, its result is
302    /// available to [`try_get`](Self::try_get), [`take`](Self::take) and
303    /// [`join`](Self::join).
304    pub fn state(&self) -> State {
305        match &self.inner {
306            Inner::NotStarted => State::NotStarted,
307            Inner::Running { status, .. } => TaskStatus::load(status),
308            Inner::Done {
309                callback_panic: None,
310                ..
311            } => State::Completed,
312            Inner::Done {
313                callback_panic: Some(_),
314                ..
315            } => State::CallbackPanicked,
316            Inner::Panicked(_) => State::TaskPanicked,
317            Inner::Cancelled => State::Cancelled,
318        }
319    }
320
321    /// Returns the panic message if the task or its callback panicked.
322    ///
323    /// Catching a panic does not silence it: the panic hook still reports it, as for any
324    /// other panic.
325    pub fn panic_message(&mut self) -> Option<&str> {
326        self.poll_task();
327        match &self.inner {
328            Inner::Panicked(msg)
329            | Inner::Done {
330                callback_panic: Some(msg),
331                ..
332            } => Some(msg),
333            _ => None,
334        }
335    }
336
337    /// Returns the result if the task has finished, without waiting.
338    pub fn try_get(&mut self) -> Option<&T> {
339        self.poll_task();
340        match &self.inner {
341            Inner::Done { value, .. } => Some(value),
342            _ => None,
343        }
344    }
345
346    /// Moves the result out if the task has finished, without waiting.
347    ///
348    /// On success, the `Deferred` is reset and can start a new task.
349    ///
350    /// ```rust
351    /// use async_deferred::{Deferred, State};
352    ///
353    /// # tokio_test::block_on(async {
354    /// let mut deferred = Deferred::start(async { vec![1, 2, 3] });
355    /// deferred.join().await.unwrap();
356    /// assert_eq!(deferred.take(), Some(vec![1, 2, 3]));
357    /// assert_eq!(deferred.state(), State::NotStarted);
358    /// # })
359    /// ```
360    pub fn take(&mut self) -> Option<T> {
361        self.poll_task();
362        if !matches!(self.inner, Inner::Done { .. }) {
363            return None;
364        }
365        match core::mem::replace(&mut self.inner, Inner::NotStarted) {
366            Inner::Done { value, .. } => Some(value),
367            _ => unreachable!("checked above"),
368        }
369    }
370
371    /// Stops a running task and resets the `Deferred` so it can start a new one.
372    ///
373    /// The task may still be using its runtime resources, such as an embassy task pool slot,
374    /// when this returns. To start a new task right away in a full task pool, use
375    /// [`cancel_and_wait`](Self::cancel_and_wait) instead.
376    /// Returns `false` and does nothing if no task is running.
377    ///
378    /// Cancelling is cooperative: the task stops at its next `.await`. Code that blocks
379    /// without awaiting keeps running until it reaches one.
380    ///
381    /// If the task finishes just as `cancel` runs, its result is discarded and `cancel`
382    /// still returns `true`. To keep a result that has already arrived, call
383    /// [`take`](Self::take) first.
384    ///
385    /// ```rust
386    /// use async_deferred::{Deferred, State};
387    ///
388    /// # tokio_test::block_on(async {
389    /// let mut deferred = Deferred::start(std::future::pending::<u32>());
390    /// assert!(deferred.cancel());
391    /// assert_eq!(deferred.state(), State::NotStarted);
392    /// # })
393    /// ```
394    pub fn cancel(&mut self) -> bool {
395        self.poll_task();
396        let Inner::Running { abort, .. } = &self.inner else {
397            return false;
398        };
399        abort.abort();
400        self.inner = Inner::NotStarted;
401        true
402    }
403
404    /// Like [`cancel`](Self::cancel), and waits until the task has stopped.
405    ///
406    /// On a single-threaded executor such as embassy, its task pool slot is free when this
407    /// returns, so a new task can start right away even in a full pool. The task only stops
408    /// while its runtime is running, so don't await this from code that blocks the runtime.
409    /// Returns `false` and does nothing if no task is running.
410    ///
411    /// ```rust
412    /// use async_deferred::{Deferred, State};
413    ///
414    /// # tokio_test::block_on(async {
415    /// let mut deferred = Deferred::start(std::future::pending::<u32>());
416    /// assert!(deferred.cancel_and_wait().await);
417    /// assert_eq!(deferred.state(), State::NotStarted);
418    /// # })
419    /// ```
420    pub async fn cancel_and_wait(&mut self) -> bool {
421        self.poll_task();
422        if !matches!(self.inner, Inner::Running { .. }) {
423            return false;
424        }
425        let Inner::Running {
426            receiver, abort, ..
427        } = core::mem::replace(&mut self.inner, Inner::NotStarted)
428        else {
429            unreachable!("checked above")
430        };
431        abort.abort();
432        // The task sends its outcome or drops the sender as it stops.
433        let _ = receiver.await;
434        true
435    }
436
437    /// Returns `true` if the result is available, even if the callback panicked.
438    pub fn is_ready(&self) -> bool {
439        matches!(self.state(), State::Completed | State::CallbackPanicked)
440    }
441
442    /// Returns `true` if the task and its callback finished without panicking.
443    pub fn is_complete(&self) -> bool {
444        self.state() == State::Completed
445    }
446
447    /// Returns `true` if the task is still running.
448    pub fn is_pending(&self) -> bool {
449        self.state() == State::Pending
450    }
451
452    /// Returns `true` if no task has been started, or its result was taken.
453    pub fn is_not_started(&self) -> bool {
454        self.state() == State::NotStarted
455    }
456
457    /// Returns `true` if the task panicked.
458    pub fn has_task_panicked(&self) -> bool {
459        self.state() == State::TaskPanicked
460    }
461
462    /// Returns `true` if the task finished but its callback panicked.
463    pub fn has_callback_panicked(&self) -> bool {
464        self.state() == State::CallbackPanicked
465    }
466
467    /// Returns `true` if the runtime dropped the task before it finished.
468    ///
469    /// A task stopped with [`cancel`](Self::cancel) is not reported here: cancelling resets
470    /// the `Deferred` to [`State::NotStarted`].
471    pub fn is_cancelled(&self) -> bool {
472        self.state() == State::Cancelled
473    }
474}
475
476#[cfg(feature = "tokio")]
477impl<T> Deferred<T> {
478    /// Spawns `future` on the current Tokio runtime and returns its `Deferred`.
479    ///
480    /// # Panics
481    ///
482    /// Panics if called outside a Tokio runtime. Use [`start_on`](Self::start_on) with a
483    /// [`tokio::runtime::Handle`] there.
484    pub fn start<F>(future: F) -> Self
485    where
486        F: Future<Output = T> + Send + 'static,
487        T: Send + 'static,
488    {
489        Self::start_on(&Tokio, future)
490            .expect("`Deferred::start` was called outside a Tokio runtime")
491    }
492
493    /// Like [`start`](Self::start), and runs `callback` with the result once `future` finishes.
494    ///
495    /// The callback is not run if `future` panics, or if the task is cancelled or dropped by
496    /// the runtime.
497    ///
498    /// # Panics
499    ///
500    /// Panics if called outside a Tokio runtime. Use
501    /// [`start_with_callback_on`](Self::start_with_callback_on) with a
502    /// [`tokio::runtime::Handle`] there.
503    ///
504    /// ```rust
505    /// use async_deferred::Deferred;
506    ///
507    /// # tokio_test::block_on(async {
508    /// let deferred = Deferred::start_with_callback(
509    ///     async { 42 },
510    ///     |result| println!("computed {result}"),
511    /// );
512    /// # })
513    /// ```
514    pub fn start_with_callback<F, C>(future: F, callback: C) -> Self
515    where
516        F: Future<Output = T> + Send + 'static,
517        C: FnOnce(&T) + Send + 'static,
518        T: Send + 'static,
519    {
520        Self::start_with_callback_on(&Tokio, future, callback)
521            .expect("`Deferred::start_with_callback` was called outside a Tokio runtime")
522    }
523
524    /// Spawns `future` on the current Tokio runtime.
525    ///
526    /// Returns [`BeginError::AlreadyStarted`] and does nothing if a task is running or its
527    /// result has not been taken. A task that panicked or was dropped by the runtime does
528    /// not prevent starting a new one.
529    ///
530    /// Outside a Tokio runtime, returns [`BeginError::Spawn`].
531    ///
532    /// ```rust
533    /// use async_deferred::Deferred;
534    ///
535    /// # tokio_test::block_on(async {
536    /// let mut deferred = Deferred::new();
537    /// assert!(deferred.begin(async { 42 }).is_ok());
538    /// assert!(deferred.begin(async { 24 }).is_err());
539    /// # })
540    /// ```
541    pub fn begin<F>(&mut self, future: F) -> Result<(), BeginError>
542    where
543        F: Future<Output = T> + Send + 'static,
544        T: Send + 'static,
545    {
546        self.begin_on(&Tokio, future)
547    }
548
549    /// Like [`begin`](Self::begin), and runs `callback` with the result once `future` finishes.
550    ///
551    /// The callback is not run if `future` panics, or if the task is cancelled or dropped by
552    /// the runtime.
553    pub fn begin_with_callback<F, C>(&mut self, future: F, callback: C) -> Result<(), BeginError>
554    where
555        F: Future<Output = T> + Send + 'static,
556        C: FnOnce(&T) + Send + 'static,
557        T: Send + 'static,
558    {
559        self.begin_with_callback_on(&Tokio, future, callback)
560    }
561}
562
563impl<T> IntoFuture for Deferred<T> {
564    type Output = Result<T, Error>;
565    type IntoFuture = IntoResult<T>;
566
567    /// Same as [`Deferred::into_result`].
568    fn into_future(self) -> IntoResult<T> {
569        self.into_result()
570    }
571}
572
573/// The future returned by [`Deferred::into_result`] and by `.await` on a [`Deferred`].
574#[derive(Debug)]
575#[must_use = "futures do nothing unless you `.await` or poll them"]
576pub struct IntoResult<T> {
577    deferred: Deferred<T>,
578}
579
580// The value is never pinned: it is only moved out once the task has finished.
581impl<T> Unpin for IntoResult<T> {}
582
583impl<T> Future for IntoResult<T> {
584    type Output = Result<T, Error>;
585
586    fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
587        let inner = &mut self.get_mut().deferred.inner;
588        if let Inner::Running { receiver, .. } = inner {
589            match Pin::new(receiver).poll(cx) {
590                Poll::Pending => return Poll::Pending,
591                Poll::Ready(outcome) => *inner = Inner::finished(outcome.ok()),
592            }
593        }
594        Poll::Ready(match core::mem::replace(inner, Inner::NotStarted) {
595            Inner::Done { value, .. } => Ok(value),
596            Inner::Panicked(msg) => Err(Error::Panicked(msg)),
597            Inner::Cancelled => Err(Error::Cancelled),
598            Inner::NotStarted => Err(Error::NotStarted),
599            Inner::Running { .. } => unreachable!("the task was polled above"),
600        })
601    }
602}
603
604impl<T> Default for Deferred<T> {
605    /// Same as [`Deferred::new`].
606    fn default() -> Self {
607        Self::new()
608    }
609}
610
611impl<T> Inner<T> {
612    /// `None` means the task was dropped before sending its outcome.
613    fn finished(outcome: Option<Outcome<T>>) -> Self {
614        match outcome {
615            Some(Ok((value, callback_panic))) => Inner::Done {
616                value,
617                callback_panic,
618            },
619            Some(Err(msg)) => Inner::Panicked(msg),
620            None => Inner::Cancelled,
621        }
622    }
623}
624
625/// Builds the task to spawn, and the `Running` state that tracks it.
626///
627/// The task is `Send` whenever `F`, `C` and `T` are.
628fn task<T, F, C>(future: F, callback: C) -> (impl Future<Output = ()>, Inner<T>)
629where
630    F: Future<Output = T> + 'static,
631    C: FnOnce(&T) + 'static,
632    T: 'static,
633{
634    let (sender, receiver) = oneshot::channel();
635    let (abort, abort_registration) = AbortHandle::new_pair();
636    let status = Arc::new(AtomicU8::new(TaskStatus::PENDING));
637    // Created now, so it also reports a task the runtime drops before ever running it.
638    let reporter = Reporter {
639        sender: Some(sender),
640        status: status.clone(),
641    };
642    let task = Abortable::new(
643        async move {
644            let outcome = match catch_unwind(future).await {
645                Ok(value) => {
646                    // Catch a callback panic so the computed value is not lost with it.
647                    let callback_panic = call_catching_panic(callback, &value).err();
648                    Ok((value, callback_panic))
649                }
650                Err(msg) => Err(msg),
651            };
652            reporter.finish(outcome);
653        },
654        abort_registration,
655    );
656    let task = async move {
657        let _ = task.await;
658    };
659    (
660        task,
661        Inner::Running {
662            receiver,
663            abort,
664            status,
665        },
666    )
667}
668
669/// The values of the status flag a running task shares with its `Deferred`.
670///
671/// The flag lets [`Deferred::state`] work through `&self`. The task stores it after
672/// sending its outcome, so once the flag says the task has finished, the outcome is in
673/// the channel.
674struct TaskStatus;
675
676impl TaskStatus {
677    const PENDING: u8 = 0;
678    const COMPLETED: u8 = 1;
679    const CALLBACK_PANICKED: u8 = 2;
680    const TASK_PANICKED: u8 = 3;
681    const CANCELLED: u8 = 4;
682
683    fn load(status: &AtomicU8) -> State {
684        match status.load(Ordering::Acquire) {
685            Self::PENDING => State::Pending,
686            Self::COMPLETED => State::Completed,
687            Self::CALLBACK_PANICKED => State::CallbackPanicked,
688            Self::TASK_PANICKED => State::TaskPanicked,
689            _ => State::Cancelled,
690        }
691    }
692}
693
694/// Owned by the task: sends its outcome and sets the status flag.
695///
696/// If the task is dropped before finishing, it closes the channel and then marks the
697/// task cancelled, in that order, so the flag never runs ahead of the channel.
698struct Reporter<T> {
699    sender: Option<oneshot::Sender<Outcome<T>>>,
700    status: Arc<AtomicU8>,
701}
702
703impl<T> Reporter<T> {
704    fn finish(mut self, outcome: Outcome<T>) {
705        let status = match &outcome {
706            Ok((_, None)) => TaskStatus::COMPLETED,
707            Ok((_, Some(_))) => TaskStatus::CALLBACK_PANICKED,
708            Err(_) => TaskStatus::TASK_PANICKED,
709        };
710        if let Some(sender) = self.sender.take() {
711            // The `Deferred` may have been dropped; the result is then discarded.
712            let _ = sender.send(outcome);
713        }
714        self.status.store(status, Ordering::Release);
715    }
716}
717
718impl<T> Drop for Reporter<T> {
719    fn drop(&mut self) {
720        if let Some(sender) = self.sender.take() {
721            drop(sender);
722            self.status.store(TaskStatus::CANCELLED, Ordering::Release);
723        }
724    }
725}
726
727/// Awaits `future`, turning a panic into its message.
728#[cfg(feature = "std")]
729async fn catch_unwind<F: Future>(future: F) -> Result<F::Output, String> {
730    use futures_util::FutureExt;
731    std::panic::AssertUnwindSafe(future)
732        .catch_unwind()
733        .await
734        .map_err(|payload| panic_message(&*payload))
735}
736
737/// Awaits `future`. Without `std`, panics cannot be caught.
738#[cfg(not(feature = "std"))]
739async fn catch_unwind<F: Future>(future: F) -> Result<F::Output, String> {
740    Ok(future.await)
741}
742
743/// Calls `callback`, turning a panic into its message.
744#[cfg(feature = "std")]
745fn call_catching_panic<T, C: FnOnce(&T)>(callback: C, value: &T) -> Result<(), String> {
746    std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| callback(value)))
747        .map_err(|payload| panic_message(&*payload))
748}
749
750/// Calls `callback`. Without `std`, panics cannot be caught.
751#[cfg(not(feature = "std"))]
752fn call_catching_panic<T, C: FnOnce(&T)>(callback: C, value: &T) -> Result<(), String> {
753    callback(value);
754    Ok(())
755}
756
757/// Extracts a readable message from a panic payload.
758#[cfg(feature = "std")]
759fn panic_message(payload: &(dyn std::any::Any + Send)) -> String {
760    if let Some(s) = payload.downcast_ref::<&str>() {
761        s.to_string()
762    } else if let Some(s) = payload.downcast_ref::<String>() {
763        s.clone()
764    } else {
765        "unknown panic payload".to_string()
766    }
767}