1use std::sync::RwLock;
31use std::sync::atomic::{AtomicBool, Ordering};
32use std::time::{Duration, Instant, SystemTime, UNIX_EPOCH};
33
34const MAX_TIMESTAMP: f64 = 253_402_300_800.0;
37
38const MAX_ADVANCE: Duration = Duration::from_secs(100 * 366 * 24 * 60 * 60);
41
42#[derive(Debug, Clone, Copy)]
44enum Wall {
45 Frozen(SystemTime),
49 Shifted(Duration),
51}
52
53#[derive(Debug, Clone, Copy)]
54struct Override {
55 wall: Wall,
56 elapsed: Duration,
59}
60
61struct Clock {
64 active: AtomicBool,
67 touched: AtomicBool,
70 state: RwLock<Option<Override>>,
71}
72
73impl Clock {
74 const fn new() -> Self {
75 Self {
76 active: AtomicBool::new(false),
77 touched: AtomicBool::new(false),
78 state: RwLock::new(None),
79 }
80 }
81
82 fn current(&self) -> Option<Override> {
83 if !self.active.load(Ordering::Relaxed) {
84 return None;
85 }
86 self.state.read().ok().and_then(|state| *state)
89 }
90
91 fn system(&self) -> SystemTime {
92 let real = SystemTime::now();
93 match self.current().map(|o| o.wall) {
94 None => real,
95 Some(Wall::Frozen(at)) => at,
96 Some(Wall::Shifted(by)) => real.checked_add(by).unwrap_or(real),
97 }
98 }
99
100 fn instant(&self) -> Instant {
101 let real = Instant::now();
102 match self.current() {
103 None => real,
104 Some(o) => real.checked_add(o.elapsed).unwrap_or(real),
105 }
106 }
107
108 fn set(&self, ts: f64) -> Result<(), String> {
109 if !ts.is_finite() || !(0.0..MAX_TIMESTAMP).contains(&ts) {
110 return Err(format!(
111 "clock.set({ts}): the timestamp must be unix seconds between 0 and year 9999"
112 ));
113 }
114 let at = Duration::try_from_secs_f64(ts)
115 .map(|since| UNIX_EPOCH + since)
116 .map_err(|err| format!("clock.set({ts}): {err}"))?;
117 self.update(|current| Override {
118 wall: Wall::Frozen(at),
119 elapsed: current.map_or(Duration::ZERO, |o| o.elapsed),
120 })
121 }
122
123 fn advance(&self, secs: f64) -> Result<(), String> {
124 let by = Duration::try_from_secs_f64(secs)
125 .ok()
126 .filter(|_| secs.is_finite())
127 .ok_or_else(|| {
128 format!("clock.advance({secs}): the step must be a non-negative number of seconds")
129 })?;
130 let too_far = || {
131 format!(
132 "clock.advance({secs}): the clock may move at most {} days forward in total",
133 MAX_ADVANCE.as_secs() / 86_400
134 )
135 };
136 let current = self.current();
137 let elapsed = current
138 .map_or(Duration::ZERO, |o| o.elapsed)
139 .checked_add(by)
140 .filter(|total| *total <= MAX_ADVANCE)
141 .ok_or_else(too_far)?;
142 let wall = match current.map(|o| o.wall) {
143 None => Wall::Shifted(by),
144 Some(Wall::Shifted(shift)) => Wall::Shifted(
145 shift
146 .checked_add(by)
147 .filter(|total| *total <= MAX_ADVANCE)
148 .ok_or_else(too_far)?,
149 ),
150 Some(Wall::Frozen(at)) => {
151 let moved = at.checked_add(by).ok_or_else(too_far)?;
152 let limit = UNIX_EPOCH + Duration::from_secs(MAX_TIMESTAMP as u64);
153 if moved >= limit {
154 return Err(too_far());
155 }
156 Wall::Frozen(moved)
157 }
158 };
159 self.update(|_| Override { wall, elapsed })
160 }
161
162 fn update(&self, next: impl FnOnce(Option<Override>) -> Override) -> Result<(), String> {
163 let mut state = self
164 .state
165 .write()
166 .map_err(|_| "the clock override lock is poisoned".to_string())?;
167 *state = Some(next(*state));
168 self.active.store(true, Ordering::Relaxed);
169 self.touched.store(true, Ordering::Relaxed);
170 Ok(())
171 }
172
173 fn reset(&self) {
174 self.active.store(false, Ordering::Relaxed);
175 if let Ok(mut state) = self.state.write() {
176 *state = None;
177 }
178 }
179}
180
181static CLOCK: Clock = Clock::new();
182
183pub fn now_system() -> SystemTime {
185 CLOCK.system()
186}
187
188pub fn now_unix() -> i64 {
190 now_system()
191 .duration_since(UNIX_EPOCH)
192 .map_or(0, |d| d.as_secs() as i64)
193}
194
195pub fn now_unix_f64() -> f64 {
197 now_system()
198 .duration_since(UNIX_EPOCH)
199 .map_or(0.0, |d| d.as_secs_f64())
200}
201
202pub fn now_instant() -> Instant {
204 CLOCK.instant()
205}
206
207pub fn set(ts: f64) -> Result<(), String> {
214 CLOCK.set(ts)
215}
216
217pub fn advance(secs: f64) -> Result<(), String> {
224 CLOCK.advance(secs)
225}
226
227pub fn reset() {
229 CLOCK.reset();
230}
231
232pub fn take_touched() -> bool {
237 CLOCK.touched.swap(false, Ordering::Relaxed)
238}
239
240#[cfg(test)]
241mod tests {
242 use super::*;
243
244 fn unix(clock: &Clock) -> f64 {
245 clock
246 .system()
247 .duration_since(UNIX_EPOCH)
248 .expect("after the epoch")
249 .as_secs_f64()
250 }
251
252 #[test]
253 fn without_an_override_the_real_clock_answers() {
254 let clock = Clock::new();
255 let before = SystemTime::now();
256 let read = clock.system();
257 assert!(read >= before && read <= SystemTime::now());
258 let before = Instant::now();
259 let read = clock.instant();
260 assert!(read >= before && read <= Instant::now());
261 }
262
263 #[test]
264 fn set_freezes_the_wall_clock_and_leaves_elapsed_time_alone() {
265 let clock = Clock::new();
266 clock.set(1_735_689_600.0).expect("set");
267 assert_eq!(unix(&clock), 1_735_689_600.0);
268 assert_eq!(unix(&clock), 1_735_689_600.0, "frozen, not flowing");
269 let before = Instant::now();
270 let read = clock.instant();
271 assert!(read >= before && read <= Instant::now() + Duration::from_millis(50));
272 }
273
274 #[test]
275 fn advance_moves_wall_and_elapsed_time_together() {
276 let clock = Clock::new();
277 clock.set(1_000.0).expect("set");
278 clock.advance(3_600.0).expect("advance");
279 assert_eq!(unix(&clock), 4_600.0);
280 let lead = clock.instant().duration_since(Instant::now());
281 assert!(lead > Duration::from_secs(3_599), "elapsed moved: {lead:?}");
282
283 let shifted = Clock::new();
285 let real = SystemTime::now();
286 shifted.advance(86_400.0).expect("advance");
287 let ahead = shifted.system().duration_since(real).expect("ahead");
288 assert!(ahead >= Duration::from_secs(86_400) && ahead < Duration::from_secs(86_460));
289 }
290
291 #[test]
292 fn reset_restores_the_real_clock() {
293 let clock = Clock::new();
294 assert!(!clock.touched.load(Ordering::Relaxed));
295 clock.set(5.0).expect("set");
296 clock.advance(10.0).expect("advance");
297 clock.reset();
298 assert!(
299 clock.touched.swap(false, Ordering::Relaxed),
300 "a reset keeps the record that the clock moved"
301 );
302 let now = SystemTime::now();
303 let read = clock.system();
304 assert!(read.duration_since(now).unwrap_or_default() < Duration::from_secs(1));
305 assert!(clock.instant() <= Instant::now());
306 }
307
308 #[test]
309 fn out_of_range_steps_are_refused_without_moving_the_clock() {
310 let clock = Clock::new();
311 for bad in [f64::NAN, f64::INFINITY, -1.0, 253_402_300_800.0, 1e300] {
312 let err = clock.set(bad).expect_err("bad set");
313 assert!(err.contains("year 9999"), "{bad}: {err}");
314 }
315 for bad in [f64::NAN, f64::INFINITY, -1.0, 1e300] {
316 clock.advance(bad).expect_err("bad advance");
317 }
318 let err = clock
319 .advance(MAX_ADVANCE.as_secs_f64() + 1.0)
320 .expect_err("too far");
321 assert!(err.contains("at most"), "{err}");
322 assert!(clock.current().is_none(), "a refused step installs nothing");
323
324 clock.set(253_402_300_000.0).expect("set");
326 clock.advance(1_000.0).expect_err("past year 9999");
327 assert_eq!(unix(&clock), 253_402_300_000.0);
328 }
329}