1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
//! Async-std specific green thread management implementation.
use crate::AsyncStdGlobalRuntime;
use arta::task::{RuntimeJoinHandle, TaskRuntime};
use futures::{prelude::Future, FutureExt};
use std::{
    panic::AssertUnwindSafe,
    pin::Pin,
    task::{Context, Poll},
};

/// Async-std specific [`RuntimeJoinHandle`] implementation.
pub struct AsyncStdJoinHandle<T> {
    inner: async_std::task::JoinHandle<std::thread::Result<T>>,
}

impl<T> Future for AsyncStdJoinHandle<T>
where
    T: Send,
{
    type Output = std::thread::Result<T>;

    fn poll(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
        self.inner.poll_unpin(cx)
    }
}

impl<T> RuntimeJoinHandle<T> for AsyncStdJoinHandle<T>
where
    T: Send + 'static,
{
    fn cancel(self) -> impl Future<Output = Option<std::thread::Result<T>>> + Send {
        self.inner.cancel()
    }
}

impl TaskRuntime for AsyncStdGlobalRuntime {
    type JoinHandle<T> = AsyncStdJoinHandle<T> where T: Send + 'static;

    fn spawn<R>(&self, future: impl Future<Output = R> + Send + 'static) -> Self::JoinHandle<R>
    where
        R: Send + 'static,
    {
        AsyncStdJoinHandle {
            inner: async_std::task::spawn(AssertUnwindSafe(future).catch_unwind()),
        }
    }

    fn spawn_blocking<R>(&self, task: impl FnOnce() -> R + Send + 'static) -> Self::JoinHandle<R>
    where
        R: Send + 'static,
    {
        AsyncStdJoinHandle {
            inner: async_std::task::spawn_blocking(|| {
                std::panic::catch_unwind(AssertUnwindSafe(task))
            }),
        }
    }
}