atagen

matrix-rust-sdk

public
Star0
Watch0
ssh://brewery@pls.lobotomise.me:33/atagen/matrix-rust-sdk.git
crates/matrix-sdk-common/src/timeout.rsRust85 lines2.6 KB
1
// Copyright 2022 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::{error::Error, fmt, time::Duration};
16
17
use futures_core::Future;
18
#[cfg(target_family = "wasm")]
19
use futures_util::future::{Either, select};
20
#[cfg(target_family = "wasm")]
21
use gloo_timers::future::TimeoutFuture;
22
#[cfg(not(target_family = "wasm"))]
23
use tokio::time::timeout as tokio_timeout;
24
25
/// Error type notifying that a timeout has elapsed.
26
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
27
pub struct ElapsedError();
28
29
impl fmt::Display for ElapsedError {
30
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
31
        write!(f, "time waiting for future has elapsed!")
32
    }
33
}
34
35
impl Error for ElapsedError {}
36
37
/// Wait for `future` to be completed. `future` needs to return
38
/// a `Result`.
39
///
40
/// If the given timeout has elapsed the method will stop waiting and return
41
/// an error.
42
pub async fn timeout<F, T>(future: F, duration: Duration) -> Result<T, ElapsedError>
43
where
44
    F: Future<Output = T>,
45
{
46
    #[cfg(not(target_family = "wasm"))]
47
    return tokio_timeout(duration, future).await.map_err(|_| ElapsedError());
48
49
    #[cfg(target_family = "wasm")]
50
    {
51
        let timeout_future =
52
            TimeoutFuture::new(u32::try_from(duration.as_millis()).expect("Overlong duration"));
53
54
        match select(std::pin::pin!(future), timeout_future).await {
55
            Either::Left((res, _)) => Ok(res),
56
            Either::Right((_, _)) => Err(ElapsedError()),
57
        }
58
    }
59
}
60
61
#[cfg(test)]
62
pub(crate) mod tests {
63
    use std::{future, time::Duration};
64
65
    use matrix_sdk_test_macros::async_test;
66
67
    use super::timeout;
68
69
    #[cfg(target_family = "wasm")]
70
    wasm_bindgen_test::wasm_bindgen_test_configure!(run_in_browser);
71
72
    #[async_test]
73
    async fn test_without_timeout() {
74
        timeout(future::ready(()), Duration::from_millis(100))
75
            .await
76
            .expect("future should have completed without ElapsedError");
77
    }
78
79
    #[async_test]
80
    async fn test_with_timeout() {
81
        timeout(future::pending::<()>(), Duration::from_millis(100))
82
            .await
83
            .expect_err("future should return an ElapsedError");
84
    }
85
}