agnostic-lite 0.6.2

`agnostic-lite` is an agnostic abstraction layer for any async runtime.
Documentation
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
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
#![doc = include_str!("../README.md")]
#![cfg_attr(not(feature = "std"), no_std)]
#![forbid(unsafe_code)]
#![deny(warnings, missing_docs)]
#![cfg_attr(docsrs, feature(doc_cfg))]
#![cfg_attr(docsrs, allow(unused_attributes))]

#[cfg(all(feature = "alloc", not(feature = "std")))]
extern crate alloc as std;

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

macro_rules! cfg_time_with_docsrs {
  ($($item:item)*) => {
    $(
      #[cfg(feature = "time")]
      #[cfg_attr(docsrs, doc(cfg(feature = "time")))]
      $item
    )*
  };
}

macro_rules! cfg_time {
  ($($item:item)*) => {
    $(
      #[cfg(feature = "time")]
      $item
    )*
  };
}

use core::future::Future;

cfg_time_with_docsrs!(
  /// Time related traits
  pub mod time;
);

/// Macro to conditionally compile items for `tokio` feature
#[macro_export]
macro_rules! cfg_tokio {
  ($($item:item)*) => {
    $(
      #[cfg(feature = "tokio")]
      #[cfg_attr(docsrs, doc(cfg(feature = "tokio")))]
      $item
    )*
  };
  (@no_doc_cfg $($item:item)*) => {
    $(
      #[cfg(feature = "tokio")]
      $item
    )*
  };
}

/// Macro to conditionally compile items for `smol` feature
#[macro_export]
macro_rules! cfg_smol {
  ($($item:item)*) => {
    $(
      #[cfg(feature = "smol")]
      #[cfg_attr(docsrs, doc(cfg(feature = "smol")))]
      $item
    )*
  };
  (@no_doc_cfg $($item:item)*) => {
    $(
      #[cfg(feature = "smol")]
      $item
    )*
  };
}

/// Macro to conditionally compile items for `unix` system
#[macro_export]
macro_rules! cfg_unix {
  ($($item:item)*) => {
    $(
      #[cfg(feature = "unix")]
      #[cfg_attr(docsrs, doc(cfg(feature = "unix")))]
      $item
    )*
  };
  (@no_doc_cfg $($item:item)*) => {
    $(
      #[cfg(feature = "unix")]
      $item
    )*
  };
}

/// Macro to conditionally compile items for `windows` system
#[macro_export]
macro_rules! cfg_windows {
  ($($item:item)*) => {
    $(
      #[cfg(feature = "windows")]
      #[cfg_attr(docsrs, doc(cfg(feature = "windows")))]
      $item
    )*
  };
  (@no_doc_cfg $($item:item)*) => {
    $(
      #[cfg(feature = "windows")]
      $item
    )*
  };
}

/// Macro to conditionally compile items for `linux` system
#[macro_export]
macro_rules! cfg_linux {
  ($($item:item)*) => {
    $(
      #[cfg(target_os = "linux")]
      #[cfg_attr(docsrs, doc(cfg(target_os = "linux")))]
      $item
    )*
  };
  (@no_doc_cfg $($item:item)*) => {
    $(
      #[cfg(target_os = "linux")]
      $item
    )*
  };
}

#[macro_use]
mod spawner;

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

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

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

/// Concrete runtime implementations based on the [`embassy-executor`] runtime.
///
/// This is the only `no_std` runtime backend. It requires `alloc` (futures are boxed) and a
/// running [`embassy-executor`] executor. Because [`embassy-executor`] allocates task storage
/// statically and spawns through a `Send` spawner, this backend is necessarily a degraded fit for
/// the [`RuntimeLite`] contract:
///
/// - You **must** call [`embassy::init`] once, from within a running executor, to install the
///   global spawner before spawning anything.
/// - The number of concurrently-alive spawned tasks is bounded by [`embassy::TASK_POOL_SIZE`];
///   exceeding it makes the returned handle resolve to an error.
/// - [`block_on`](embassy::block_on) busy-polls (it does not sleep the CPU).
/// - [`spawn_blocking`](RuntimeLite::spawn_blocking) and local spawning
///   ([`spawn_local`](RuntimeLite::spawn_local)) **panic**: the global spawner is `Send`-only, so
///   `!Send` local tasks cannot be spawned through it.
///
/// [`embassy-executor`]: https://docs.rs/embassy-executor
#[cfg(feature = "embassy")]
#[cfg_attr(docsrs, doc(cfg(feature = "embassy")))]
pub mod embassy;

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

pub use spawner::*;

/// Yielder hints the runtime to execution back
pub trait Yielder {
  /// Yields execution back to the runtime.
  fn yield_now() -> impl Future<Output = ()> + Send;

  /// Yields execution back to the runtime.
  fn yield_now_local() -> impl Future<Output = ()>;
}

/// 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;

  cfg_time_with_docsrs!(
    /// The instant type for this runtime
    type Instant: time::Instant;

    /// The after spawner type for this runtime
    type AfterSpawner: AsyncAfterSpawner<Instant = Self::Instant>;

    /// The interval type for this runtime
    type Interval: time::AsyncInterval<Instant = Self::Instant>;

    /// The local interval type for this runtime
    type LocalInterval: time::AsyncLocalInterval<Instant = Self::Instant>;

    /// The sleep type for this runtime
    type Sleep: time::AsyncSleep<Instant = Self::Instant>;

    /// The local sleep type for this runtime
    type LocalSleep: time::AsyncLocalSleep<Instant = Self::Instant>;

    /// The delay type for this runtime
    type Delay<F>: time::AsyncDelay<F, Instant = Self::Instant>
    where
      F: Future + Send;

    /// The local delay type for this runtime
    type LocalDelay<F>: time::AsyncLocalDelay<F, Instant = Self::Instant>
    where
      F: Future;

    /// The timeout type for this runtime
    type Timeout<F>: time::AsyncTimeout<F, Instant = Self::Instant>
    where
      F: Future + Send;

    /// The local timeout type for this runtime
    type LocalTimeout<F>: time::AsyncLocalTimeout<F, Instant = Self::Instant>
    where
      F: Future;
  );

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

  /// Returns the name of the runtime
  ///
  /// See also fully qualified name of the runtime
  fn name() -> &'static str;

  /// Returns the fully qualified name of the runtime
  ///
  /// See also [`name`](RuntimeLite::name) of the runtime
  fn fqname() -> &'static str;

  /// 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);
  }

  /// 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;

  cfg_time_with_docsrs!(
    /// Returns an instant corresponding to "now".
    fn now() -> Self::Instant {
      <Self::Instant as time::Instant>::now()
    }

    /// Spawn a future onto the runtime and run the given future after the given duration
    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.
    fn spawn_after_at<F>(
      at: Self::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)
    }

    /// Create a new interval that starts at the current time and
    /// yields every `period` duration
    fn interval(interval: core::time::Duration) -> Self::Interval;

    /// Create a new interval that starts at the given instant and
    /// yields every `period` duration
    fn interval_at(start: Self::Instant, period: core::time::Duration) -> Self::Interval;

    /// Create a new interval that starts at the current time and
    /// yields every `period` duration
    fn interval_local(interval: core::time::Duration) -> Self::LocalInterval;

    /// Create a new interval that starts at the given instant and
    /// yields every `period` duration
    fn interval_local_at(start: Self::Instant, period: core::time::Duration)
    -> Self::LocalInterval;

    /// Create a new sleep future that completes after the given duration
    /// has elapsed
    fn sleep(duration: core::time::Duration) -> Self::Sleep;

    /// Create a new sleep future that completes at the given instant
    /// has elapsed
    fn sleep_until(instant: Self::Instant) -> Self::Sleep;

    /// Create a new sleep future that completes after the given duration
    /// has elapsed
    fn sleep_local(duration: core::time::Duration) -> Self::LocalSleep;

    /// Create a new sleep future that completes at the given instant
    /// has elapsed
    fn sleep_local_until(instant: Self::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.
    fn delay<F>(duration: core::time::Duration, fut: F) -> Self::Delay<F>
    where
      F: Future + Send;

    /// Like [`delay`](RuntimeLite::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.
    fn delay_local<F>(duration: core::time::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.
    fn delay_at<F>(deadline: Self::Instant, fut: F) -> Self::Delay<F>
    where
      F: Future + Send;

    /// Like [`delay_at`](RuntimeLite::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.
    fn delay_local_at<F>(deadline: Self::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.
    fn timeout<F>(duration: core::time::Duration, future: F) -> Self::Timeout<F>
    where
      F: Future + Send;

    /// 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<F>(deadline: Self::Instant, future: F) -> Self::Timeout<F>
    where
      F: Future + Send;

    /// Like [`timeout`](RuntimeLite::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.
    fn timeout_local<F>(duration: core::time::Duration, future: F) -> Self::LocalTimeout<F>
    where
      F: Future;

    /// Like [`timeout_at`](RuntimeLite::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.
    fn timeout_local_at<F>(deadline: Self::Instant, future: F) -> Self::LocalTimeout<F>
    where
      F: Future;
  );
}

/// Unit test for the [`RuntimeLite`]
///
/// These helpers exercise the time-related runtime methods, so they require the `time` feature.
#[cfg(all(any(test, feature = "test"), feature = "std", feature = "time"))]
#[cfg_attr(docsrs, doc(cfg(all(any(test, feature = "test"), feature = "time"))))]
pub mod tests {
  use core::sync::atomic::{AtomicUsize, Ordering};

  use std::{sync::Arc, time::Duration};

  use super::{AfterHandle, RuntimeLite};

  /// 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);
  }

  /// Unit test for the [`RuntimeLite::spawn_after`] function
  ///
  /// The [`AfterHandle`] will be abort after it is created, and the task will not be executed.
  pub async fn spawn_after_abort_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.abort();
    R::sleep(Duration::from_millis(600)).await;
    assert_eq!(ctr.load(Ordering::SeqCst), 1);
  }

  /// Unit test for the [`RuntimeLite::spawn_after`] function
  ///
  /// The [`AfterHandle`] will be reset to passed than the original duration after it is created, and the task will be executed after the reset duration.
  pub async fn spawn_after_reset_to_pass_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.reset(Duration::from_millis(250));
    R::sleep(Duration::from_millis(10)).await;
    assert_eq!(ctr.load(Ordering::SeqCst), 2);
  }

  /// Unit test for the [`RuntimeLite::spawn_after`] function
  ///
  /// The [`AfterHandle`] will be reset to future than the original duration after it is created, and the task will be executed after the reset duration.
  pub async fn spawn_after_reset_to_future_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.reset(Duration::from_millis(1250)); // now delay 1.25s
    R::sleep(Duration::from_millis(750 + 10)).await; // we already delayed 500ms, so remaining is 750ms
    assert_eq!(ctr.load(Ordering::SeqCst), 2);
  }
}