| 1 | |
| 2 | |
| 3 | |
| 4 | |
| 5 | |
| 6 | use std::time::{Duration, SystemTime}; |
| 7 | |
| 8 | use crate::application::port::Clock; |
| 9 | |
| 10 | |
| 11 | #[derive(Debug, Clone, Copy, Default)] |
| 12 | pub struct SystemClock; |
| 13 | |
| 14 | impl Clock for SystemClock { |
| 15 | fn now(&self) -> SystemTime { |
| 16 | SystemTime::now() |
| 17 | } |
| 18 | } |
| 19 | |
| 20 | |
| 21 | |
| 22 | |
| 23 | |
| 24 | |
| 25 | |
| 26 | #[derive(Debug, Clone, Copy)] |
| 27 | pub struct FixedClock(SystemTime); |
| 28 | |
| 29 | impl FixedClock { |
| 30 | pub fn new(at: SystemTime) -> Self { |
| 31 | Self(at) |
| 32 | } |
| 33 | |
| 34 | |
| 35 | |
| 36 | pub fn at_epoch_plus(seconds: u64) -> Self { |
| 37 | Self(SystemTime::UNIX_EPOCH + Duration::from_secs(seconds)) |
| 38 | } |
| 39 | } |
| 40 | |
| 41 | impl Clock for FixedClock { |
| 42 | fn now(&self) -> SystemTime { |
| 43 | self.0 |
| 44 | } |
| 45 | } |
| 46 | |
| 47 | #[cfg(test)] |
| 48 | mod tests { |
| 49 | use super::*; |
| 50 | |
| 51 | #[test] |
| 52 | fn a_fixed_clock_does_not_move() { |
| 53 | let clock = FixedClock::at_epoch_plus(1_700_000_000); |
| 54 | assert_eq!(clock.now(), clock.now()); |
| 55 | assert_eq!( |
| 56 | clock.now(), |
| 57 | SystemTime::UNIX_EPOCH + Duration::from_secs(1_700_000_000) |
| 58 | ); |
| 59 | } |
| 60 | |
| 61 | #[test] |
| 62 | fn the_system_clock_moves_forward() { |
| 63 | let before = SystemClock.now(); |
| 64 | assert!(SystemClock.now() >= before); |
| 65 | } |
| 66 | } |