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