1use std::any::Any;
12use std::future::Future;
13use std::pin::Pin;
14
15type ErasedFuture = Pin<Box<dyn Future<Output = ()> + Send>>;
16
17pub fn spawn(future: impl Future<Output = ()> + Send + 'static) -> tokio::task::JoinHandle<()> {
19 spawn_erased(Box::pin(future))
20}
21
22#[inline(never)]
23fn spawn_erased(future: ErasedFuture) -> tokio::task::JoinHandle<()> {
24 tokio::spawn(future)
25}
26
27type ErasedJob = Box<dyn FnOnce() -> Box<dyn Any + Send> + Send>;
28
29pub async fn spawn_blocking<T: Send + 'static>(
34 job: impl FnOnce() -> T + Send + 'static,
35) -> Result<T, tokio::task::JoinError> {
36 let erased: ErasedJob = Box::new(move || Box::new(job()) as Box<dyn Any + Send>);
37 let output = run_erased(erased).await?;
38 match output.downcast::<T>() {
40 Ok(value) => Ok(*value),
41 Err(_) => unreachable!("blocking job returned another type"),
42 }
43}
44
45#[inline(never)]
46fn run_erased(job: ErasedJob) -> tokio::task::JoinHandle<Box<dyn Any + Send>> {
47 tokio::task::spawn_blocking(job)
48}
49
50#[cfg(test)]
51mod tests {
52 #[tokio::test]
53 async fn returns_the_value_and_reports_panics() {
54 assert_eq!(super::spawn_blocking(|| 6 * 7).await.unwrap(), 42);
55 assert_eq!(super::spawn_blocking(|| String::from("x")).await.unwrap(), "x");
56 let panicked = super::spawn_blocking(|| -> u8 { std::panic::panic_any("boom") }).await;
57 assert!(panicked.unwrap_err().is_panic());
58 let (sender, receiver) = tokio::sync::oneshot::channel();
59 super::spawn(async move { sender.send(7).unwrap() }).await.unwrap();
60 assert_eq!(receiver.await.unwrap(), 7);
61 }
62}