#[cfg(not(test))]
pub use std::time::Instant;
#[cfg(test)]
pub use test::Instant;
#[cfg(test)]
mod test {
use core::cell::Cell;
use core::ops::Sub;
use core::time::Duration;
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct Instant(Duration);
impl Instant {
thread_local! {
static ELAPSED: Cell<Duration> = const { Cell::new(Duration::from_secs(0)) };
}
pub fn advance(duration: Duration) {
Self::ELAPSED.with(|elapsed| elapsed.set(elapsed.get() + duration))
}
pub fn now() -> Self {
Self(Self::ELAPSED.with(|elapsed| elapsed.get()))
}
pub fn duration_since(&self, earlier: Self) -> Duration {
self.0 - earlier.0
}
}
impl Sub<Duration> for Instant {
type Output = Self;
fn sub(self, other: Duration) -> Self {
Self(self.0 - other)
}
}
#[test]
fn time_passes_when_advanced() {
let now = Instant::now();
Instant::advance(Duration::from_secs(1));
Instant::advance(Duration::from_secs(1));
let later = Instant::now();
assert_eq!(now.0 + Duration::from_secs(2), later.0);
}
}