use std::any::Any;
use std::future::Future;
use std::marker::PhantomData;
use std::pin::Pin;
use std::task::{Context, Poll};
use pin_project_lite::pin_project;
#[cfg(feature = "async-std")]
mod catch_unwind;
pub type Error = Box<dyn Any + Send + 'static>;
pub type Result<T, E = Error> = std::result::Result<T, E>;
pin_project! {
pub struct JoinHandle<T> {
#[pin]
inner: FromRuntime! {
"std" => PhantomData<*const T>,
"async-std" => async_std::task::JoinHandle<Result<T>>,
"tokio" => tokio::task::JoinHandle<T>,
},
phantom: PhantomData<*const T>,
}
}
impl<T> Future for JoinHandle<T> {
type Output = Result<T>;
fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
apply_mut_runtime_async!(self.project().inner, cx, {
"async-std" => |handle, cx| Pin::new(handle).poll(cx),
"tokio" => |handle, cx|
Pin::new(handle).poll(cx).map(|res| res.map_err(tokio::task::JoinError::into_panic)),
})
}
}
#[allow(unreachable_code)]
pub fn spawn<T: Future + Send + 'static>(future: T) -> JoinHandle<T::Output>
where
T::Output: Send + 'static,
{
let inner = pick_async_runtime!(future, {
"async-std" => |future| async_std::task::spawn(catch_unwind::CatchUnwind::new(future)),
"tokio" => |future| tokio::task::spawn(future),
});
JoinHandle {
inner,
phantom: PhantomData,
}
}