Skip to main content

spawn_std_tokio/
lib.rs

1use std::pin::Pin;
2use std::task::{Context, Poll};
3
4use spawn_std_core::{Executor, Handle};
5use tokio::task::{JoinError, JoinHandle};
6
7pub struct TokioExecutor;
8
9impl Executor for TokioExecutor {
10    type Handle<T: Send + 'static> = TokioHandle<T>;
11
12    fn spawn<T, F>(future: F) -> Self::Handle<T>
13    where
14        T: Send + 'static,
15        F: Future<Output = T> + Send + 'static,
16    {
17        TokioHandle(tokio::task::spawn(future))
18    }
19}
20
21pub struct TokioHandle<T>(JoinHandle<T>);
22
23impl<T> TokioHandle<T> {
24    fn inner_pin_mut(self: Pin<&mut Self>) -> Pin<&mut JoinHandle<T>> {
25        unsafe { self.map_unchecked_mut(|x| &mut x.0) }
26    }
27}
28
29impl<T> Unpin for TokioHandle<T> {}
30
31impl<T> Future for TokioHandle<T> {
32    type Output = Result<T, JoinError>;
33
34    #[inline]
35    fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
36        self.inner_pin_mut().poll(cx)
37    }
38}
39
40impl<T> Handle<T> for TokioHandle<T>
41where
42    T: Send + 'static,
43{
44    type Error = tokio::task::JoinError;
45
46    #[inline]
47    fn abort(self) {
48        self.0.abort();
49    }
50}