xref: /webrtc/interceptor/src/mock/mock_time.rs (revision 5b79f08a)
1 use std::time::{Duration, SystemTime};
2 
3 use util::sync::Mutex;
4 
5 /// MockTime is a helper to replace SystemTime::now() for testing purposes.
6 pub struct MockTime {
7     cur_now: Mutex<SystemTime>,
8 }
9 
10 impl Default for MockTime {
default() -> Self11     fn default() -> Self {
12         MockTime {
13             cur_now: Mutex::new(SystemTime::UNIX_EPOCH),
14         }
15     }
16 }
17 
18 impl MockTime {
19     /// set_now sets the current time.
set_now(&self, now: SystemTime)20     pub fn set_now(&self, now: SystemTime) {
21         let mut cur_now = self.cur_now.lock();
22         *cur_now = now;
23     }
24 
25     /// now returns the current time.
now(&self) -> SystemTime26     pub fn now(&self) -> SystemTime {
27         let cur_now = self.cur_now.lock();
28         *cur_now
29     }
30 
31     /// advance advances duration d
advance(&mut self, d: Duration)32     pub fn advance(&mut self, d: Duration) {
33         let mut cur_now = self.cur_now.lock();
34         *cur_now = cur_now.checked_add(d).unwrap_or(*cur_now);
35     }
36 }
37