serialplugin_testing/
clock.rs1use std::collections::BTreeMap;
5use std::sync::{Arc, Condvar, Mutex, MutexGuard};
6use std::time::{Duration, Instant};
7
8pub type Job = Box<dyn FnOnce() + Send>;
10
11pub trait Clock: Send + Sync + std::fmt::Debug {
16 fn now(&self) -> Duration;
18
19 fn at(&self, at: Duration, job: Job);
21}
22
23#[derive(Default)]
25struct Timers {
26 jobs: BTreeMap<(Duration, u64), Job>,
27 seq: u64,
28}
29
30impl Timers {
31 fn add(&mut self, at: Duration, job: Job) {
32 self.seq += 1;
33 self.jobs.insert((at, self.seq), job);
34 }
35
36 fn due(&mut self, now: Duration) -> Option<Job> {
38 let first = *self.jobs.keys().next()?;
39 (first.0 <= now).then(|| self.jobs.remove(&first)).flatten()
40 }
41
42 fn next(&self) -> Option<Duration> {
43 self.jobs.keys().next().map(|k| k.0)
44 }
45}
46
47fn lock<T>(m: &Mutex<T>) -> MutexGuard<'_, T> {
48 m.lock().unwrap_or_else(|e| e.into_inner())
49}
50
51#[derive(Debug, Clone)]
56pub struct SystemClock(Arc<SystemInner>);
57
58struct SystemInner {
59 start: Instant,
60 timers: Mutex<(Timers, bool)>,
61 wake: Condvar,
62}
63
64impl std::fmt::Debug for SystemInner {
65 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
66 f.debug_struct("SystemClock").finish_non_exhaustive()
67 }
68}
69
70impl Default for SystemClock {
71 fn default() -> Self {
72 Self::new()
73 }
74}
75
76impl SystemClock {
77 pub fn new() -> Self {
79 Self(Arc::new(SystemInner {
80 start: Instant::now(),
81 timers: Mutex::new((Timers::default(), false)),
82 wake: Condvar::new(),
83 }))
84 }
85}
86
87impl Clock for SystemClock {
88 fn now(&self) -> Duration {
89 self.0.start.elapsed()
90 }
91
92 fn at(&self, at: Duration, job: Job) {
93 let mut timers = lock(&self.0.timers);
94 timers.0.add(at, job);
95 if !timers.1 {
96 timers.1 = true;
97 let inner = Arc::downgrade(&self.0);
99 std::thread::spawn(move || run_system(inner));
100 }
101 drop(timers);
102 self.0.wake.notify_all();
103 }
104}
105
106fn run_system(inner: std::sync::Weak<SystemInner>) {
107 loop {
108 let Some(clock) = inner.upgrade() else {
109 return;
110 };
111 let mut timers = lock(&clock.timers);
112 let now = clock.start.elapsed();
113 if let Some(job) = timers.0.due(now) {
114 drop(timers);
115 let _ = std::panic::catch_unwind(std::panic::AssertUnwindSafe(job));
118 continue;
119 }
120 let wait = timers
122 .0
123 .next()
124 .map_or(Duration::from_millis(100), |next| next - now)
125 .min(Duration::from_millis(100));
126 let _woken = clock.wake.wait_timeout(timers, wait);
127 }
128}
129
130#[derive(Clone, Default)]
148pub struct ManualClock(Arc<Mutex<(Duration, Timers)>>);
149
150impl std::fmt::Debug for ManualClock {
151 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
152 f.debug_tuple("ManualClock").field(&self.now()).finish()
153 }
154}
155
156impl ManualClock {
157 pub fn new() -> Self {
159 Self::default()
160 }
161
162 pub fn advance(&self, by: Duration) {
168 let target = lock(&self.0).0 + by;
169 loop {
170 let mut state = lock(&self.0);
171 let Some(next) = state.1.next().filter(|next| *next <= target) else {
172 state.0 = state.0.max(target);
174 return;
175 };
176 state.0 = state.0.max(next);
178 let now = state.0;
179 let job = state.1.due(now);
180 drop(state);
181 if let Some(job) = job {
182 job();
183 }
184 }
185 }
186}
187
188impl Clock for ManualClock {
189 fn now(&self) -> Duration {
190 lock(&self.0).0
191 }
192
193 fn at(&self, at: Duration, job: Job) {
194 lock(&self.0).1.add(at, job);
196 }
197}
198
199#[cfg(feature = "tokio")]
203#[derive(Debug, Clone)]
204pub struct TokioClock(Arc<TokioInner>);
205
206#[cfg(feature = "tokio")]
207struct TokioInner {
208 start: tokio::time::Instant,
209 runtime: tokio::runtime::Handle,
210 timers: Mutex<Timers>,
211 running: Mutex<()>,
213}
214
215#[cfg(feature = "tokio")]
216impl std::fmt::Debug for TokioInner {
217 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
218 f.debug_struct("TokioClock").finish_non_exhaustive()
219 }
220}
221
222#[cfg(feature = "tokio")]
223impl TokioClock {
224 #[allow(clippy::new_without_default)]
227 pub fn new() -> Self {
228 Self(Arc::new(TokioInner {
229 start: tokio::time::Instant::now(),
230 runtime: tokio::runtime::Handle::current(),
231 timers: Mutex::new(Timers::default()),
232 running: Mutex::new(()),
233 }))
234 }
235}
236
237#[cfg(feature = "tokio")]
238impl Clock for TokioClock {
239 fn now(&self) -> Duration {
240 let _runtime = self.0.runtime.enter();
243 self.0.start.elapsed()
244 }
245
246 fn at(&self, at: Duration, job: Job) {
247 lock(&self.0.timers).add(at, job);
248 let inner = self.0.clone();
249 self.0.runtime.spawn(async move {
250 tokio::time::sleep_until(inner.start + at).await;
251 let _running = lock(&inner.running);
252 loop {
253 let job = lock(&inner.timers).due(inner.start.elapsed());
254 let Some(job) = job else { break };
255 job();
256 }
257 });
258 }
259}