aboutsummaryrefslogtreecommitdiff
path: root/core/src/async_util/timeout.rs
blob: 9ac64c86ae76ccd6c5512742e50507f10c471dca (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
use std::{future::Future, time::Duration};

use crate::{error::Error, Result};

use super::{select, sleep, Either};

/// Waits for a future to complete or times out if it exceeds a specified
/// duration.
///
/// # Example
///
/// ```
/// use std::{future, time::Duration};
///
/// use karyon_core::async_util::timeout;
///
/// async {
///     let fut = future::pending::<()>();
///     assert!(timeout(Duration::from_millis(100), fut).await.is_err());
/// };
///
/// ```
///
pub async fn timeout<T, F>(delay: Duration, future1: F) -> Result<T>
where
    F: Future<Output = T>,
{
    let result = select(sleep(delay), future1).await;

    match result {
        Either::Left(_) => Err(Error::Timeout),
        Either::Right(res) => Ok(res),
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use std::{future, time::Duration};

    #[test]
    fn test_timeout() {
        crate::async_runtime::block_on(async move {
            let fut = future::pending::<()>();
            assert!(timeout(Duration::from_millis(10), fut).await.is_err());

            let fut = sleep(Duration::from_millis(10));
            assert!(timeout(Duration::from_millis(50), fut).await.is_ok())
        });
    }
}