Debian Codegraph @

src/global.rs

raw symbols ◀ ▶ SCIP
1 Debian patch touch this file
1 use std::{sync::Mutex, time::Duration};
2
3 static TIME: Mutex<Duration> = Mutex::new(Duration::ZERO);
4 static SYSTEM_TIME: Mutex<Duration> = Mutex::new(Duration::ZERO);
5
6 fn with_time(d: impl Fn(&mut Duration)) {
7 let mut t = TIME.lock().unwrap();
8 d(&mut t);
9 }
10
11 fn get_time() -> Duration {
12 *TIME.lock().unwrap()
13 }
14
15 fn with_system_time(d: impl Fn(&mut Duration)) {
16 let mut t = SYSTEM_TIME.lock().unwrap();
17 d(&mut t);
18 }
19
20 fn get_system_time() -> Duration {
21 *SYSTEM_TIME.lock().unwrap()
22 }
23
24 crate::macros::define_mock_clock! {
25 false;
26 /// This uses a global mutex state for the deterministic clock
27 }
28
29 crate::macros::define_instant! {
30 MockClock::time;
31 false;
32 /// This uses a global mutex for its time source
33 }
34
35 crate::macros::define_system_time! {
36 MockClock::system_time;
37 false;
38 /// This uses a global mutex for its time source
39 }
40
•41 crate::macros::define_instant_tests!(let _guard = tests::TESTLOCK.lock());
42
43 #[cfg(test)]
44 mod tests {
45 use super::*;
•46 pub (super) static TESTLOCK: Mutex<()> = Mutex::new(());
47
48 #[test]
49 fn is_thread_local() {
50 assert!(!MockClock::is_thread_local());
51 assert!(!Instant::now().is_thread_local());
52 assert!(!SystemTime::now().is_thread_local());
53 }
54
55 #[test]
56 fn thread_sharing() {
•57 let _guard = TESTLOCK.lock();
58 MockClock::set_time(Duration::ZERO);
59
60 let start = Instant::now();
61
62 std::thread::spawn(move || {
63 let start = Instant::now();
64 MockClock::advance(Duration::from_secs(3));
65 assert_eq!(start.elapsed(), Duration::from_secs(3));
66 })
67 .join()
68 .unwrap();
69
70 std::thread::spawn(move || {
71 let next = Instant::now();
72 MockClock::advance(Duration::from_secs(30));
73 assert_eq!(next.elapsed(), Duration::from_secs(30));
74 })
75 .join()
76 .unwrap();
77
78 MockClock::advance(Duration::from_secs(10));
79 // using seconds because a mutex can be slow on some operating systems
80 // the creation/locking time may be in microseconds so we'll have something like 43.002 != 43
81 assert_eq!(start.elapsed().as_secs(), 43);
82 }
83 }