use std::any::Any;
use std::future::Future;
use std::pin::Pin;
type ErasedFuture = Pin<Box<dyn Future<Output = ()> + Send>>;
pub fn spawn(future: impl Future<Output = ()> + Send + 'static) -> tokio::task::JoinHandle<()> {
spawn_erased(Box::pin(future))
}
#[inline(never)]
fn spawn_erased(future: ErasedFuture) -> tokio::task::JoinHandle<()> {
tokio::spawn(future)
}
type ErasedJob = Box<dyn FnOnce() -> Box<dyn Any + Send> + Send>;
pub async fn spawn_blocking<T: Send + 'static>(
job: impl FnOnce() -> T + Send + 'static,
) -> Result<T, tokio::task::JoinError> {
let erased: ErasedJob = Box::new(move || Box::new(job()) as Box<dyn Any + Send>);
let output = run_erased(erased).await?;
match output.downcast::<T>() {
Ok(value) => Ok(*value),
Err(_) => unreachable!("blocking job returned another type"),
}
}
#[inline(never)]
fn run_erased(job: ErasedJob) -> tokio::task::JoinHandle<Box<dyn Any + Send>> {
tokio::task::spawn_blocking(job)
}
#[cfg(test)]
mod tests {
#[tokio::test]
async fn returns_the_value_and_reports_panics() {
assert_eq!(super::spawn_blocking(|| 6 * 7).await.unwrap(), 42);
assert_eq!(super::spawn_blocking(|| String::from("x")).await.unwrap(), "x");
let panicked = super::spawn_blocking(|| -> u8 { std::panic::panic_any("boom") }).await;
assert!(panicked.unwrap_err().is_panic());
let (sender, receiver) = tokio::sync::oneshot::channel();
super::spawn(async move { sender.send(7).unwrap() }).await.unwrap();
assert_eq!(receiver.await.unwrap(), 7);
}
}