Skip to main content

graphrt_core/
task.rs

1//! One tokio task type for many spawn sites.
2//!
3//! `tokio::spawn` and `tokio::task::spawn_blocking` are generic over the
4//! future / closure, and each type compiles its own task machinery (poll,
5//! harness, join handle: about 1.9 KiB per call site on x86_64). Stores run
6//! every operation on the blocking pool, so a store with 30 methods paid for 30
7//! task types. [`spawn`] and [`spawn_blocking`] erase the future / closure
8//! behind a box (one allocation, which a spawn makes anyway), so the machinery
9//! exists once for each.
10
11use std::any::Any;
12use std::future::Future;
13use std::pin::Pin;
14
15type ErasedFuture = Pin<Box<dyn Future<Output = ()> + Send>>;
16
17/// Spawns `future` on the current runtime, like `tokio::spawn`.
18pub 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
29/// Runs `job` on the blocking pool, like `tokio::task::spawn_blocking`.
30///
31/// # Errors
32/// The `JoinError` when the job panicked or the runtime shut down.
33pub 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    // The erased job returns exactly a `T`, so the downcast cannot fail.
39    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}