Skip to main content

agnostic_lite/time/
timeout.rs

1use core::{
2  future::Future,
3  time::Duration,
4};
5
6/// The timeout abstraction for async runtime.
7pub trait AsyncTimeout<F>
8where
9  F: Future + Send,
10  Self: Future<Output = Result<F::Output, Elapsed>> + Send
11{
12  /// The instant type
13  type Instant: super::Instant;
14
15  /// Requires a `Future` to complete before the specified duration has elapsed.
16  ///
17  /// The behavior of this function may different in different runtime implementations.
18  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  /// Requires a `Future` to complete before the specified instant in time.
24  ///
25  /// The behavior of this function may different in different runtime implementations.
26  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
32/// Like [`AsyncTimeout`], but this does not require `Send`.
33pub trait AsyncLocalTimeout<F: Future>: Future<Output = Result<F::Output, Elapsed>> {
34  /// The instant type
35  type Instant: super::Instant;
36
37  /// Requires a `Future` to complete before the specified duration has elapsed.
38  ///
39  /// The behavior of this function may different in different runtime implementations.
40  fn timeout_local(timeout: Duration, fut: F) -> Self
41  where
42    Self: Sized + Future<Output = Result<F::Output, Elapsed>>,
43    F: Future;
44
45  /// Requires a `Future` to complete before the specified instant in time.
46  ///
47  /// The behavior of this function may different in different runtime implementations.
48  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/// Elapsed error
55#[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}