1use std::any::Any;
12use std::future::Future;
13use std::marker::PhantomData;
14use std::pin::Pin;
15use std::task::{Context, Poll};
16
17type ErasedFuture = Pin<Box<dyn Future<Output = ()> + Send>>;
18
19pub fn spawn(future: impl Future<Output = ()> + Send + 'static) -> tokio::task::JoinHandle<()> {
21 spawn_erased(Box::pin(future))
22}
23
24#[inline(never)]
25fn spawn_erased(future: ErasedFuture) -> tokio::task::JoinHandle<()> {
26 tokio::spawn(future)
27}
28
29type ErasedJob = Box<dyn FnOnce() -> Box<dyn Any + Send> + Send>;
30type ErasedOutput = Result<Box<dyn Any + Send>, tokio::task::JoinError>;
31
32pub fn spawn_blocking<T: Send + 'static>(job: impl FnOnce() -> T + Send + 'static) -> Blocking<T> {
38 let erased: ErasedJob = Box::new(move || Box::new(job()) as Box<dyn Any + Send>);
39 Blocking { job: ErasedBlocking { job: Some(erased), handle: None }, output: PhantomData }
40}
41
42#[must_use = "a blocking job runs only once its future is polled"]
49pub struct Blocking<T> {
50 job: ErasedBlocking,
51 output: PhantomData<fn() -> T>,
52}
53
54impl<T> std::fmt::Debug for Blocking<T> {
55 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
56 f.debug_struct("Blocking").field("spawned", &self.job.handle.is_some()).finish_non_exhaustive()
57 }
58}
59
60struct ErasedBlocking {
61 job: Option<ErasedJob>,
62 handle: Option<tokio::task::JoinHandle<Box<dyn Any + Send>>>,
63}
64
65impl<T: 'static> Future for Blocking<T> {
66 type Output = Result<T, tokio::task::JoinError>;
67
68 fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
69 let output = match poll_erased(&mut self.get_mut().job, cx) {
70 Poll::Ready(output) => output?,
71 Poll::Pending => return Poll::Pending,
72 };
73 match output.downcast::<T>() {
75 Ok(value) => Poll::Ready(Ok(*value)),
76 Err(_) => unreachable!("blocking job returned another type"),
77 }
78 }
79}
80
81#[inline(never)]
82fn poll_erased(state: &mut ErasedBlocking, cx: &mut Context<'_>) -> Poll<ErasedOutput> {
83 if let Some(job) = state.job.take() {
84 state.handle = Some(tokio::task::spawn_blocking(job));
85 }
86 match &mut state.handle {
87 Some(handle) => Pin::new(handle).poll(cx),
88 None => Poll::Pending,
90 }
91}
92
93#[cfg(test)]
94mod tests {
95 #[tokio::test]
96 async fn returns_the_value_and_reports_panics() {
97 assert_eq!(super::spawn_blocking(|| 6 * 7).await.unwrap(), 42);
98 assert_eq!(super::spawn_blocking(|| String::from("x")).await.unwrap(), "x");
99 let panicked = super::spawn_blocking(|| -> u8 { std::panic::panic_any("boom") }).await;
100 assert!(panicked.unwrap_err().is_panic());
101 let (sender, receiver) = tokio::sync::oneshot::channel();
102 super::spawn(async move { sender.send(7).unwrap() }).await.unwrap();
103 assert_eq!(receiver.await.unwrap(), 7);
104 }
105
106 #[tokio::test]
107 async fn the_job_starts_when_first_polled() {
108 use std::sync::Arc;
109 use std::sync::atomic::{AtomicBool, Ordering};
110 let ran = Arc::new(AtomicBool::new(false));
111 let flag = ran.clone();
112 let job = super::spawn_blocking(move || flag.store(true, Ordering::SeqCst));
113 std::thread::sleep(std::time::Duration::from_millis(50));
115 assert!(!ran.load(Ordering::SeqCst), "the job ran before its future was polled");
116 job.await.unwrap();
117 assert!(ran.load(Ordering::SeqCst));
118 }
119}