1#[cfg(not(target_arch = "wasm32"))]
16pub use std::time::Instant;
17use std::{
18 cell::RefCell,
19 sync::{Arc, Mutex},
20 time::{Duration, SystemTime},
21};
22
23#[cfg(target_arch = "wasm32")]
24pub use self::wasm::Instant;
25
26pub fn now() -> Instant {
29 CURRENT.with(|current| match &*current.borrow() {
30 Some(clock) => clock.now(),
31 None => Instant::now(),
32 })
33}
34
35pub fn unix_ms() -> f64 {
38 CURRENT.with(|current| match &*current.borrow() {
39 Some(clock) => clock.unix_ms(),
40 None => system_unix_ms(),
41 })
42}
43
44pub fn manual() -> bool {
47 CURRENT.with(|current| current.borrow().as_ref().is_some_and(Clock::is_manual))
48}
49
50pub fn current() -> Clock {
54 CURRENT.with(|current| current.borrow().clone().unwrap_or_default())
55}
56
57pub const FRAME: Duration = Duration::from_nanos(16_666_667);
60
61thread_local! {
62 static CURRENT: RefCell<Option<Clock>> = const { RefCell::new(None) };
64}
65
66#[derive(Clone, Default)]
69pub struct Clock(Option<Arc<Mutex<Manual>>>);
70
71struct Manual {
73 origin: Instant,
76 elapsed: Duration,
78 unix_origin: f64,
80 alarms: Vec<(Instant, Box<dyn FnOnce() + Send>)>,
82 frames: bool,
84}
85
86impl std::fmt::Debug for Clock {
87 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
88 f.write_str(if self.is_manual() {
89 "Clock::Manual"
90 } else {
91 "Clock::System"
92 })
93 }
94}
95
96impl Clock {
97 pub fn system() -> Clock {
99 Clock(None)
100 }
101
102 pub fn manual(start: SystemTime) -> Clock {
105 Clock(Some(Arc::new(Mutex::new(Manual {
106 origin: Instant::now(),
107 elapsed: Duration::ZERO,
108 unix_origin: epoch_ms(start),
109 alarms: Vec::new(),
110 frames: false,
111 }))))
112 }
113
114 pub fn with_frames(self) -> Clock {
120 if let Some(mut m) = self.manual_state() {
121 m.frames = true;
122 }
123 self
124 }
125
126 pub fn moves_with_frames(&self) -> bool {
129 self.manual_state().is_some_and(|m| m.frames)
130 }
131
132 pub fn is_manual(&self) -> bool {
134 self.0.is_some()
135 }
136
137 fn manual_state(&self) -> Option<std::sync::MutexGuard<'_, Manual>> {
138 self.0
139 .as_ref()
140 .map(|m| m.lock().unwrap_or_else(|e| e.into_inner()))
141 }
142
143 pub fn now(&self) -> Instant {
145 match self.manual_state() {
146 Some(m) => m.origin + m.elapsed,
147 None => Instant::now(),
148 }
149 }
150
151 pub fn unix_ms(&self) -> f64 {
153 match self.manual_state() {
154 Some(m) => m.unix_origin + m.elapsed.as_secs_f64() * 1000.0,
155 None => system_unix_ms(),
156 }
157 }
158
159 pub fn set_system_time(&self, at: SystemTime) {
162 if let Some(mut m) = self.manual_state() {
163 m.unix_origin = epoch_ms(at) - m.elapsed.as_secs_f64() * 1000.0;
164 }
165 }
166
167 pub fn advance_to(&self, at: Instant) {
170 let due = {
171 let Some(mut m) = self.manual_state() else {
172 return;
173 };
174 let elapsed = at.saturating_duration_since(m.origin);
175 m.elapsed = m.elapsed.max(elapsed);
176 let now = m.origin + m.elapsed;
177 let split = m.alarms.partition_point(|(when, _)| *when <= now);
178 m.alarms.drain(..split).collect::<Vec<_>>()
179 };
180 for (_, alarm) in due {
181 alarm();
182 }
183 }
184
185 pub fn at(&self, at: Instant, alarm: impl FnOnce() + Send + 'static) {
189 match self.manual_state() {
190 Some(mut m) => {
191 let index = m.alarms.partition_point(|(when, _)| *when <= at);
192 m.alarms.insert(index, (at, Box::new(alarm)));
193 }
194 None => {
195 #[cfg(not(target_arch = "wasm32"))]
196 std::thread::spawn(move || {
197 std::thread::sleep(at.saturating_duration_since(Instant::now()));
198 alarm();
199 });
200 #[cfg(target_arch = "wasm32")]
202 alarm();
203 }
204 }
205 }
206
207 pub fn next_alarm(&self) -> Option<Instant> {
209 self.manual_state()?.alarms.first().map(|(at, _)| *at)
210 }
211
212 pub fn enter(&self) -> ClockGuard {
215 let previous = CURRENT.with(|current| current.replace(Some(self.clone())));
216 ClockGuard { previous }
217 }
218}
219
220#[must_use = "the clock is the thread's while the guard lives"]
222pub struct ClockGuard {
223 previous: Option<Clock>,
224}
225
226impl Drop for ClockGuard {
227 fn drop(&mut self) {
228 let previous = self.previous.take();
229 CURRENT.with(|current| *current.borrow_mut() = previous);
230 }
231}
232
233fn epoch_ms(at: SystemTime) -> f64 {
235 match at.duration_since(SystemTime::UNIX_EPOCH) {
236 Ok(since) => since.as_secs_f64() * 1000.0,
237 Err(before) => -before.duration().as_secs_f64() * 1000.0,
238 }
239}
240
241#[cfg(not(target_arch = "wasm32"))]
243fn system_unix_ms() -> f64 {
244 std::time::SystemTime::now()
245 .duration_since(std::time::UNIX_EPOCH)
246 .map_or(0.0, |d| d.as_millis() as f64)
247}
248
249#[cfg(target_arch = "wasm32")]
251fn system_unix_ms() -> f64 {
252 #[link(wasm_import_module = "nsh")]
253 unsafe extern "C" {
254 fn date_now_ms() -> f64;
255 }
256 unsafe { date_now_ms() }
258}
259
260#[cfg(target_arch = "wasm32")]
261mod wasm {
262 use std::{
263 ops::{Add, AddAssign, Sub, SubAssign},
264 time::Duration,
265 };
266
267 #[link(wasm_import_module = "nsh")]
268 unsafe extern "C" {
269 fn now_ms() -> f64;
271 }
272
273 #[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
275 pub struct Instant(Duration);
276
277 impl Instant {
278 pub fn now() -> Instant {
280 let ms = unsafe { now_ms() };
282 Instant(Duration::from_secs_f64(ms.max(0.0) / 1000.0))
283 }
284
285 pub fn duration_since(&self, earlier: Instant) -> Duration {
287 self.0.saturating_sub(earlier.0)
288 }
289
290 pub fn saturating_duration_since(&self, earlier: Instant) -> Duration {
292 self.duration_since(earlier)
293 }
294
295 pub fn elapsed(&self) -> Duration {
297 Instant::now().duration_since(*self)
298 }
299
300 pub fn checked_add(&self, duration: Duration) -> Option<Instant> {
302 self.0.checked_add(duration).map(Instant)
303 }
304
305 pub fn checked_sub(&self, duration: Duration) -> Option<Instant> {
307 self.0.checked_sub(duration).map(Instant)
308 }
309 }
310
311 impl Add<Duration> for Instant {
312 type Output = Instant;
313 fn add(self, rhs: Duration) -> Instant {
314 Instant(self.0 + rhs)
315 }
316 }
317
318 impl AddAssign<Duration> for Instant {
319 fn add_assign(&mut self, rhs: Duration) {
320 self.0 += rhs;
321 }
322 }
323
324 impl Sub<Duration> for Instant {
325 type Output = Instant;
326 fn sub(self, rhs: Duration) -> Instant {
327 Instant(self.0.saturating_sub(rhs))
328 }
329 }
330
331 impl SubAssign<Duration> for Instant {
332 fn sub_assign(&mut self, rhs: Duration) {
333 self.0 = self.0.saturating_sub(rhs);
334 }
335 }
336
337 impl Sub<Instant> for Instant {
338 type Output = Duration;
339 fn sub(self, rhs: Instant) -> Duration {
340 self.duration_since(rhs)
341 }
342 }
343}
344
345#[cfg(test)]
346mod tests {
347 use super::*;
348
349 #[test]
350 fn a_manual_clock_moves_only_when_told_and_runs_its_alarms_in_order() {
351 let clock = Clock::manual(SystemTime::UNIX_EPOCH + Duration::from_secs(1));
352 let start = clock.now();
353 std::thread::sleep(Duration::from_millis(5));
354 assert_eq!(clock.now(), start);
355 let rang = Arc::new(Mutex::new(Vec::new()));
356 for (ms, name) in [(30, "b"), (10, "a"), (50, "c")] {
357 let rang = rang.clone();
358 clock.at(start + Duration::from_millis(ms), move || {
359 rang.lock().unwrap().push(name)
360 });
361 }
362 assert_eq!(clock.next_alarm(), Some(start + Duration::from_millis(10)));
363 clock.advance_to(start + Duration::from_millis(30));
364 assert_eq!(*rang.lock().unwrap(), ["a", "b"]);
365 assert_eq!(clock.unix_ms(), 1_030.0);
366 clock.advance_to(start);
368 assert_eq!(clock.now(), start + Duration::from_millis(30));
369 clock.set_system_time(SystemTime::UNIX_EPOCH + Duration::from_secs(5));
370 assert_eq!(
371 (clock.unix_ms(), clock.now()),
372 (5_000.0, start + Duration::from_millis(30))
373 );
374 }
375
376 #[test]
377 fn a_thread_reads_its_engine_s_clock_while_it_is_entered() {
378 assert!(!manual());
379 let clock = Clock::manual(SystemTime::UNIX_EPOCH + Duration::from_millis(42));
380 {
381 let _guard = clock.enter();
382 assert!(manual());
383 assert_eq!((now(), unix_ms()), (clock.now(), 42.0));
384 }
385 assert!(!manual());
386 assert!(unix_ms() > 1.0e12);
387 }
388}