bitwarden_threading/
time.rs

1use std::time::Duration;
2
3#[cfg(not(target_arch = "wasm32"))]
4pub async fn sleep(duration: Duration) {
5    tokio::time::sleep(duration).await;
6}
7
8#[cfg(target_arch = "wasm32")]
9pub async fn sleep(duration: Duration) {
10    use gloo_timers::future::sleep;
11
12    sleep(duration).await;
13}
14
15#[cfg(test)]
16mod test {
17    use wasm_bindgen_test::wasm_bindgen_test;
18
19    #[wasm_bindgen_test]
20    #[allow(dead_code)] // Not actually dead, but rust-analyzer doesn't understand `wasm_bindgen_test`
21    async fn should_sleep_wasm() {
22        use js_sys::Date;
23
24        use super::*;
25
26        console_error_panic_hook::set_once();
27        let start = Date::now();
28
29        sleep(Duration::from_millis(100)).await;
30
31        let end = Date::now();
32        let elapsed = end - start;
33
34        assert!(elapsed >= 90.0, "Elapsed time was less than expected");
35    }
36
37    #[tokio::test]
38    async fn should_sleep_tokio() {
39        use std::time::Instant;
40
41        use super::*;
42
43        let start = Instant::now();
44
45        sleep(Duration::from_millis(100)).await;
46
47        let end = Instant::now();
48        let elapsed = end.duration_since(start);
49
50        assert!(
51            elapsed >= Duration::from_millis(90),
52            "Elapsed time was less than expected"
53        );
54    }
55}