1use cfg_if::cfg_if;
2use core::future::Future;
3
4cfg_if! {
5 if #[cfg(feature = "tokio_runtime")] {
6 pub async fn timeout<T>(
7 duration: core::time::Duration,
8 fut: impl Future<Output = T>,
9 ) -> Result<T, ()> {
10 tokio::time::timeout(duration, fut)
11 .await
12 .map_err(|_| ())
13 }
14
15 pub async fn sleep(dur: core::time::Duration) {
16 tokio::time::sleep(dur).await;
17 }
18 }
19
20 else if #[cfg(feature = "wasm_runtime")] {
21 use futures::future;
22
23 pub async fn timeout<T>(
24 duration: core::time::Duration,
25 fut: impl Future<Output = T>,
26 ) -> Result<T, ()> {
27 let timeout_fut = sleep(duration);
28 futures::pin_mut!(fut);
29 futures::pin_mut!(timeout_fut);
30
31 match future::select(fut, timeout_fut).await {
32 future::Either::Left((res, _)) => Ok(res),
33 future::Either::Right(_) => Err(()),
34 }
35 }
36 pub async fn sleep(dur: core::time::Duration) {
37 gloo_timers::future::sleep(dur).await;
38 }
39 }
40
41 else if #[cfg(feature = "embassy_runtime")] {
42 use embassy_time::{Duration, Timer};
43 use embassy_futures::select::select;
44 use embassy_futures::select::Either;
45
46 pub async fn sleep(dur: core::time::Duration) {
47 let emb_dur = Duration::from_millis(dur.as_millis() as u64);
48 Timer::after(emb_dur).await;
49 }
50
51 pub async fn timeout<T>(
52 duration: core::time::Duration,
53 fut: impl Future<Output = T>,
54 ) -> Result<T, ()> {
55 let emb_dur = Duration::from_millis(duration.as_millis() as u64);
56 let timeout = Timer::after(emb_dur);
57
58 match select(fut, timeout).await {
59 Either::First(t) => Ok(t),
60 Either::Second(_) => Err(()),
61 }
62 }
63 }
64 else {
65 pub async fn sleep(duration: core::time::Duration) {
66 let mut interval = async_timer::Interval::platform_new(duration);
67 interval.wait().await;
68 }
69
70 pub async fn timeout<T>(
71 duration: core::time::Duration,
72 fut: impl Future<Output = T>,
73 ) -> Result<T, ()> {
74 let mut pinned_fut = core::pin::pin!(fut);
75 let work = async_timer::Timed::platform_new(pinned_fut.as_mut(), duration);
76
77 work.await.map_err(|_| ())
78 }
79 }
80}