atagen

matrix-rust-sdk

public
Star0
Watch0
ssh://brewery@pls.lobotomise.me:33/atagen/matrix-rust-sdk.git
crates/matrix-sdk-common/src/sleep.rsRust49 lines1.5 KB
1
// Copyright 2024 The Matrix.org Foundation C.I.C.
2
//
3
// Licensed under the Apache License, Version 2.0 (the "License");
4
// you may not use this file except in compliance with the License.
5
// You may obtain a copy of the License at
6
//
7
//     http://www.apache.org/licenses/LICENSE-2.0
8
//
9
// Unless required by applicable law or agreed to in writing, software
10
// distributed under the License is distributed on an "AS IS" BASIS,
11
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
// See the License for the specific language governing permissions and
13
// limitations under the License.
14
15
use std::time::Duration;
16
17
/// Sleep for the specified duration.
18
///
19
/// This is a cross-platform sleep implementation that works on both wasm32 and
20
/// non-wasm32 targets.
21
pub async fn sleep(duration: Duration) {
22
    #[cfg(not(target_family = "wasm"))]
23
    tokio::time::sleep(duration).await;
24
25
    #[cfg(target_family = "wasm")]
26
    gloo_timers::future::TimeoutFuture::new(u32::try_from(duration.as_millis()).unwrap_or_else(
27
        |_| {
28
            tracing::error!("Sleep duration too long, sleeping for u32::MAX ms");
29
            u32::MAX
30
        },
31
    ))
32
    .await;
33
}
34
35
#[cfg(test)]
36
mod tests {
37
    use matrix_sdk_test_macros::async_test;
38
39
    use super::*;
40
41
    #[cfg(target_family = "wasm")]
42
    wasm_bindgen_test::wasm_bindgen_test_configure!(run_in_browser);
43
44
    #[async_test]
45
    async fn test_sleep() {
46
        // Just test that it doesn't panic
47
        sleep(Duration::from_millis(1)).await;
48
    }
49
}