| 1 |
use std::{cell::RefCell, time::Duration}; |
| 2 |
|
| 3 |
std::thread_local! { |
| 4 |
static TIME: RefCell<Duration> = const { RefCell::new(Duration::ZERO) }; |
| 5 |
static SYSTEM_TIME: RefCell<Duration> = const { RefCell::new(Duration::ZERO) }; |
| 6 |
} |
| 7 |
|
| 8 |
fn with_time(d: impl Fn(&mut Duration)) { |
| 9 |
TIME.with(|t| d(&mut t.borrow_mut())); |
| 10 |
} |
| 11 |
|
| 12 |
fn get_time() -> Duration { |
| 13 |
TIME.with(|t| *t.borrow()) |
| 14 |
} |
| 15 |
|
| 16 |
fn with_system_time(d: impl Fn(&mut Duration)) { |
| 17 |
SYSTEM_TIME.with(|t| d(&mut t.borrow_mut())); |
| 18 |
} |
| 19 |
|
| 20 |
fn get_system_time() -> Duration { |
| 21 |
SYSTEM_TIME.with(|t| *t.borrow()) |
| 22 |
} |
| 23 |
|
| 24 |
crate::macros::define_mock_clock! { |
| 25 |
true; |
| 26 |
/// This uses thread-local state for the deterministic clock |
| 27 |
} |
| 28 |
|
| 29 |
crate::macros::define_instant! { |
| 30 |
MockClock::time; |
| 31 |
true; |
| 32 |
/// This uses a thread-local cell for its time source |
| 33 |
} |
| 34 |
|
| 35 |
crate::macros::define_system_time! { |
| 36 |
MockClock::system_time; |
| 37 |
true; |
| 38 |
/// This uses a thread-local cell for its time source |
| 39 |
} |
| 40 |
|
| 41 |
crate::macros::define_instant_tests!(); |
| 42 |
|
| 43 |
#[cfg(test)] |
| 44 |
mod tests { |
| 45 |
|
| 46 |
use super::*; |
| 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 |
// this checks that threads get their own time source |
| 56 |
#[test] |
| 57 |
fn thread_locality() { |
| 58 |
MockClock::set_time(Duration::ZERO); |
| 59 |
|
| 60 |
let start = Instant::now(); |
| 61 |
let handles = [ |
| 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 |
std::thread::spawn(move || { |
| 68 |
let start = Instant::now(); |
| 69 |
MockClock::advance(Duration::from_secs(30)); |
| 70 |
assert_eq!(start.elapsed(), Duration::from_secs(30)); |
| 71 |
}), |
| 72 |
]; |
| 73 |
|
| 74 |
MockClock::advance(Duration::from_secs(10)); |
| 75 |
assert_eq!(start.elapsed(), Duration::from_secs(10)); |
| 76 |
|
| 77 |
for handle in handles { |
| 78 |
handle.join().unwrap(); |
| 79 |
} |
| 80 |
} |
| 81 |
} |