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
use std::{future::Future, time::Duration};

/// Trait for async runtime functionality needed by `turbulence`.
///
/// This is designed so that it can be implemented on multiple platforms with multiple runtimes,
/// including `wasm32-unknown-unknown`, where `std::time::Instant` is unavailable.
pub trait Runtime: Clone + Send + Sync + Unpin {
    type Instant: Copy + Send + Sync + Unpin;
    type Sleep: Future<Output = ()> + Send;

    /// This is similar to the `futures::task::Spawn` trait, but it is generic in the spawned
    /// future, which is better for backends like tokio.
    fn spawn<F>(&self, future: F)
    where
        F: Future<Output = ()> + Send + 'static;

    /// Return the current instant.
    fn now(&self) -> Self::Instant;
    /// Return the time elapsed since the given instant.
    fn elapsed(&self, instant: Self::Instant) -> Duration;

    /// Similarly to `std::time::Instant::duration_since`, may panic if `later` comes before
    /// `earlier`.
    fn duration_between(&self, earlier: Self::Instant, later: Self::Instant) -> Duration;

    /// Create a future which resolves after the given time has passed.
    fn sleep(&self, duration: Duration) -> Self::Sleep;
}

impl<'a, R: Runtime> Runtime for &'a R {
    type Instant = R::Instant;
    type Sleep = R::Sleep;

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

    fn now(&self) -> Self::Instant {
        (**self).now()
    }

    fn elapsed(&self, instant: Self::Instant) -> Duration {
        (**self).elapsed(instant)
    }

    fn duration_between(&self, earlier: Self::Instant, later: Self::Instant) -> Duration {
        (**self).duration_between(earlier, later)
    }

    fn sleep(&self, duration: Duration) -> Self::Sleep {
        (**self).sleep(duration)
    }
}