use futures::FutureExt;
use std::future::Future;
use std::pin::Pin;
use std::task::{Context, Poll};
use std::time::Duration;
use async_std::future;
use async_std::task;
use async_std::task::JoinHandle;
#[derive(Debug)]
pub struct TaskHandle<T>(JoinHandle<T>);
impl<T> TaskHandle<T> {
pub async fn cancel(self) -> Option<T> {
self.0.cancel().await
}
pub async fn wait(self) -> Option<T> {
self.await
}
}
impl<T> Future for TaskHandle<T> {
type Output = Option<T>;
fn poll(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
self.0.poll_unpin(cx).map(Some)
}
}
pub fn block_on<F, T>(future: F) -> T
where
F: Future<Output = T>,
{
task::block_on(future)
}
pub fn spawn<F, T>(future: F) -> TaskHandle<T>
where
F: Future<Output = T> + Send + 'static,
T: Send + 'static,
{
let h = task::spawn(async move { future.await });
TaskHandle(h)
}
pub async fn sleep(dur: Duration) {
task::sleep(dur).await
}
pub async fn timeout<F, T>(dur: Duration, f: F) -> Result<T, ()>
where
F: Future<Output = T>,
{
future::timeout(dur, f).await.map_err(|_| ())
}