agnostic_lite/time/
timeout.rs1use core::{
2 future::Future,
3 time::Duration,
4};
5
6pub trait AsyncTimeout<F>
8where
9 F: Future + Send,
10 Self: Future<Output = Result<F::Output, Elapsed>> + Send
11{
12 type Instant: super::Instant;
14
15 fn timeout(timeout: Duration, fut: F) -> Self
19 where
20 F: Future + Send,
21 Self: Future<Output = Result<F::Output, Elapsed>> + Send + Sized;
22
23 fn timeout_at(deadline: Self::Instant, fut: F) -> Self
27 where
28 F: Future + Send,
29 Self: Future<Output = Result<F::Output, Elapsed>> + Send + Sized;
30}
31
32pub trait AsyncLocalTimeout<F: Future>: Future<Output = Result<F::Output, Elapsed>> {
34 type Instant: super::Instant;
36
37 fn timeout_local(timeout: Duration, fut: F) -> Self
41 where
42 Self: Sized + Future<Output = Result<F::Output, Elapsed>>,
43 F: Future;
44
45 fn timeout_local_at(deadline: Self::Instant, fut: F) -> Self
49 where
50 Self: Sized + Future<Output = Result<F::Output, Elapsed>>,
51 F: Future;
52}
53
54#[derive(Debug, PartialEq, Eq)]
56pub struct Elapsed;
57
58impl core::fmt::Display for Elapsed {
59 fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
60 write!(f, "deadline has elapsed")
61 }
62}
63
64impl core::error::Error for Elapsed {}
65
66#[cfg(feature = "std")]
67impl From<Elapsed> for std::io::Error {
68 fn from(_: Elapsed) -> Self {
69 std::io::ErrorKind::TimedOut.into()
70 }
71}
72
73#[cfg(feature = "tokio")]
74impl From<::tokio::time::error::Elapsed> for Elapsed {
75 fn from(_: ::tokio::time::error::Elapsed) -> Self {
76 Elapsed
77 }
78}
79
80#[test]
81#[cfg(feature = "std")]
82fn test_elapsed_error() {
83 assert_eq!(Elapsed.to_string(), "deadline has elapsed");
84 let _: std::io::Error = Elapsed.into();
85}