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
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
//! Agnostic is a trait for users who want to write async runtime-agnostic crate.
#![deny(warnings)]
#![cfg_attr(docsrs, feature(doc_cfg))]
#![cfg_attr(docsrs, allow(unused_attributes))]
#![allow(clippy::needless_return)]
#![allow(unreachable_code)]

#[cfg(all(feature = "compat", not(feature = "net")))]
compile_error!("`compat` feature is enabled, but `net` feature is disabled, `compact` feature must only be enabled with `net` feature");

#[macro_use]
mod macros;

/// [`tokio`] runtime adapter
///
/// [`tokio`]: https://docs.rs/tokio
#[cfg(feature = "tokio")]
#[cfg_attr(docsrs, doc(cfg(feature = "tokio")))]
pub mod tokio;

/// [`async_std`] runtime adapter
///
/// [`async_std`]: https://docs.rs/async-std
#[cfg(feature = "async-std")]
#[cfg_attr(docsrs, doc(cfg(feature = "async-std")))]
pub mod async_std;

/// [`smol`] runtime adapter
///
/// [`smol`]: https://docs.rs/smol
#[cfg(feature = "smol")]
#[cfg_attr(docsrs, doc(cfg(feature = "smol")))]
pub mod smol;

// /// [`monoio`] runtime adapter
// ///
// /// [`monoio`]: https://docs.rs/monoio
// #[cfg(not(all(feature = "monoio", feature = "net")))]
// #[cfg_attr(docsrs, doc(cfg(feature = "monoio")))]
// pub mod monoio;

#[cfg(feature = "net")]
#[cfg_attr(docsrs, doc(cfg(feature = "net")))]
pub mod net;

#[cfg(feature = "lock")]
#[cfg_attr(docsrs, doc(cfg(feature = "lock")))]
pub mod lock;

use std::{
  future::Future,
  time::{Duration, Instant},
};

use futures_util::Stream;

/// Simlilar to Go's `time.AfterFunc`
#[async_trait::async_trait]
pub trait Delay<F>
where
  F: Future + Send + 'static,
  F::Output: Send,
{
  fn new(delay: Duration, fut: F) -> Self;

  async fn reset(&mut self, dur: Duration);

  async fn cancel(&mut self) -> Option<F::Output>;
}

/// Runtime trait
pub trait Runtime: Send + Sync + 'static {
  type JoinHandle<F>: Future;
  type Interval: Stream;
  type Sleep: Future;
  type Delay<F>: Delay<F>
  where
    F: Future + Send + 'static,
    F::Output: Send;
  type Timeout<F>: Future
  where
    F: Future;
  #[cfg(feature = "net")]
  type Net: net::Net;

  #[cfg(feature = "lock")]
  type Mutex<T>: lock::Mutex<T>;

  #[cfg(feature = "lock")]
  type RwLock<T>: lock::RwLock<T>;

  fn new() -> Self;

  fn spawn<F>(&self, future: F) -> Self::JoinHandle<F::Output>
  where
    F::Output: Send + 'static,
    F: Future + Send + 'static;

  fn spawn_detach<F>(&self, future: F)
  where
    F::Output: Send + 'static,
    F: Future + Send + 'static,
  {
    self.spawn(future);
  }

  fn spawn_local<F>(&self, future: F) -> Self::JoinHandle<F::Output>
  where
    F: Future + 'static,
    F::Output: 'static;

  fn spawn_local_detach<F>(&self, future: F)
  where
    F: Future + 'static,
    F::Output: 'static,
  {
    self.spawn_local(future);
  }

  fn spawn_blocking<F, R>(&self, f: F) -> Self::JoinHandle<R>
  where
    F: FnOnce() -> R + Send + 'static,
    R: Send + 'static;

  fn spawn_blocking_detach<F, R>(&self, f: F)
  where
    F: FnOnce() -> R + Send + 'static,
    R: Send + 'static,
  {
    self.spawn_blocking(f);
  }

  fn interval(&self, interval: Duration) -> Self::Interval;

  fn interval_at(&self, start: Instant, period: Duration) -> Self::Interval;

  fn sleep(&self, duration: Duration) -> Self::Sleep;

  fn sleep_until(&self, instant: Instant) -> Self::Sleep;

  fn delay<F>(&self, duration: Duration, fut: F) -> Self::Delay<F>
  where
    F: Future + Send + 'static,
    F::Output: Send + Sync + 'static;

  fn timeout<F>(&self, duration: Duration, future: F) -> Self::Timeout<F>
  where
    F: Future;

  fn timeout_at<F>(&self, instant: Instant, future: F) -> Self::Timeout<F>
  where
    F: Future;
}

#[cfg(any(feature = "async-std", feature = "smol"))]
mod timer {
  use std::{future::Future, io, task::Poll, time::Duration};

  pin_project_lite::pin_project! {
    /// Future returned by the `FutureExt::timeout` method.
    #[derive(Debug)]
    #[cfg_attr(docsrs, doc(cfg(any(feature = "async-std", feature = "smol"))))]
    pub struct Timeout<F>
    where
        F: Future,
    {
      #[pin]
      pub(crate) future: F,
      #[pin]
      pub(crate) timeout: async_io::Timer,
    }
  }

  impl<F> Timeout<F>
  where
    F: Future,
  {
    pub fn new(timeout: Duration, future: F) -> Self {
      Self {
        future,
        timeout: async_io::Timer::after(timeout),
      }
    }
  }

  impl<F> Future for Timeout<F>
  where
    F: Future,
  {
    type Output = io::Result<F::Output>;

    fn poll(
      self: std::pin::Pin<&mut Self>,
      cx: &mut std::task::Context<'_>,
    ) -> std::task::Poll<Self::Output> {
      let this = self.project();
      match this.future.poll(cx) {
        Poll::Pending => {}
        other => return other.map(Ok),
      }

      if this.timeout.poll(cx).is_ready() {
        let err = Err(io::Error::new(io::ErrorKind::TimedOut, "future timed out"));
        Poll::Ready(err)
      } else {
        Poll::Pending
      }
    }
  }
}