use std::sync::Mutex;
use std::time::Duration;
pub trait Clock: Send + Sync + 'static {
fn now(&self) -> f64;
fn elapsed_since(&self, earlier: f64) -> f64 {
(self.now() - earlier).max(0.0)
}
}
#[derive(Debug, Default)]
pub struct ManualClock {
seconds: Mutex<f64>,
}
impl ManualClock {
pub fn new() -> Self {
Self::default()
}
pub fn at(seconds: f64) -> Self {
Self {
seconds: Mutex::new(seconds),
}
}
pub fn set(&self, seconds: f64) {
if let Ok(mut current) = self.seconds.lock() {
*current = seconds;
}
}
pub fn advance(&self, seconds: f64) {
if let Ok(mut current) = self.seconds.lock() {
*current += seconds;
}
}
}
impl Clock for ManualClock {
fn now(&self) -> f64 {
self.seconds.lock().map(|seconds| *seconds).unwrap_or(0.0)
}
}
#[cfg(all(feature = "threads", not(target_arch = "wasm32")))]
#[derive(Debug)]
pub struct SystemClock {
origin: std::time::Instant,
}
#[cfg(all(feature = "threads", not(target_arch = "wasm32")))]
impl Default for SystemClock {
fn default() -> Self {
Self::new()
}
}
#[cfg(all(feature = "threads", not(target_arch = "wasm32")))]
impl SystemClock {
pub fn new() -> Self {
Self {
origin: std::time::Instant::now(),
}
}
}
#[cfg(all(feature = "threads", not(target_arch = "wasm32")))]
impl Clock for SystemClock {
fn now(&self) -> f64 {
self.origin.elapsed().as_secs_f64()
}
}
#[cfg(target_arch = "wasm32")]
#[derive(Debug, Default)]
pub struct PerformanceClock {
seconds: std::sync::Mutex<f64>,
}
#[cfg(target_arch = "wasm32")]
impl PerformanceClock {
pub fn new() -> Self {
Self::default()
}
pub fn tick(&self, delta: f64) {
if let Ok(mut seconds) = self.seconds.lock() {
*seconds += delta.max(0.0);
}
}
pub fn set(&self, seconds: f64) {
if let Ok(mut current) = self.seconds.lock() {
*current = seconds.max(0.0);
}
}
}
#[cfg(target_arch = "wasm32")]
impl Clock for PerformanceClock {
fn now(&self) -> f64 {
self.seconds.lock().map(|seconds| *seconds).unwrap_or(0.0)
}
}
pub fn seconds(duration: Duration) -> f64 {
duration.as_secs_f64()
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn a_manual_clock_moves_without_sleeping() {
let clock = ManualClock::new();
assert_eq!(clock.now(), 0.0);
clock.advance(1.5);
assert_eq!(clock.now(), 1.5);
assert_eq!(clock.elapsed_since(0.5), 1.0);
clock.set(10.0);
assert_eq!(clock.now(), 10.0);
assert_eq!(clock.elapsed_since(12.0), 0.0);
}
#[test]
fn the_system_clock_is_monotonic() {
#[cfg(all(feature = "threads", not(target_arch = "wasm32")))]
{
let clock = SystemClock::new();
let first = clock.now();
let second = clock.now();
assert!(second >= first);
}
}
}