Skip to main content

zbus/abstractions/
timeout.rs

1use crate::{Error, Result};
2use std::{future::Future, io::ErrorKind, time::Duration};
3
4#[cfg(feature = "tokio")]
5async fn timeout_tokio<F, T>(fut: F, timeout: Duration) -> Result<T>
6where
7    F: Future<Output = Result<T>>,
8{
9    tokio::time::timeout(timeout, fut).await.map_err(|_| {
10        Error::from(std::io::Error::new(
11            ErrorKind::TimedOut,
12            "timed out".to_string(),
13        ))
14    })?
15}
16
17#[cfg(feature = "async-io")]
18async fn timeout_async_io<F, T>(fut: F, timeout: Duration) -> Result<T>
19where
20    F: Future<Output = Result<T>>,
21{
22    use futures_lite::FutureExt;
23
24    fut.or(async {
25        async_io::Timer::after(timeout).await;
26
27        Err(Error::from(std::io::Error::new(
28            ErrorKind::TimedOut,
29            "timed out",
30        )))
31    })
32    .await
33}
34
35/// Awaits a future with a provided timeout.
36pub(crate) async fn timeout<F, T>(fut: F, timeout: Duration) -> Result<T>
37where
38    F: Future<Output = Result<T>>,
39{
40    crate::abstractions::select_runtime! {
41        tokio: timeout_tokio(fut, timeout).await,
42        async_io: timeout_async_io(fut, timeout).await,
43    }
44}