1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
use std::{
  future::Future,
  time::{Duration, Instant},
};

/// The timeout abstraction for async runtime.
pub trait AsyncTimeout<F: Future + Send>:
  Future<Output = Result<F::Output, Elapsed>> + Send
{
  /// Requires a `Future` to complete before the specified duration has elapsed.
  ///
  /// The behavior of this function may different in different runtime implementations.
  fn timeout(timeout: Duration, fut: F) -> Self
  where
    Self: Sized;

  /// Requires a `Future` to complete before the specified instant in time.
  ///
  /// The behavior of this function may different in different runtime implementations.
  fn timeout_at(deadline: Instant, fut: F) -> Self
  where
    Self: Sized;
}

/// Like [`AsyncTimeout`], but this does not require `Send`.
pub trait AsyncLocalTimeout<F: Future>: Future<Output = Result<F::Output, Elapsed>> {
  /// Requires a `Future` to complete before the specified duration has elapsed.
  ///
  /// The behavior of this function may different in different runtime implementations.
  fn timeout_local(timeout: Duration, fut: F) -> Self
  where
    Self: Sized;

  /// Requires a `Future` to complete before the specified instant in time.
  ///
  /// The behavior of this function may different in different runtime implementations.
  fn timeout_local_at(deadline: Instant, fut: F) -> Self
  where
    Self: Sized;
}

/// Elapsed error
#[derive(Debug, PartialEq, Eq)]
pub struct Elapsed;

impl core::fmt::Display for Elapsed {
  fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
    write!(f, "deadline has elapsed")
  }
}

impl std::error::Error for Elapsed {}

impl From<Elapsed> for std::io::Error {
  fn from(_: Elapsed) -> Self {
    std::io::ErrorKind::TimedOut.into()
  }
}

#[cfg(feature = "tokio")]
impl From<::tokio::time::error::Elapsed> for Elapsed {
  fn from(_: ::tokio::time::error::Elapsed) -> Self {
    Elapsed
  }
}

#[test]
fn test_elapsed_error() {
  assert_eq!(Elapsed.to_string(), "deadline has elapsed");
  let _: std::io::Error = Elapsed.into();
}