use crate::AppState;
use anyhow::Result;
use serde::{Deserialize, Serialize};
pub type CurrentTime = u64;
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
pub struct Clock {
current_time: CurrentTime,
}
impl Default for Clock {
fn default() -> Self {
Self { current_time: 0 }
}
}
impl AppState for Clock {
}
impl Clock {
pub fn current_time(&self) -> CurrentTime {
self.current_time
}
pub fn advance_by(&mut self, dt: CurrentTime) -> Result<()> {
if dt == 0 {
return Ok(());
}
self.current_time = self
.current_time
.checked_add(dt)
.ok_or_else(|| anyhow::anyhow!("Clock overflow"))?;
Ok(())
}
pub fn set_to(&mut self, new_time: CurrentTime) -> Result<()> {
if new_time < self.current_time {
anyhow::bail!("Cannot set clock to a time before current time (time regression).");
}
self.current_time = new_time;
Ok(())
}
}