• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 use crate::time::{Clock, Duration, Instant};
2 
3 use std::convert::TryInto;
4 
5 /// A structure which handles conversion from Instants to u64 timestamps.
6 #[derive(Debug)]
7 pub(crate) struct TimeSource {
8     pub(crate) clock: Clock,
9     start_time: Instant,
10 }
11 
12 impl TimeSource {
new(clock: Clock) -> Self13     pub(crate) fn new(clock: Clock) -> Self {
14         Self {
15             start_time: clock.now(),
16             clock,
17         }
18     }
19 
deadline_to_tick(&self, t: Instant) -> u6420     pub(crate) fn deadline_to_tick(&self, t: Instant) -> u64 {
21         // Round up to the end of a ms
22         self.instant_to_tick(t + Duration::from_nanos(999_999))
23     }
24 
instant_to_tick(&self, t: Instant) -> u6425     pub(crate) fn instant_to_tick(&self, t: Instant) -> u64 {
26         // round up
27         let dur: Duration = t
28             .checked_duration_since(self.start_time)
29             .unwrap_or_else(|| Duration::from_secs(0));
30         let ms = dur.as_millis();
31 
32         ms.try_into().unwrap_or(u64::MAX)
33     }
34 
tick_to_duration(&self, t: u64) -> Duration35     pub(crate) fn tick_to_duration(&self, t: u64) -> Duration {
36         Duration::from_millis(t)
37     }
38 
now(&self) -> u6439     pub(crate) fn now(&self) -> u64 {
40         self.instant_to_tick(self.clock.now())
41     }
42 }
43