1use std::future::Future;
4use std::time::{Duration, Instant};
5
6use async_io::Timer;
7use futures_lite::future::or;
8
9pub trait FutureTimeout<T>: Future<Output = T> + Sized {
11 fn timeout(self, duration: Duration) -> impl Future<Output = Option<T>> {
16 let this = async { Some(self.await) };
17
18 let timeout = async move {
19 sleep(duration).await;
20 None
21 };
22
23 or(this, timeout)
24 }
25}
26
27impl<T, F: Future<Output = T>> FutureTimeout<T> for F {}
28
29pub async fn sleep(duration: Duration) {
31 Timer::after(duration).await;
32}
33
34pub async fn sleep_until(instant: Instant) {
36 Timer::at(instant).await;
37}