1use std::future::Future;
7use std::time::Duration;
8
9#[cfg(not(target_arch = "wasm32"))]
12pub use tokio::time::Instant;
13#[cfg(target_arch = "wasm32")]
14pub use web_time::Instant;
15pub use web_time::{SystemTime, UNIX_EPOCH};
16
17#[cfg(not(target_arch = "wasm32"))]
21pub trait MaybeSend: Send {}
22#[cfg(not(target_arch = "wasm32"))]
23impl<T: Send + ?Sized> MaybeSend for T {}
24
25#[cfg(target_arch = "wasm32")]
27pub trait MaybeSend {}
28#[cfg(target_arch = "wasm32")]
29impl<T: ?Sized> MaybeSend for T {}
30
31pub fn spawn<F>(future: F)
34where
35 F: Future<Output = ()> + MaybeSend + 'static,
36{
37 #[cfg(not(target_arch = "wasm32"))]
38 drop(tokio::spawn(future));
39 #[cfg(target_arch = "wasm32")]
40 wasm_bindgen_futures::spawn_local(future);
41}
42
43pub struct Task<T: 'static> {
47 handle: Option<futures_util::future::RemoteHandle<Result<T, futures_util::future::Aborted>>>,
48 abort: futures_util::future::AbortHandle,
49}
50
51#[derive(Debug, Clone, Copy, PartialEq, Eq, thiserror::Error)]
53#[error("the task was aborted")]
54pub struct Aborted;
55
56pub fn spawn_task<F>(future: F) -> Task<F::Output>
59where
60 F: Future + MaybeSend + 'static,
61 F::Output: MaybeSend + 'static,
62{
63 use futures_util::FutureExt;
64 let (future, abort) = futures_util::future::abortable(future);
65 let (future, handle) = future.remote_handle();
66 spawn(future);
67 Task {
68 handle: Some(handle),
69 abort,
70 }
71}
72
73impl<T: 'static> Task<T> {
74 pub async fn join(mut self) -> Result<T, Aborted> {
80 match self.handle.take() {
81 Some(handle) => handle.await.map_err(|_| Aborted),
82 None => Err(Aborted),
83 }
84 }
85
86 pub fn abort(&self) {
88 self.abort.abort();
89 }
90}
91
92impl<T: 'static> Drop for Task<T> {
93 fn drop(&mut self) {
94 if let Some(handle) = self.handle.take() {
95 handle.forget();
96 }
97 }
98}
99
100#[derive(Debug, Clone, Copy, PartialEq, Eq, thiserror::Error)]
102#[error("timed out after {0:?}")]
103pub struct Elapsed(pub Duration);
104
105pub async fn sleep(duration: Duration) {
107 #[cfg(not(target_arch = "wasm32"))]
108 tokio::time::sleep(duration).await;
109 #[cfg(target_arch = "wasm32")]
110 gloo_timers::future::sleep(duration).await;
111}
112
113pub async fn timeout<F: Future>(duration: Duration, future: F) -> Result<F::Output, Elapsed> {
119 #[cfg(not(target_arch = "wasm32"))]
120 {
121 tokio::time::timeout(duration, future)
122 .await
123 .map_err(|_| Elapsed(duration))
124 }
125 #[cfg(target_arch = "wasm32")]
126 {
127 use futures_util::future::{select, Either};
128 let future = std::pin::pin!(future);
129 let deadline = std::pin::pin!(sleep(duration));
130 match select(future, deadline).await {
131 Either::Left((output, _)) => Ok(output),
132 Either::Right(((), _)) => Err(Elapsed(duration)),
133 }
134 }
135}