1use std::time::Duration;
5
6pub async fn sleep(duration: Duration) {
11 imp::sleep(duration).await;
12}
13
14#[cfg(not(target_family = "wasm"))]
19#[must_use]
20pub fn timer_now() -> tokio::time::Instant {
21 tokio::time::Instant::now()
22}
23
24#[cfg(not(target_family = "wasm"))]
25mod imp {
26 use std::time::Duration;
27
28 pub(super) async fn sleep(duration: Duration) {
29 tokio::time::sleep(duration).await;
30 }
31}
32
33#[cfg(all(target_family = "wasm", target_os = "unknown"))]
34mod imp {
35 use std::time::Duration;
36
37 use wasm_bindgen::JsCast as _;
38
39 pub(super) async fn sleep(duration: Duration) {
42 let (fired, wait) = tokio::sync::oneshot::channel::<()>();
43 let armed = {
44 let callback = wasm_bindgen::closure::Closure::once_into_js(move || {
45 let _ = fired.send(());
46 });
47 #[allow(
49 clippy::cast_precision_loss,
50 reason = "a clamped millisecond count is exact in an f64"
51 )]
52 let millis = duration.as_millis().min(i32::MAX as u128) as f64;
53 let global = js_sys::global();
54 js_sys::Reflect::get(&global, &"setTimeout".into())
55 .ok()
56 .and_then(|set_timeout| set_timeout.dyn_into::<js_sys::Function>().ok())
57 .is_some_and(|set_timeout| {
58 set_timeout
59 .call2(&global, &callback, &millis.into())
60 .is_ok()
61 })
62 };
63 if armed {
64 let _ = wait.await;
65 }
66 }
67}
68
69#[cfg(all(target_family = "wasm", not(target_os = "unknown")))]
70mod imp {
71 use std::time::Duration;
72
73 pub(super) async fn sleep(duration: Duration) {
74 tokio::time::sleep(duration).await;
75 }
76}
77
78#[cfg(test)]
79#[cfg(not(target_family = "wasm"))]
80mod tests {
81 use super::*;
82
83 tilo_test_env::scenario! {
84 fn sleep_waits_on_the_runtime_timer_and_is_send;
85
86 phase sleep_waits_on_the_runtime_timer;
87 {
88 let started = tilo_clock::now();
89 crate::block_on(sleep(Duration::from_millis(30))).unwrap();
90 assert!(started.elapsed() >= Duration::from_millis(30));
91 }
92
93 phase sleep_is_send;
94 {
95 fn send<T: Send>(_: &T) {}
96 send(&sleep(Duration::ZERO));
97 }
98 }
99}