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};
type Outcome<T> = Result<(T, Option<String>), String>;
#[derive(Debug)]
enum Inner<T> {
NotStarted,
Running {
receiver: oneshot::Receiver<Outcome<T>>,
abort: AbortHandle,
status: Arc<AtomicU8>,
},
Done {
value: T,
callback_panic: Option<String>,
},
Panicked(String),
Cancelled,
}
#[derive(Debug)]
pub struct Deferred<T> {
inner: Inner<T>,
}
impl<T> Deferred<T> {
pub fn new() -> Self {
Self {
inner: Inner::NotStarted,
}
}
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)
}
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)
}
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| {})
}
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(())
}
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)
}
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)
}
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| {})
}
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(())
}
fn is_busy(&mut self) -> bool {
self.poll_task();
matches!(self.inner, Inner::Running { .. } | Inner::Done { .. })
}
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),
}
}
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"),
}
}
pub fn into_result(self) -> IntoResult<T> {
IntoResult { deferred: self }
}
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,
}
}
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,
}
}
pub fn try_get(&mut self) -> Option<&T> {
self.poll_task();
match &self.inner {
Inner::Done { value, .. } => Some(value),
_ => None,
}
}
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"),
}
}
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
}
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();
let _ = receiver.await;
true
}
pub fn is_ready(&self) -> bool {
matches!(self.state(), State::Completed | State::CallbackPanicked)
}
pub fn is_complete(&self) -> bool {
self.state() == State::Completed
}
pub fn is_pending(&self) -> bool {
self.state() == State::Pending
}
pub fn is_not_started(&self) -> bool {
self.state() == State::NotStarted
}
pub fn has_task_panicked(&self) -> bool {
self.state() == State::TaskPanicked
}
pub fn has_callback_panicked(&self) -> bool {
self.state() == State::CallbackPanicked
}
pub fn is_cancelled(&self) -> bool {
self.state() == State::Cancelled
}
}
#[cfg(feature = "tokio")]
impl<T> Deferred<T> {
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")
}
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")
}
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)
}
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>;
fn into_future(self) -> IntoResult<T> {
self.into_result()
}
}
#[derive(Debug)]
#[must_use = "futures do nothing unless you `.await` or poll them"]
pub struct IntoResult<T> {
deferred: Deferred<T>,
}
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> {
fn default() -> Self {
Self::new()
}
}
impl<T> Inner<T> {
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,
}
}
}
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));
let reporter = Reporter {
sender: Some(sender),
status: status.clone(),
};
let task = Abortable::new(
async move {
let outcome = match catch_unwind(future).await {
Ok(value) => {
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,
},
)
}
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,
}
}
}
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() {
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);
}
}
}
#[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))
}
#[cfg(not(feature = "std"))]
async fn catch_unwind<F: Future>(future: F) -> Result<F::Output, String> {
Ok(future.await)
}
#[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))
}
#[cfg(not(feature = "std"))]
fn call_catching_panic<T, C: FnOnce(&T)>(callback: C, value: &T) -> Result<(), String> {
callback(value);
Ok(())
}
#[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()
}
}