use std::future::Future;
use std::time::Duration;
#[cfg(not(target_arch = "wasm32"))]
pub use tokio::time::Instant;
#[cfg(target_arch = "wasm32")]
pub use web_time::Instant;
pub use web_time::{SystemTime, UNIX_EPOCH};
#[cfg(not(target_arch = "wasm32"))]
pub trait MaybeSend: Send {}
#[cfg(not(target_arch = "wasm32"))]
impl<T: Send + ?Sized> MaybeSend for T {}
#[cfg(target_arch = "wasm32")]
pub trait MaybeSend {}
#[cfg(target_arch = "wasm32")]
impl<T: ?Sized> MaybeSend for T {}
pub fn spawn<F>(future: F)
where
F: Future<Output = ()> + MaybeSend + 'static,
{
#[cfg(not(target_arch = "wasm32"))]
drop(tokio::spawn(future));
#[cfg(target_arch = "wasm32")]
wasm_bindgen_futures::spawn_local(future);
}
pub struct Task<T: 'static> {
handle: Option<futures_util::future::RemoteHandle<Result<T, futures_util::future::Aborted>>>,
abort: futures_util::future::AbortHandle,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, thiserror::Error)]
#[error("the task was aborted")]
pub struct Aborted;
pub fn spawn_task<F>(future: F) -> Task<F::Output>
where
F: Future + MaybeSend + 'static,
F::Output: MaybeSend + 'static,
{
use futures_util::FutureExt;
let (future, abort) = futures_util::future::abortable(future);
let (future, handle) = future.remote_handle();
spawn(future);
Task {
handle: Some(handle),
abort,
}
}
impl<T: 'static> Task<T> {
pub async fn join(mut self) -> Result<T, Aborted> {
match self.handle.take() {
Some(handle) => handle.await.map_err(|_| Aborted),
None => Err(Aborted),
}
}
pub fn abort(&self) {
self.abort.abort();
}
}
impl<T: 'static> Drop for Task<T> {
fn drop(&mut self) {
if let Some(handle) = self.handle.take() {
handle.forget();
}
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, thiserror::Error)]
#[error("timed out after {0:?}")]
pub struct Elapsed(pub Duration);
pub async fn sleep(duration: Duration) {
#[cfg(not(target_arch = "wasm32"))]
tokio::time::sleep(duration).await;
#[cfg(target_arch = "wasm32")]
gloo_timers::future::sleep(duration).await;
}
pub async fn timeout<F: Future>(duration: Duration, future: F) -> Result<F::Output, Elapsed> {
#[cfg(not(target_arch = "wasm32"))]
{
tokio::time::timeout(duration, future)
.await
.map_err(|_| Elapsed(duration))
}
#[cfg(target_arch = "wasm32")]
{
use futures_util::future::{select, Either};
let future = std::pin::pin!(future);
let deadline = std::pin::pin!(sleep(duration));
match select(future, deadline).await {
Either::Left((output, _)) => Ok(output),
Either::Right(((), _)) => Err(Elapsed(duration)),
}
}
}