use std::time::Instant;
pub trait Clock {
fn timestamp_ns(&self) -> i64;
}
pub struct TimePassed {
start: Instant,
}
impl TimePassed {
pub fn new() -> Self {
Self {
start: Instant::now(),
}
}
}
impl Default for TimePassed {
fn default() -> Self {
Self {
start: Instant::now(),
}
}
}
impl Clock for TimePassed {
fn timestamp_ns(&self) -> i64 {
self.start.elapsed().as_nanos() as i64
}
}
#[cfg(test)]
pub mod tests {
use super::{Clock, TimePassed};
#[test]
fn time_passed_smoke_test() {
assert!(TimePassed::default().timestamp_ns() >= 0);
}
}
#[cfg(any(test, feature = "test-support"))]
pub mod test_support {
use std::{cell::RefCell, time::Duration};
use super::*;
#[derive(Default)]
pub struct FakeClock {
timestamp_ns: RefCell<i64>,
}
impl FakeClock {
pub fn new() -> Self {
Self::default()
}
}
impl Clock for FakeClock {
fn timestamp_ns(&self) -> i64 {
*self.timestamp_ns.borrow_mut() += 1;
*self.timestamp_ns.borrow()
}
}
impl FakeClock {
pub fn advance_by(&self, duration: Duration) {
*self.timestamp_ns.borrow_mut() += duration.as_nanos() as i64;
}
}
}