Debian Codegraph @

src/macros.rs

raw symbols ◀ ▶
Source reconstructed at patch state 0 of 1 — not the installed (fully patched) source.
1 Debian patch touch this file
1 macro_rules! define_mock_clock {
2 ($thread_local:expr; $(#[$outer:meta])*) => {
3 /// A Mock clock
4 ///
5 $(#[$outer])*
6 #[derive(Copy, Clone)]
7 pub struct MockClock;
8
9 impl std::fmt::Debug for MockClock {
10 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
11 f.debug_struct("MockClock")
12 .field("time", &Self::time())
13 .field("system_time", &Self::system_time())
14 .finish()
15 }
16 }
17
18 impl MockClock {
19 /// Set the internal [`Instant`] clock to this [`Duration`]
20 pub fn set_time(time: Duration) {
21 self::with_time(|t| *t = time);
22 }
23
24 /// Advance the internal [`Instant`] clock by this [`Duration`]
25 pub fn advance(time: Duration) {
26 self::with_time(|t| *t += time);
27 }
28
29 /// Get the current [`Instant`] duration
30 pub fn time() -> Duration {
31 self::get_time()
32 }
33
34 /// Set the internal [`SystemTime`] clock to this [`Duration`]
35 pub fn set_system_time(time: Duration) {
36 self::with_system_time(|t| *t = time);
37 }
38
39 /// Advance the internal [`SystemTime`] clock by this [`Duration`]
40 pub fn advance_system_time(time: Duration) {
41 self::with_system_time(|t| *t += time);
42 }
43
44 /// Get the current [`SystemTime`] duration
45 pub fn system_time() -> Duration {
46 self::get_system_time()
47 }
48
49 /// Is this MockClock thread-local?
50 pub const fn is_thread_local() -> bool {
51 $thread_local
52 }
53 }
54 };
55 }
56
57 macro_rules! define_instant {
58 ($now:expr ; $thread_local:expr ; $(#[$outer:meta])* ) => {
59 /// A simple deterministic [`std::time::Instant`] wrapped around a modifiable [`std::time::Duration`]
60 ///
61 $(#[$outer])*
62 #[derive(Debug, Copy, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
63 pub struct Instant(Duration);
64
65 impl Instant {
66 pub fn now() -> Self {
67 Self($now())
68 }
69
70 pub fn duration_since(&self, earlier: Self) -> Duration {
71 self.checked_duration_since(earlier).unwrap_or_default()
72 }
73
74 pub fn checked_duration_since(&self, earlier: Self) -> Option<Duration> {
75 self.0.checked_sub(earlier.0)
76 }
77
78 pub fn saturating_duration_since(&self, earlier: Self) -> Duration {
79 self.checked_duration_since(earlier).unwrap_or_default()
80 }
81
82 pub fn elapsed(&self) -> Duration {
83 $now() - self.0
84 }
85
86 pub fn checked_add(&self, duration: Duration) -> Option<Self> {
87 self.0.checked_add(duration).map(Self)
88 }
89
90 pub fn checked_sub(&self, duration: Duration) -> Option<Self> {
91 self.0.checked_sub(duration).map(Self)
92 }
93
94 /// Is this Instant thread-local?
95 pub const fn is_thread_local(&self) -> bool {
96 $thread_local
97 }
98 }
99
100 impl std::ops::Add<Duration> for Instant {
101 type Output = Self;
102 fn add(self, rhs: Duration) -> Self::Output {
103 Self(self.0 + rhs)
104 }
105 }
106
107 impl std::ops::AddAssign<Duration> for Instant {
108 fn add_assign(&mut self, rhs: Duration) {
109 self.0 += rhs
110 }
111 }
112
113 impl std::ops::Sub for Instant {
114 type Output = Duration;
115 fn sub(self, rhs: Self) -> Self::Output {
116 self.duration_since(rhs)
117 }
118 }
119
120 impl std::ops::Sub<Duration> for Instant {
121 type Output = Instant;
122 fn sub(self, rhs: Duration) -> Self::Output {
123 self.checked_sub(rhs)
124 .expect("overflow when substracting duration from instant")
125 }
126 }
127
128 impl std::ops::SubAssign<Duration> for Instant {
129 fn sub_assign(&mut self, rhs: Duration) {
130 self.0 -= rhs
131 }
132 }
133 };
134 }
135
136 macro_rules! define_system_time {
137 ($now:expr; $thread_local:expr; $(#[$outer:meta])*) => {
138 /// A simple deterministic [`std::time::SystemTime`] wrapped around a modifiable [`std::time::Duration`]
139 ///
140 /// The source is the [`MockClock`]
141 ///
142 $(#[$outer])*
143 #[derive(Debug, Copy, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
144 pub struct SystemTime(Duration);
145
146 /// A mocked UNIX_EPOCH. This starts at `0` rather than the traditional unix epoch date.
147 pub const UNIX_EPOCH: SystemTime = SystemTime(Duration::ZERO);
148
149 impl SystemTime {
150 pub const UNIX_EPOCH: SystemTime = UNIX_EPOCH;
151
152 pub fn now() -> Self {
153 Self($now())
154 }
155
156 pub fn duration_since(
157 &self,
158 earlier: SystemTime,
159 ) -> Result<Duration, $crate::SystemTimeError> {
160 self.0
161 .checked_sub(earlier.0)
162 .ok_or_else(|| $crate::SystemTimeError(earlier.0 - self.0))
163 }
164
165 pub fn elapsed(&self) -> Result<Duration, $crate::SystemTimeError> {
166 Self::now().duration_since(*self)
167 }
168
169 pub fn checked_add(&self, duration: Duration) -> Option<SystemTime> {
170 self.0.checked_add(duration).map(Self)
171 }
172
173 pub fn checked_sub(&self, duration: Duration) -> Option<SystemTime> {
174 self.0.checked_sub(duration).map(Self)
175 }
176
177 /// Is this SystemTime thread-local?
178 pub const fn is_thread_local(&self) -> bool {
179 $thread_local
180 }
181 }
182
183 impl std::ops::Add<Duration> for SystemTime {
184 type Output = SystemTime;
185
186 fn add(self, rhs: Duration) -> Self::Output {
187 self.checked_add(rhs)
188 .expect("overflow when adding duration to instant")
189 }
190 }
191
192 impl std::ops::AddAssign<Duration> for SystemTime {
193 fn add_assign(&mut self, rhs: Duration) {
194 *self = *self + rhs
195 }
196 }
197
198 impl std::ops::Sub<Duration> for SystemTime {
199 type Output = SystemTime;
200
201 fn sub(self, rhs: Duration) -> Self::Output {
202 self.checked_sub(rhs)
203 .expect("overflow when subtracting duration from instant")
204 }
205 }
206
207 impl std::ops::SubAssign<Duration> for SystemTime {
208 fn sub_assign(&mut self, rhs: Duration) {
209 *self = *self - rhs
210 }
211 }
212
213 impl From<std::time::SystemTime> for SystemTime {
214 fn from(value: std::time::SystemTime) -> Self {
215 Self(
216 value
217 .duration_since(std::time::SystemTime::UNIX_EPOCH)
218 .expect("std::time::SystemTime is before UNIX_EPOCH"),
219 )
220 }
221 }
222
223 impl From<SystemTime> for std::time::SystemTime {
224 fn from(value: SystemTime) -> Self {
225 Self::UNIX_EPOCH + value.0
226 }
227 }
228 };
229 }
230
231 macro_rules! define_instant_tests {
232 () => {
233 #[cfg(test)]
234 mod common {
235 use super::*;
236
237 fn reset_time() {
238 MockClock::set_time(Duration::ZERO)
239 }
240
241 fn reset_system_time() {
242 MockClock::set_system_time(Duration::ZERO)
243 }
244
245 #[test]
246 fn set_system_time() {
247 reset_system_time();
248
249 MockClock::set_system_time(Duration::from_secs(42));
250 assert_eq!(MockClock::system_time(), Duration::from_secs(42));
251
252 reset_system_time();
253 assert_eq!(MockClock::system_time(), Duration::ZERO);
254 }
255
256 #[test]
257 fn advance_system_time() {
258 reset_system_time();
259
260 for i in 0..3 {
261 MockClock::advance_system_time(Duration::from_millis(100));
262 let time = Duration::from_millis(100 * (i + 1));
263 assert_eq!(MockClock::system_time(), time);
264 }
265 }
266
267 #[test]
268 fn system_time() {
269 reset_system_time();
270
271 let now = SystemTime::now();
272 for i in 0..3 {
273 MockClock::advance_system_time(Duration::from_millis(100));
274 assert_eq!(now.elapsed().unwrap(), Duration::from_millis(100 * (i + 1)));
275 }
276 MockClock::advance_system_time(Duration::from_millis(100));
277
278 let next = SystemTime::now();
279 assert_eq!(
280 next.duration_since(now).unwrap(),
281 Duration::from_millis(400)
282 );
283 }
284
285 #[test]
286 fn system_time_methods() {
287 reset_system_time();
288
289 let system_time = SystemTime::now();
290 let interval = Duration::from_millis(42);
291 MockClock::advance_system_time(interval);
292
293 // zero + 1 = 1
294 assert_eq!(
295 system_time.checked_add(Duration::from_millis(1)).unwrap(),
296 SystemTime(Duration::from_millis(1))
297 );
298
299 // now + 1 = diff + 1
300 assert_eq!(
301 SystemTime::now()
302 .checked_add(Duration::from_millis(1))
303 .unwrap(),
304 SystemTime(Duration::from_millis(43))
305 );
306
307 // zero - 1 = None
308 assert!(system_time.checked_sub(Duration::from_millis(1)).is_none());
309
310 // now - 1 = diff -1
311 assert_eq!(
312 SystemTime::now()
313 .checked_sub(Duration::from_millis(1))
314 .unwrap(),
315 SystemTime(Duration::from_millis(41))
316 );
317
318 // now - 1 = diff - 1
319 assert_eq!(
320 SystemTime::now() - Duration::from_millis(1),
321 SystemTime(Duration::from_millis(41))
322 );
323
324 // now - diff + 1 = none
325 assert!(SystemTime::now()
326 .checked_sub(Duration::from_millis(43))
327 .is_none());
328 }
329
330 #[test]
331 fn system_time_sub_millisecond_precision() {
332 reset_system_time();
333
334 let t1 = SystemTime::UNIX_EPOCH;
335 let t2 = SystemTime::UNIX_EPOCH
336 .checked_add(Duration::from_micros(100))
337 .unwrap();
338 assert!(t2 > t1, "{t2:?} > {t1:?}");
339
340 let t3 = t2.checked_sub(Duration::from_nanos(1)).unwrap();
341 assert!(t2 > t3, "{t2:?} > {t3:?}");
342 }
343
344 #[test]
345 fn system_time_from_std_roundtrip() {
346 let std_now = std::time::SystemTime::now();
347 let mock_now: SystemTime = std_now.into();
348 assert!(mock_now.0 > Duration::from_secs(1708041600)); // Friday 16 February 2024 00:00:00 GMT
349 let roundtrip_now: std::time::SystemTime = mock_now.into();
350 assert_eq!(std_now, roundtrip_now)
351 }
352
353 #[test]
354 fn set_time() {
355 reset_time();
356
357 MockClock::set_time(Duration::from_secs(42));
358 assert_eq!(MockClock::time(), Duration::from_secs(42));
359
360 reset_time();
361 assert_eq!(MockClock::time(), Duration::ZERO);
362 }
363
364 #[test]
365 fn advance() {
366 reset_time();
367
368 for i in 0..3 {
369 MockClock::advance(Duration::from_millis(100));
370 let time = Duration::from_millis(100 * (i + 1));
371 assert_eq!(MockClock::time(), time);
372 }
373 }
374
375 #[test]
376 fn instant() {
377 reset_time();
378
379 let now = Instant::now();
380 for i in 0..3 {
381 MockClock::advance(Duration::from_millis(100));
382 assert_eq!(now.elapsed(), Duration::from_millis(100 * (i + 1)));
383 }
384 MockClock::advance(Duration::from_millis(100));
385
386 let next = Instant::now();
387 assert_eq!(next.duration_since(now), Duration::from_millis(400));
388 }
389
390 #[test]
391 fn methods() {
392 reset_time();
393
394 let instant = Instant::now();
395 let interval = Duration::from_millis(42);
396 MockClock::advance(interval);
397
398 // 0 - now = None
399 assert!(instant.checked_duration_since(Instant::now()).is_none());
400
401 // now - 0 = diff
402 assert_eq!(
403 Instant::now().checked_duration_since(instant).unwrap(),
404 interval
405 );
406
407 // 0 since now = 0
408 assert_eq!(
409 instant.saturating_duration_since(Instant::now()),
410 Duration::ZERO
411 );
412
413 // now since 0 = diff
414 assert_eq!(Instant::now().saturating_duration_since(instant), interval);
415
416 // 0 since now = 0 - same behavior as saturating_duration_since
417 assert_eq!(instant.duration_since(Instant::now()), Duration::ZERO);
418
419 // now since 0 = diff
420 assert_eq!(Instant::now().duration_since(instant), interval);
421
422 // zero + 1 = 1
423 assert_eq!(
424 instant.checked_add(Duration::from_millis(1)).unwrap(),
425 Instant(Duration::from_millis(1))
426 );
427
428 // now + 1 = diff + 1
429 assert_eq!(
430 Instant::now()
431 .checked_add(Duration::from_millis(1))
432 .unwrap(),
433 Instant(Duration::from_millis(43))
434 );
435
436 // zero - 1 = None
437 assert!(instant.checked_sub(Duration::from_millis(1)).is_none());
438
439 // now - 1 = diff -1
440 assert_eq!(
441 Instant::now()
442 .checked_sub(Duration::from_millis(1))
443 .unwrap(),
444 Instant(Duration::from_millis(41))
445 );
446
447 // now - 1 = diff - 1
448 assert_eq!(
449 Instant::now() - Duration::from_millis(1),
450 Instant(Duration::from_millis(41))
451 );
452
453 // now - diff + 1 = none
454 assert!(Instant::now()
455 .checked_sub(Duration::from_millis(43))
456 .is_none());
457 }
458
459 #[test]
460 fn instant_sub_millisecond_precision() {
461 reset_time();
462
463 let t1 = Instant::now();
464 let t2 = t1.checked_add(Duration::from_micros(100)).unwrap();
465 assert!(t2 > t1, "{t2:?} > {t1:?}");
466
467 let t3 = t2.checked_add(Duration::from_nanos(1)).unwrap();
468 assert!(t3 > t2, "{t3:?} > {t2:?}");
469
470 let t4 = t3.checked_sub(Duration::from_nanos(1)).unwrap();
471 assert_eq!(t4, t2);
472
473 let t5 = t4.checked_sub(Duration::from_micros(100)).unwrap();
474 assert_eq!(t5, t1);
475 }
476 }
477 };
478 }
479
480 pub(super) use define_instant;
481 pub(super) use define_instant_tests;
482 pub(super) use define_mock_clock;
483 pub(super) use define_system_time;