use std::cell::Cell;
use std::sync::Arc;
use std::sync::Mutex;
use tokio::sync::broadcast::Sender;
use crate::CacheClock;
pub struct FakeClock {
current_now: Mutex<Cell<i32>>,
sender: Sender<()>,
}
pub type FakeClockDuration = i32;
pub type FakeClockInstant = i32;
impl FakeClock {
pub fn new() -> Arc<Self> {
let (sender, _) = tokio::sync::broadcast::channel(16);
let fake_clock = Self {
current_now: Mutex::new(Default::default()),
sender,
};
Arc::new(fake_clock)
}
pub fn set_time(&self, time_index: FakeClockInstant) {
self.current_now.lock().unwrap().set(time_index);
let _ = self.sender.send(());
}
pub async fn wait_until(&self, time_index: FakeClockInstant) {
let mut receiver = self.sender.subscribe();
while time_index > self.now() {
receiver.recv().await.unwrap();
}
}
pub fn now(&self) -> FakeClockInstant {
self.current_now.lock().unwrap().get()
}
}
impl CacheClock for Arc<FakeClock> {
type Duration = FakeClockDuration;
type Instant = FakeClockInstant;
fn now(&self) -> FakeClockInstant {
self.as_ref().now()
}
}