1use std::sync::Mutex;
9use std::sync::atomic::{AtomicBool, Ordering};
10use std::time::{Duration, Instant};
11
12#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, PartialOrd, Ord, Hash)]
14pub enum TimerPrecision {
15 #[default]
18 Normal,
19 High,
21 Exact,
24}
25
26impl crate::prop::PropEnum for TimerPrecision {
27 const NAMES: &'static [&'static str] = &["normal", "high", "exact"];
28 fn from_index(index: usize) -> Option<Self> {
29 [Self::Normal, Self::High, Self::Exact].get(index).copied()
30 }
31 fn index(self) -> usize {
32 self as usize
33 }
34}
35
36pub const SPIN: Duration = Duration::from_micros(1500);
38
39struct Resolution {
40 hook: Option<fn(bool)>,
41 requests: usize,
42}
43
44static RESOLUTION: Mutex<Resolution> = Mutex::new(Resolution { hook: None, requests: 0 });
45
46pub fn set_resolution_hook(hook: fn(bool)) {
48 if let Ok(mut r) = RESOLUTION.lock() {
49 r.hook = Some(hook);
50 if r.requests > 0 {
52 hook(true);
53 }
54 }
55}
56
57pub fn fine_clock(on: bool) {
59 let Ok(mut r) = RESOLUTION.lock() else { return };
60 let before = r.requests;
61 r.requests = if on { before + 1 } else { before.saturating_sub(1) };
62 if let Some(hook) = r.hook
63 && (before == 0) != (r.requests == 0)
64 {
65 hook(r.requests > 0);
66 }
67}
68
69pub fn park_until(deadline: Instant, precision: TimerPrecision, stop: &AtomicBool) -> bool {
73 let margin = if precision == TimerPrecision::Exact { SPIN } else { Duration::ZERO };
74 loop {
75 if stop.load(Ordering::Relaxed) {
76 return false;
77 }
78 let now = Instant::now();
79 if now + margin >= deadline {
80 break;
81 }
82 std::thread::park_timeout(deadline - margin - now);
83 }
84 while Instant::now() < deadline {
85 std::hint::spin_loop();
86 }
87 !stop.load(Ordering::Relaxed)
88}
89
90#[cfg(test)]
91mod tests {
92 use super::*;
93 use std::sync::atomic::AtomicUsize;
94
95 static CALLS: AtomicUsize = AtomicUsize::new(0);
96
97 fn hook(on: bool) {
98 CALLS.fetch_add(if on { 1 } else { 100 }, Ordering::SeqCst);
99 }
100
101 #[test]
102 fn requests_are_counted_and_exact_is_exact() {
103 set_resolution_hook(hook);
104 fine_clock(true);
105 fine_clock(true);
106 fine_clock(false);
107 assert_eq!(CALLS.load(Ordering::SeqCst), 1, "só o primeiro pedido liga");
108 fine_clock(false);
109 assert_eq!(CALLS.load(Ordering::SeqCst), 101, "o último devolve");
110 let deadline = Instant::now() + Duration::from_millis(1);
112 assert!(park_until(deadline, TimerPrecision::Exact, &AtomicBool::new(false)));
113 let late = Instant::now() - deadline;
114 assert!(late < Duration::from_millis(1), "atrasou {late:?}");
115 }
116}