use std::cell::Cell;
thread_local! {
static PINNED: Cell<Option<f64>> = const { Cell::new(None) };
}
pub(crate) fn pin(ms: Option<f64>) {
PINNED.with(|pinned| pinned.set(ms));
}
pub(crate) fn pinned() -> Option<f64> {
PINNED.with(|pinned| pinned.get())
}
pub fn now_ms() -> f64 {
if let Some(ms) = pinned() {
return ms;
}
real_now_ms()
}
pub fn date_now_ms() -> f64 {
if let Some(ms) = pinned() {
return ms;
}
real_date_now_ms()
}
#[cfg(not(target_arch = "wasm32"))]
fn real_now_ms() -> f64 {
use std::sync::OnceLock;
use std::time::Instant;
static ORIGIN: OnceLock<Instant> = OnceLock::new();
ORIGIN.get_or_init(Instant::now).elapsed().as_secs_f64() * 1e3
}
#[cfg(not(target_arch = "wasm32"))]
pub(crate) fn real_date_now_ms() -> f64 {
std::time::SystemTime::now()
.duration_since(std::time::UNIX_EPOCH)
.map(|since| since.as_secs_f64() * 1e3)
.unwrap_or(0.0)
}
#[cfg(target_arch = "wasm32")]
fn real_now_ms() -> f64 {
web_sys::window()
.and_then(|window| window.performance())
.map(|performance| performance.now())
.unwrap_or(0.0)
}
#[cfg(target_arch = "wasm32")]
pub(crate) fn real_date_now_ms() -> f64 {
js_sys::Date::now()
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn pinning_freezes_both_clocks() {
pin(Some(0.0));
assert_eq!(now_ms(), 0.0);
assert_eq!(date_now_ms(), 0.0);
pin(Some(1234.5));
assert_eq!(now_ms(), 1234.5);
assert_eq!(date_now_ms(), 1234.5);
pin(None);
assert!(date_now_ms() > 1_600_000_000_000.0);
assert!(now_ms() >= 0.0);
}
#[test]
fn the_monotonic_clock_does_not_run_backwards() {
pin(None);
let first = now_ms();
let second = now_ms();
assert!(second >= first);
}
}