zbus/abstractions/
timeout.rs

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