1use std::time::Duration;
2
3#[inline]
4pub async fn sleep(duration: Duration) {
5 timeout_future(duration).await;
6}
7
8#[cfg(not(target_os = "unknown"))]
9pub use os::*;
10#[cfg(not(target_os = "unknown"))]
11mod os {
12 use std::{
13 future::Future,
14 pin::Pin,
15 task::{Context, Poll},
16 time::Duration,
17 };
18
19 use async_global_executor::Task;
20
21 pub struct JoinHandle<T> {
22 task: Option<Task<T>>,
23 }
24
25 impl<T> Drop for JoinHandle<T> {
26 fn drop(&mut self) {
27 if let Some(task) = self.task.take() {
28 task.detach();
29 }
30 }
31 }
32
33 impl<T> Future for JoinHandle<T> {
34 type Output = T;
35
36 fn poll(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
37 match self.task.as_mut() {
38 Some(task) => Future::poll(Pin::new(task), cx),
39 None => unreachable!("JoinHandle polled after dropping"),
40 }
41 }
42 }
43
44 pub fn spawn<F>(f: F) -> JoinHandle<F::Output>
45 where
46 F: Future + Send + 'static,
47 F::Output: Send,
48 {
49 JoinHandle {
50 task: Some(async_global_executor::spawn(f)),
51 }
52 }
53
54 pub fn spawn_local<F>(f: F) -> JoinHandle<F::Output>
55 where
56 F: Future + 'static,
57 {
58 JoinHandle {
59 task: Some(async_global_executor::spawn_local(f)),
60 }
61 }
62
63 pub fn spawn_blocking<F, T>(f: F) -> impl Future<Output = T>
64 where
65 F: FnOnce() -> T + Send + 'static,
66 T: Send + 'static,
67 {
68 async_global_executor::spawn_blocking(f)
69 }
70
71 pub fn block_on<T>(future: impl Future<Output = T>) -> T {
72 async_io::block_on(future)
73 }
74
75 pub fn timeout_future(duration: Duration) -> impl Future {
76 async_io::Timer::after(duration)
77 }
78}
79
80#[cfg(target_arch = "wasm32")]
81pub use wasm::*;
82#[cfg(target_arch = "wasm32")]
83mod wasm {
84 use std::{future::Future, time::Duration};
85
86 pub fn spawn<F>(f: F)
87 where
88 F: Future + 'static,
89 {
90 spawn_local(f)
91 }
92
93 pub fn spawn_local<F>(f: F)
94 where
95 F: Future + 'static,
96 {
97 wasm_bindgen_futures::spawn_local(async move {
98 f.await;
99 });
100 }
101
102 pub fn timeout_future(duration: Duration) -> impl Future {
103 gloo_timers::future::TimeoutFuture::new(duration.as_millis() as u32)
104 }
105}