#![doc = include_str!("../README.md")]
#![cfg_attr(not(feature = "std"), no_std)]
extern crate alloc;
mod embassy;
mod spawner;
#[doc(hidden)]
pub mod __private {
pub use alloc::boxed::Box;
}
use alloc::string::String;
use core::fmt;
use core::future::Future;
use futures_channel::oneshot;
use futures_util::future::{AbortHandle, Abortable};
#[cfg(feature = "smol")]
pub use spawner::Smol;
#[cfg(feature = "tokio")]
pub use spawner::Tokio;
pub use spawner::{LocalSpawner, Spawner};
type Outcome<T> = Result<(T, Option<String>), String>;
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum State {
NotStarted,
Pending,
Completed,
TaskPanicked,
CallbackPanicked,
Cancelled,
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum Error {
NotStarted,
Panicked(String),
Cancelled,
}
impl fmt::Display for Error {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
Error::NotStarted => f.write_str("no task has been started"),
Error::Panicked(msg) => write!(f, "task panicked: {msg}"),
Error::Cancelled => f.write_str("task was cancelled"),
}
}
}
#[cfg(feature = "std")]
impl std::error::Error for Error {}
#[derive(Debug)]
enum Inner<T> {
NotStarted,
Running {
receiver: oneshot::Receiver<Outcome<T>>,
abort: AbortHandle,
},
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) -> Self
where
S: Spawner,
F: Future<Output = T> + Send + 'static,
T: Send + 'static,
{
let mut deferred = Self::new();
deferred.begin_on(spawner, future);
deferred
}
pub fn start_with_callback_on<S, F, C>(spawner: &S, future: F, callback: C) -> Self
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);
deferred
}
pub fn begin_on<S, F>(&mut self, spawner: &S, future: F) -> bool
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) -> bool
where
S: Spawner,
F: Future<Output = T> + Send + 'static,
C: FnOnce(&T) + Send + 'static,
T: Send + 'static,
{
if !self.is_not_started() {
return false;
}
let (task, running) = task(future, callback);
spawner.spawn(task);
self.inner = running;
true
}
pub fn start_local_on<S, F>(spawner: &S, future: F) -> Self
where
S: LocalSpawner,
F: Future<Output = T> + 'static,
T: 'static,
{
let mut deferred = Self::new();
deferred.begin_local_on(spawner, future);
deferred
}
pub fn start_with_callback_local_on<S, F, C>(spawner: &S, future: F, callback: C) -> Self
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);
deferred
}
pub fn begin_local_on<S, F>(&mut self, spawner: &S, future: F) -> bool
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,
) -> bool
where
S: LocalSpawner,
F: Future<Output = T> + 'static,
C: FnOnce(&T) + 'static,
T: 'static,
{
if !self.is_not_started() {
return false;
}
let (task, running) = task(future, callback);
spawner.spawn_local(task);
self.inner = running;
true
}
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 state(&mut self) -> State {
self.poll_task();
match &self.inner {
Inner::NotStarted => State::NotStarted,
Inner::Running { .. } => State::Pending,
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 fn is_ready(&mut self) -> bool {
self.try_get().is_some()
}
pub fn is_complete(&mut self) -> bool {
self.state() == State::Completed
}
pub fn is_pending(&mut self) -> bool {
self.state() == State::Pending
}
pub fn is_not_started(&mut self) -> bool {
self.state() == State::NotStarted
}
pub fn has_task_panicked(&mut self) -> bool {
self.state() == State::TaskPanicked
}
}
#[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)
}
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)
}
pub fn begin<F>(&mut self, future: F) -> bool
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) -> bool
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> 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 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),
};
let _ = sender.send(outcome);
},
abort_registration,
);
let task = async move {
let _ = task.await;
};
(task, Inner::Running { receiver, abort })
}
#[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()
}
}