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
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
use std::{
  future::Future,
  pin::Pin,
  time::{Duration, Instant},
};

/// The sleep abstraction for a runtime.
#[cfg_attr(docsrs, doc(cfg(feature = "std")))]
pub trait AsyncSleep: Future<Output = Instant> {
  /// Resets the Sleep instance to a new deadline.
  ///
  /// The behavior of this function may different in different runtime implementations.
  fn reset(self: Pin<&mut Self>, deadline: Instant);
}

/// Extension trait for [`AsyncSleep`].
#[cfg_attr(docsrs, doc(cfg(feature = "std")))]
pub trait AsyncSleepExt: AsyncSleep {
  /// Creates a timer that emits an event once after the given duration of time.
  fn sleep(after: Duration) -> Self
  where
    Self: Sized;

  /// Creates a timer that emits an event once at the given time instant.
  fn sleep_until(deadline: Instant) -> Self
  where
    Self: Sized;
}

#[cfg(all(feature = "tokio", feature = "std"))]
#[cfg_attr(docsrs, doc(cfg(all(feature = "std", feature = "tokio"))))]
pub use _tokio::TokioSleep;

#[cfg(all(feature = "tokio", feature = "std"))]
mod _tokio {
  use super::*;
  use core::task::Poll;

  pin_project_lite::pin_project! {
    /// The [`AsyncSleep`] implementation for tokio runtime
    #[cfg_attr(docsrs, doc(cfg(all(feature = "std", feature = "tokio"))))]
    #[repr(transparent)]
    pub struct TokioSleep {
      #[pin]
      inner: ::tokio::time::Sleep,
    }
  }

  impl From<::tokio::time::Sleep> for TokioSleep {
    fn from(sleep: ::tokio::time::Sleep) -> Self {
      Self { inner: sleep }
    }
  }

  impl From<TokioSleep> for ::tokio::time::Sleep {
    fn from(sleep: TokioSleep) -> Self {
      sleep.inner
    }
  }

  impl Future for TokioSleep {
    type Output = Instant;

    fn poll(self: std::pin::Pin<&mut Self>, cx: &mut std::task::Context<'_>) -> Poll<Self::Output> {
      let this = self.project();
      let ddl = this.inner.deadline().into();
      match this.inner.poll(cx) {
        Poll::Ready(_) => Poll::Ready(ddl),
        Poll::Pending => Poll::Pending,
      }
    }
  }

  impl AsyncSleep for TokioSleep {
    fn reset(self: std::pin::Pin<&mut Self>, deadline: Instant) {
      self.project().inner.as_mut().reset(deadline.into())
    }
  }

  impl AsyncSleepExt for TokioSleep {
    fn sleep(after: Duration) -> Self
    where
      Self: Sized,
    {
      Self {
        inner: tokio::time::sleep(after),
      }
    }

    fn sleep_until(deadline: Instant) -> Self
    where
      Self: Sized,
    {
      Self {
        inner: tokio::time::sleep_until(tokio::time::Instant::from_std(deadline)),
      }
    }
  }

  #[cfg(test)]
  mod tests {
    use super::*;

    const ORIGINAL: Duration = Duration::from_secs(1);
    const RESET: Duration = Duration::from_secs(2);
    const BOUND: Duration = Duration::from_millis(10);

    #[tokio::test]
    async fn test_object_safe() {
      let _a: Box<dyn AsyncSleep> = Box::new(TokioSleep::sleep(ORIGINAL));
    }

    #[tokio::test]
    async fn test_tokio_sleep() {
      let start = Instant::now();
      let sleep = TokioSleep::sleep(ORIGINAL);
      let ins = sleep.await;
      assert!(ins >= start + ORIGINAL);
      let elapsed = start.elapsed();
      assert!(elapsed >= ORIGINAL && elapsed < ORIGINAL + BOUND);
    }

    #[tokio::test]
    async fn test_tokio_sleep_until() {
      let start = Instant::now();
      let sleep = TokioSleep::sleep_until(start + ORIGINAL);
      let ins = sleep.await;
      assert!(ins >= start + ORIGINAL);
      let elapsed = start.elapsed();
      assert!(elapsed >= ORIGINAL && elapsed < ORIGINAL + BOUND);
    }

    #[tokio::test]
    async fn test_tokio_sleep_reset() {
      let start = Instant::now();
      let sleep = TokioSleep::sleep(ORIGINAL);
      tokio::pin!(sleep);
      sleep.as_mut().reset(Instant::now() + RESET);
      let ins = sleep.await;
      assert!(ins >= start + RESET);
      let elapsed = start.elapsed();
      assert!(elapsed >= RESET && elapsed < RESET + BOUND);
    }

    #[tokio::test]
    async fn test_tokio_sleep_reset2() {
      let start = Instant::now();
      let sleep = TokioSleep::sleep_until(start + ORIGINAL);
      tokio::pin!(sleep);
      sleep.as_mut().reset(Instant::now() + RESET);
      let ins = sleep.await;
      assert!(ins >= start + RESET);
      let elapsed = start.elapsed();
      assert!(elapsed >= RESET && elapsed < RESET + BOUND);
    }
  }
}

#[cfg(all(feature = "async-io", feature = "std"))]
#[cfg_attr(docsrs, doc(cfg(all(feature = "std", feature = "async-io"))))]
pub use _async_io::AsyncIoSleep;

#[cfg(all(feature = "async-io", feature = "std"))]
mod _async_io {
  use super::*;
  use async_io::Timer;
  use core::task::{Context, Poll};

  pin_project_lite::pin_project! {
    /// The [`AsyncSleep`] implementation for any runtime based on [`async-io`](async_io), e.g. `async-std` and `smol`.
    #[derive(Debug)]
    #[repr(transparent)]
    #[cfg_attr(docsrs, doc(cfg(all(feature = "std", feature = "async-io"))))]
    pub struct AsyncIoSleep {
      #[pin]
      t: Timer,
    }
  }

  impl From<Timer> for AsyncIoSleep {
    fn from(t: Timer) -> Self {
      Self { t }
    }
  }

  impl From<AsyncIoSleep> for Timer {
    fn from(s: AsyncIoSleep) -> Self {
      s.t
    }
  }

  impl Future for AsyncIoSleep {
    type Output = Instant;

    fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
      self.project().t.poll(cx)
    }
  }

  impl AsyncSleepExt for AsyncIoSleep {
    fn sleep(after: Duration) -> Self
    where
      Self: Sized,
    {
      Self {
        t: async_io::Timer::after(after),
      }
    }

    fn sleep_until(deadline: Instant) -> Self
    where
      Self: Sized,
    {
      Self {
        t: async_io::Timer::at(deadline),
      }
    }
  }

  impl AsyncSleep for AsyncIoSleep {
    /// Sets the timer to emit an event once at the given time instant.
    ///
    /// Note that resetting a timer is different from creating a new sleep by [`sleep()`][`Runtime::sleep()`] because
    /// `reset()` does not remove the waker associated with the task.
    fn reset(self: Pin<&mut Self>, deadline: Instant) {
      self.project().t.as_mut().set_at(deadline)
    }
  }

  #[test]
  fn test_object_safe() {
    let _a: Box<dyn AsyncSleep> = Box::new(AsyncIoSleep::sleep(Duration::from_secs(1)));
  }

  #[cfg(test)]
  mod tests {
    use super::*;

    const ORIGINAL: Duration = Duration::from_secs(1);
    const RESET: Duration = Duration::from_secs(2);
    const BOUND: Duration = Duration::from_millis(10);

    #[test]
    fn test_object_safe() {
      let _a: Box<dyn AsyncSleep> = Box::new(AsyncIoSleep::sleep(ORIGINAL));
    }

    #[test]
    fn test_asyncio_sleep() {
      futures::executor::block_on(async {
        let start = Instant::now();
        let sleep = AsyncIoSleep::sleep(ORIGINAL);
        let ins = sleep.await;
        assert!(ins >= start + ORIGINAL);
        let elapsed = start.elapsed();
        assert!(elapsed >= ORIGINAL && elapsed < ORIGINAL + BOUND);
      });
    }

    #[test]
    fn test_asyncio_sleep_until() {
      futures::executor::block_on(async {
        let start = Instant::now();
        let sleep = AsyncIoSleep::sleep_until(start + ORIGINAL);
        let ins = sleep.await;
        assert!(ins >= start + ORIGINAL);
        let elapsed = start.elapsed();
        assert!(elapsed >= ORIGINAL && elapsed < ORIGINAL + BOUND);
      });
    }

    #[test]
    fn test_asyncio_sleep_reset() {
      futures::executor::block_on(async {
        let start = Instant::now();
        let mut sleep = AsyncIoSleep::sleep(ORIGINAL);
        let pin = Pin::new(&mut sleep);
        pin.reset(Instant::now() + RESET);
        let ins = sleep.await;
        assert!(ins >= start + RESET);
        let elapsed = start.elapsed();
        assert!(elapsed >= RESET && elapsed < RESET + BOUND);
      });
    }

    #[test]
    fn test_asyncio_sleep_reset2() {
      futures::executor::block_on(async {
        let start = Instant::now();
        let mut sleep = AsyncIoSleep::sleep_until(start + ORIGINAL);
        let pin = Pin::new(&mut sleep);
        pin.reset(Instant::now() + RESET);
        let ins = sleep.await;
        assert!(ins >= start + RESET);
        let elapsed = start.elapsed();
        assert!(elapsed >= RESET && elapsed < RESET + BOUND);
      });
    }
  }
}

#[cfg(all(feature = "wasm", feature = "std"))]
#[cfg_attr(docsrs, doc(cfg(all(feature = "std", feature = "wasm"))))]
pub use _wasm::WasmSleep;

#[cfg(all(feature = "wasm", feature = "std"))]
mod _wasm {
  use super::*;
  use core::task::{Context, Poll};
  use futures_timer::Delay;

  pin_project_lite::pin_project! {
    /// The [`AsyncSleep`] implementation for wasm-bindgen based runtime.
    #[cfg_attr(docsrs, doc(cfg(all(feature = "std", feature = "wasm"))))]
    pub struct WasmSleep {
      #[pin]
      pub(crate) sleep: Delay,
      pub(crate) ddl: Instant,
      pub(crate) duration: Duration,
    }
  }

  impl Future for WasmSleep {
    type Output = Instant;

    fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
      let ddl = self.ddl;
      self.project().sleep.poll(cx).map(|_| ddl)
    }
  }

  impl AsyncSleep for WasmSleep {
    fn reset(self: Pin<&mut Self>, deadline: Instant) {
      let mut this = self.project();
      let ddl = deadline - Instant::now();
      this.sleep.reset(ddl);
      *this.ddl = deadline;
    }
  }

  impl AsyncSleepExt for WasmSleep {
    fn sleep(after: Duration) -> Self
    where
      Self: Sized,
    {
      Self {
        ddl: Instant::now() + after,
        sleep: Delay::new(after),
        duration: after,
      }
    }

    fn sleep_until(deadline: Instant) -> Self
    where
      Self: Sized,
    {
      let duration = deadline - Instant::now();
      Self {
        sleep: Delay::new(duration),
        ddl: deadline,
        duration,
      }
    }
  }

  #[cfg(test)]
  mod tests {
    use super::*;

    const ORIGINAL: Duration = Duration::from_secs(1);
    const RESET: Duration = Duration::from_secs(2);
    const BOUND: Duration = Duration::from_millis(10);

    #[test]
    fn test_object_safe() {
      let _a: Box<dyn AsyncSleep> = Box::new(WasmSleep::sleep(ORIGINAL));
    }

    #[test]
    fn test_wasm_sleep() {
      futures::executor::block_on(async {
        let start = Instant::now();
        let sleep = WasmSleep::sleep(ORIGINAL);
        let ins = sleep.await;
        assert!(ins >= start + ORIGINAL);
        let elapsed = start.elapsed();
        assert!(elapsed >= ORIGINAL && elapsed < ORIGINAL + BOUND);
      });
    }

    #[test]
    fn test_wasm_sleep_until() {
      futures::executor::block_on(async {
        let start = Instant::now();
        let sleep = WasmSleep::sleep_until(start + ORIGINAL);
        let ins = sleep.await;
        assert!(ins >= start + ORIGINAL);
        let elapsed = start.elapsed();
        assert!(elapsed >= ORIGINAL && elapsed < ORIGINAL + BOUND);
      });
    }

    #[test]
    fn test_wasm_sleep_reset() {
      futures::executor::block_on(async {
        let start = Instant::now();
        let mut sleep = WasmSleep::sleep(ORIGINAL);
        let pin = Pin::new(&mut sleep);
        pin.reset(Instant::now() + RESET);
        let ins = sleep.await;
        assert!(ins >= start + RESET);
        let elapsed = start.elapsed();
        assert!(elapsed >= RESET && elapsed < RESET + BOUND);
      });
    }

    #[test]
    fn test_wasm_sleep_reset2() {
      futures::executor::block_on(async {
        let start = Instant::now();
        let mut sleep = WasmSleep::sleep_until(start + ORIGINAL);
        let pin = Pin::new(&mut sleep);
        pin.reset(Instant::now() + RESET);
        let ins = sleep.await;
        assert!(ins >= start + RESET);
        let elapsed = start.elapsed();
        assert!(elapsed >= RESET && elapsed < RESET + BOUND);
      });
    }
  }
}