use crate::{impl_now, impl_sleep};
use ::std::time::{Duration, Instant};
use tokio1::time::sleep;
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub struct SystemTokio1StdClock;
impl_now! {
impl Now for SystemTokio1StdClock {
type Instant = Instant;
fn now(&this)-> Self::Instant {
Instant::now()
}
}
}
pub type SystemTokio1StdTimer = ::tokio1::time::Sleep;
impl_sleep! {
impl Sleep<Duration> for SystemTokio1StdClock {
type Timer = SystemTokio1StdTimer;
fn sleep(&this, duration: Duration) -> Self::Timer {
sleep(duration)
}
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::{ErasedStdClock, Now, NowExt, StdClock, StdNow};
const ONE_YEAR: Duration = Duration::new(365 * 24 * 60 * 60, 0);
#[test]
fn test_now() {
let clock = SystemTokio1StdClock;
use_now(&clock);
use_std_now(&clock);
use_std_clock(&clock);
use_dyn_now(Box::new(clock));
}
fn use_now<TyNow>(clock: &TyNow)
where
TyNow: Now<Instant = Instant>,
{
let one_year_ago = Instant::now() - ONE_YEAR;
let now: Instant = clock.now();
assert!(now > one_year_ago);
use_std_now(clock);
}
fn use_std_now<TyNow>(clock: &TyNow)
where
TyNow: StdNow,
{
let one_year_ago = Instant::now() - ONE_YEAR;
let now: Instant = clock.now_std();
assert!(now > one_year_ago);
}
fn use_dyn_now(clock: Box<dyn ErasedStdClock>) {
let now = clock.now_std();
let elapsed = clock.saturating_duration_since(now);
assert!(elapsed >= Duration::ZERO);
}
fn use_std_clock<TyClock>(clock: &TyClock)
where
TyClock: StdClock,
{
let one_year_ago = Instant::now() - ONE_YEAR;
let now: Instant = clock.now_std();
assert!(now > one_year_ago);
}
}