fut_compat/task/
mod.rs

1use std::future::Future;
2use std::pin::Pin;
3use std::task::{Context, Poll};
4use std::error::Error;
5
6pub use futures::task::{Spawn, SpawnExt};
7
8
9
10/// Contains the compatibility objects for the [`tokio`](https://docs.rs/tokio) runtime.
11#[cfg(feature = "tokio-rt")]
12#[cfg_attr(docsrs, doc(cfg(feature = "tokio-rt")))]
13mod tokio;
14#[cfg(feature = "tokio-rt")]
15#[cfg_attr(docsrs, doc(cfg(feature = "tokio-rt")))]
16pub use self::tokio::*;
17
18/// Contains the compatibility objects for the [`async_std`](https://docs.rs/async-std) runtime.
19#[cfg(feature = "async-std-rt")]
20#[cfg_attr(docsrs, doc(cfg(feature = "async-std-rt")))]
21mod async_std;
22#[cfg(feature = "async-std-rt")]
23#[cfg_attr(docsrs, doc(cfg(feature = "async-std-rt")))]
24pub use self::async_std::*;
25
26
27
28/// An abstraction over executing a sync task in a new blocking thread and optionally awaiting
29/// it's completion in an async fashion.
30pub trait SpawnBlocking {
31    fn spawn_blocking<F, T>(f: F) -> JoinHandle<T>
32    where
33        F: FnOnce() -> T + Send + 'static,
34        T: Send + 'static;
35}
36
37
38/// A handle that awaits the result of a task. Gets returned by [`SpawnBlocking`].
39pub struct JoinHandle<T> {
40    inner: Box<dyn Future<Output = Result<T, Box<dyn Error>>> + Unpin +'static>
41}
42
43impl<T> JoinHandle<T>
44{
45    pub fn new<J>(inner: J) -> Self
46    where
47        J: Future<Output = Result<T, Box<dyn Error>>> + Unpin + 'static,
48    {
49        Self {
50            inner: Box::new(inner),
51        }
52    }
53}
54
55impl<T> Future for JoinHandle<T>
56{
57    type Output = Result<T, Box<dyn Error>>;
58
59    fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
60        Future::poll(Pin::new(&mut Pin::into_inner(self).inner), cx)
61    }
62}