use async_trait::async_trait;
use std::time::{Duration, Instant};
#[async_trait]
pub trait Clock: Send + Sync {
fn now(&self) -> Instant;
async fn sleep(&self, duration: Duration);
}
#[derive(Debug, Clone, Default)]
pub struct SystemClock;
impl SystemClock {
pub fn new() -> Self {
Self
}
}
#[async_trait]
impl Clock for SystemClock {
fn now(&self) -> Instant {
Instant::now()
}
async fn sleep(&self, duration: Duration) {
tokio::time::sleep(duration).await;
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_system_clock_now() {
let clock = SystemClock::new();
let before = Instant::now();
let clock_now = clock.now();
let after = Instant::now();
assert!(clock_now >= before);
assert!(clock_now <= after);
}
}