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
432
433
434
435
436
437
438
439
440
#![doc = include_str!("../README.md")]
#![cfg_attr(not(any(feature = "std", test)), no_std)]
#![forbid(unsafe_code)]
#![deny(warnings, missing_docs)]
#![cfg_attr(docsrs, feature(doc_cfg))]
#![cfg_attr(docsrs, allow(unused_attributes))]

#[cfg(any(feature = "std", test))]
extern crate std;

use core::future::Future;

#[cfg(feature = "time")]
use std::time::{Duration, Instant};

/// Time related traits
#[cfg(feature = "time")]
#[cfg_attr(docsrs, doc(cfg(feature = "time")))]
pub mod time;

/// Concrete runtime implementations based on [`tokio`](::tokio) runtime.
#[cfg(feature = "tokio")]
#[cfg_attr(docsrs, doc(cfg(feature = "tokio")))]
pub mod tokio;

/// Concrete runtime implementations based on [`async-std`](::async_std) runtime.
#[cfg(feature = "async-std")]
#[cfg_attr(docsrs, doc(cfg(feature = "async-std")))]
pub mod async_std;

/// Concrete runtime implementations based on [`smol`](::smol) runtime.
#[cfg(feature = "smol")]
#[cfg_attr(docsrs, doc(cfg(feature = "smol")))]
pub mod smol;

/// Concrete runtime implementations based on [`wasm-bindgen-futures`](::wasm_bindgen_futures).
#[cfg(feature = "wasm")]
#[cfg_attr(docsrs, doc(cfg(feature = "wasm")))]
pub mod wasm;

/// Time related traits concrete implementations for runtime based on [`async-io`](::async_io), e.g. [`async-std`](::async_std), [`smol`](::smol).
#[cfg(feature = "async-io")]
#[cfg_attr(docsrs, doc(cfg(feature = "async-io")))]
pub mod async_io;

mod spawner;
pub use spawner::*;

/// Runtime trait
pub trait RuntimeLite: Sized + Unpin + Copy + Send + Sync + 'static {
  /// The spawner type for this runtime
  type Spawner: AsyncSpawner;
  /// The local spawner type for this runtime
  type LocalSpawner: AsyncLocalSpawner;
  /// The blocking spawner type for this runtime
  type BlockingSpawner: AsyncBlockingSpawner;

  /// The after spawner type for this runtime
  #[cfg(feature = "time")]
  #[cfg_attr(docsrs, doc(cfg(feature = "time")))]
  type AfterSpawner: AsyncAfterSpawner;

  /// The local after spawner type for this runtime
  #[cfg(feature = "time")]
  #[cfg_attr(docsrs, doc(cfg(feature = "time")))]
  type LocalAfterSpawner: AsyncLocalAfterSpawner;

  /// The interval type for this runtime
  #[cfg(feature = "time")]
  #[cfg_attr(docsrs, doc(cfg(feature = "time")))]
  type Interval: time::AsyncInterval;

  /// The local interval type for this runtime
  #[cfg(feature = "time")]
  #[cfg_attr(docsrs, doc(cfg(feature = "time")))]
  type LocalInterval: time::AsyncLocalInterval;

  /// The sleep type for this runtime
  #[cfg(feature = "time")]
  #[cfg_attr(docsrs, doc(cfg(feature = "time")))]
  type Sleep: time::AsyncSleep;

  /// The local sleep type for this runtime
  #[cfg(feature = "time")]
  #[cfg_attr(docsrs, doc(cfg(feature = "time")))]
  type LocalSleep: time::AsyncLocalSleep;

  /// The delay type for this runtime
  #[cfg(feature = "time")]
  #[cfg_attr(docsrs, doc(cfg(feature = "time")))]
  type Delay<F>: time::AsyncDelay<F>
  where
    F: Future + Send;

  /// The local delay type for this runtime
  #[cfg(feature = "time")]
  #[cfg_attr(docsrs, doc(cfg(feature = "time")))]
  type LocalDelay<F>: time::AsyncLocalDelay<F>
  where
    F: Future;

  /// The timeout type for this runtime
  #[cfg(feature = "time")]
  #[cfg_attr(docsrs, doc(cfg(feature = "time")))]
  type Timeout<F>: time::AsyncTimeout<F>
  where
    F: Future + Send;

  /// The local timeout type for this runtime
  #[cfg(feature = "time")]
  #[cfg_attr(docsrs, doc(cfg(feature = "time")))]
  type LocalTimeout<F>: time::AsyncLocalTimeout<F>
  where
    F: Future;

  /// Create a new instance of the runtime
  fn new() -> Self;

  /// Spawn a future onto the runtime
  fn spawn<F>(future: F) -> <Self::Spawner as AsyncSpawner>::JoinHandle<F::Output>
  where
    F::Output: Send + 'static,
    F: Future + Send + 'static,
  {
    <Self::Spawner as AsyncSpawner>::spawn(future)
  }

  /// Spawn a future onto the runtime and detach it
  fn spawn_detach<F>(future: F)
  where
    F::Output: Send + 'static,
    F: Future + Send + 'static,
  {
    <Self::Spawner as AsyncSpawner>::spawn_detach(future);
  }

  /// Spawn a future onto the local runtime
  fn spawn_local<F>(future: F) -> <Self::LocalSpawner as AsyncLocalSpawner>::JoinHandle<F::Output>
  where
    F: Future + 'static,
    F::Output: 'static,
  {
    <Self::LocalSpawner as AsyncLocalSpawner>::spawn_local(future)
  }

  /// Spawn a future onto the local runtime and detach it
  fn spawn_local_detach<F>(future: F)
  where
    F: Future + 'static,
    F::Output: 'static,
  {
    <Self::LocalSpawner as AsyncLocalSpawner>::spawn_local_detach(future)
  }

  /// Spawn a blocking function onto the runtime
  fn spawn_blocking<F, R>(f: F) -> <Self::BlockingSpawner as AsyncBlockingSpawner>::JoinHandle<R>
  where
    F: FnOnce() -> R + Send + 'static,
    R: Send + 'static,
  {
    <Self::BlockingSpawner as AsyncBlockingSpawner>::spawn_blocking(f)
  }

  /// Spawn a blocking function onto the runtime and detach it
  fn spawn_blocking_detach<F, R>(f: F)
  where
    F: FnOnce() -> R + Send + 'static,
    R: Send + 'static,
  {
    <Self::BlockingSpawner as AsyncBlockingSpawner>::spawn_blocking_detach(f);
  }

  /// Spawn a future onto the runtime and run the given future after the given duration
  #[cfg(feature = "time")]
  #[cfg_attr(docsrs, doc(cfg(feature = "time")))]
  fn spawn_after<F>(
    duration: core::time::Duration,
    future: F,
  ) -> <Self::AfterSpawner as AsyncAfterSpawner>::JoinHandle<F::Output>
  where
    F::Output: Send + 'static,
    F: Future + Send + 'static,
  {
    <Self::AfterSpawner as AsyncAfterSpawner>::spawn_after(duration, future)
  }

  /// Spawn a future onto the runtime and run the given future after the given instant.
  #[cfg(feature = "time")]
  #[cfg_attr(docsrs, doc(cfg(feature = "time")))]
  fn spawn_after_at<F>(
    at: std::time::Instant,
    future: F,
  ) -> <Self::AfterSpawner as AsyncAfterSpawner>::JoinHandle<F::Output>
  where
    F::Output: Send + 'static,
    F: Future + Send + 'static,
  {
    <Self::AfterSpawner as AsyncAfterSpawner>::spawn_after_at(at, future)
  }

  /// Like [`spawn_after`](RuntimeLite::spawn_after), but does not require the `future` to be `Send`.
  ///
  /// Spawn a future onto the runtime and run the given future after the given duration
  #[cfg(feature = "time")]
  #[cfg_attr(docsrs, doc(cfg(feature = "time")))]
  fn spawn_local_after<F>(
    duration: core::time::Duration,
    future: F,
  ) -> <Self::LocalAfterSpawner as AsyncLocalAfterSpawner>::JoinHandle<F::Output>
  where
    F::Output: Send + 'static,
    F: Future + Send + 'static,
  {
    <Self::LocalAfterSpawner as AsyncLocalAfterSpawner>::spawn_local_after(duration, future)
  }

  /// Like [`spawn_after_at`](RuntimeLite::spawn_after_at), but does not require the `future` to be `Send`.
  ///
  /// Spawn a future onto the runtime and run the given future after the given instant.
  #[cfg(feature = "time")]
  #[cfg_attr(docsrs, doc(cfg(feature = "time")))]
  fn spawn_local_after_at<F>(
    at: std::time::Instant,
    future: F,
  ) -> <Self::LocalAfterSpawner as AsyncLocalAfterSpawner>::JoinHandle<F::Output>
  where
    F::Output: Send + 'static,
    F: Future + Send + 'static,
  {
    <Self::LocalAfterSpawner as AsyncLocalAfterSpawner>::spawn_local_after_at(at, future)
  }

  /// Block the current thread on the given future
  fn block_on<F: Future>(f: F) -> F::Output;

  /// Yield the current task
  fn yield_now() -> impl Future<Output = ()> + Send;

  /// Create a new interval that starts at the current time and
  /// yields every `period` duration
  #[cfg(feature = "time")]
  #[cfg_attr(docsrs, doc(cfg(feature = "time")))]
  fn interval(interval: Duration) -> Self::Interval;

  /// Create a new interval that starts at the given instant and
  /// yields every `period` duration
  #[cfg(feature = "time")]
  #[cfg_attr(docsrs, doc(cfg(feature = "time")))]
  fn interval_at(start: Instant, period: Duration) -> Self::Interval;

  /// Create a new interval that starts at the current time and
  /// yields every `period` duration
  #[cfg(feature = "time")]
  #[cfg_attr(docsrs, doc(cfg(feature = "time")))]
  fn interval_local(interval: Duration) -> Self::LocalInterval;

  /// Create a new interval that starts at the given instant and
  /// yields every `period` duration
  #[cfg(feature = "time")]
  #[cfg_attr(docsrs, doc(cfg(feature = "time")))]
  fn interval_local_at(start: Instant, period: Duration) -> Self::LocalInterval;

  /// Create a new sleep future that completes after the given duration
  /// has elapsed
  #[cfg(feature = "time")]
  #[cfg_attr(docsrs, doc(cfg(feature = "time")))]
  fn sleep(duration: Duration) -> Self::Sleep;

  /// Create a new sleep future that completes at the given instant
  /// has elapsed
  #[cfg(feature = "time")]
  #[cfg_attr(docsrs, doc(cfg(feature = "time")))]
  fn sleep_until(instant: Instant) -> Self::Sleep;

  /// Create a new sleep future that completes after the given duration
  /// has elapsed
  #[cfg(feature = "time")]
  #[cfg_attr(docsrs, doc(cfg(feature = "time")))]
  fn sleep_local(duration: Duration) -> Self::LocalSleep;

  /// Create a new sleep future that completes at the given instant
  /// has elapsed
  #[cfg(feature = "time")]
  #[cfg_attr(docsrs, doc(cfg(feature = "time")))]
  fn sleep_local_until(instant: Instant) -> Self::LocalSleep;

  /// Create a new delay future that runs the `fut` after the given duration
  /// has elapsed. The `Future` will never be polled until the duration has
  /// elapsed.
  ///
  /// The behavior of this function may different in different runtime implementations.
  #[cfg(feature = "time")]
  #[cfg_attr(docsrs, doc(cfg(feature = "time")))]
  fn delay<F>(duration: Duration, fut: F) -> Self::Delay<F>
  where
    F: Future + Send;

  /// Like [`delay`](Runtime::delay), but does not require the `fut` to be `Send`.
  /// Create a new delay future that runs the `fut` after the given duration
  /// has elapsed. The `Future` will never be polled until the duration has
  /// elapsed.
  ///
  /// The behavior of this function may different in different runtime implementations.
  #[cfg(feature = "time")]
  #[cfg_attr(docsrs, doc(cfg(feature = "time")))]
  fn delay_local<F>(duration: Duration, fut: F) -> Self::LocalDelay<F>
  where
    F: Future;

  /// Create a new timeout future that runs the `future` after the given deadline.
  /// The `Future` will never be polled until the deadline has reached.
  ///
  /// The behavior of this function may different in different runtime implementations.
  #[cfg(feature = "time")]
  #[cfg_attr(docsrs, doc(cfg(feature = "time")))]
  fn delay_at<F>(deadline: Instant, fut: F) -> Self::Delay<F>
  where
    F: Future + Send;

  /// Like [`delay_at`](Runtime::delay_at), but does not require the `fut` to be `Send`.
  /// Create a new timeout future that runs the `future` after the given deadline
  /// The `Future` will never be polled until the deadline has reached.
  ///
  /// The behavior of this function may different in different runtime implementations.
  #[cfg(feature = "time")]
  #[cfg_attr(docsrs, doc(cfg(feature = "time")))]
  fn delay_local_at<F>(deadline: Instant, fut: F) -> Self::LocalDelay<F>
  where
    F: Future;

  /// Requires a `Future` to complete before the specified duration has elapsed.
  ///
  /// The behavior of this function may different in different runtime implementations.
  #[cfg(feature = "time")]
  #[cfg_attr(docsrs, doc(cfg(feature = "time")))]
  fn timeout<F>(duration: Duration, future: F) -> Self::Timeout<F>
  where
    F: Future + Send,
  {
    <Self::Timeout<F> as time::AsyncTimeout<F>>::timeout(duration, future)
  }

  /// Requires a `Future` to complete before the specified instant in time.
  ///
  /// The behavior of this function may different in different runtime implementations.
  #[cfg(feature = "time")]
  #[cfg_attr(docsrs, doc(cfg(feature = "time")))]
  fn timeout_at<F>(deadline: Instant, future: F) -> Self::Timeout<F>
  where
    F: Future + Send,
  {
    <Self::Timeout<F> as time::AsyncTimeout<F>>::timeout_at(deadline, future)
  }

  /// Like [`timeout`](Runtime::timeout), but does not requrie the `future` to be `Send`.
  /// Requires a `Future` to complete before the specified duration has elapsed.
  ///
  /// The behavior of this function may different in different runtime implementations.
  #[cfg(feature = "time")]
  #[cfg_attr(docsrs, doc(cfg(feature = "time")))]
  fn timeout_local<F>(duration: Duration, future: F) -> Self::LocalTimeout<F>
  where
    F: Future,
  {
    <Self::LocalTimeout<F> as time::AsyncLocalTimeout<F>>::timeout_local(duration, future)
  }

  /// Like [`timeout_at`](Runtime::timeout_at), but does not requrie the `future` to be `Send`.
  /// Requires a `Future` to complete before the specified duration has elapsed.
  ///
  /// The behavior of this function may different in different runtime implementations.
  #[cfg(feature = "time")]
  #[cfg_attr(docsrs, doc(cfg(feature = "time")))]
  fn timeout_local_at<F>(deadline: Instant, future: F) -> Self::LocalTimeout<F>
  where
    F: Future,
  {
    <Self::LocalTimeout<F> as time::AsyncLocalTimeout<F>>::timeout_local_at(deadline, future)
  }
}

/// Unit test for the [`RuntimeLite`]
#[cfg(any(test, feature = "test"))]
#[cfg_attr(docsrs, doc(cfg(any(test, feature = "test"))))]
pub mod tests {
  use core::sync::atomic::{AtomicUsize, Ordering};
  use std::sync::Arc;

  use super::*;

  /// Unit test for the [`RuntimeLite::spawn_after`] function
  pub async fn spawn_after_unittest<R: RuntimeLite>() {
    let ctr = Arc::new(AtomicUsize::new(1));
    let ctr1 = ctr.clone();
    let handle = R::spawn_after(Duration::from_secs(1), async move {
      ctr1.fetch_add(1, Ordering::SeqCst);
    });

    R::sleep(Duration::from_millis(500)).await;
    assert_eq!(ctr.load(Ordering::SeqCst), 1);

    handle.await.unwrap();
    assert_eq!(ctr.load(Ordering::SeqCst), 2);
  }

  /// Unit test for the [`RuntimeLite::spawn_after`] function
  ///
  /// The task will be canceled before it completes
  pub async fn spawn_after_cancel_unittest<R: RuntimeLite>() {
    let ctr = Arc::new(AtomicUsize::new(1));
    let ctr1 = ctr.clone();
    let handle = R::spawn_after(Duration::from_secs(1), async move {
      ctr1.fetch_add(1, Ordering::SeqCst);
    });

    R::sleep(Duration::from_millis(500)).await;
    assert_eq!(ctr.load(Ordering::SeqCst), 1);

    let o = handle.cancel().await;
    assert!(o.is_none());
    assert_eq!(ctr.load(Ordering::SeqCst), 1);
  }

  /// Unit test for the [`RuntimeLite::spawn_after`] function
  ///
  /// The [`AfterHandle`] will be dropped immediately after it is created
  pub async fn spawn_after_drop_unittest<R: RuntimeLite>() {
    let ctr = Arc::new(AtomicUsize::new(1));
    let ctr1 = ctr.clone();
    drop(R::spawn_after(Duration::from_secs(1), async move {
      ctr1.fetch_add(1, Ordering::SeqCst);
    }));

    R::sleep(Duration::from_millis(500)).await;
    assert_eq!(ctr.load(Ordering::SeqCst), 1);

    R::sleep(Duration::from_millis(600)).await;
    assert_eq!(ctr.load(Ordering::SeqCst), 2);
  }
}