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