aboutsummaryrefslogtreecommitdiff
path: root/src/runtime/time/source.rs
diff options
context:
space:
mode:
Diffstat (limited to 'src/runtime/time/source.rs')
-rw-r--r--src/runtime/time/source.rs42
1 files changed, 42 insertions, 0 deletions
diff --git a/src/runtime/time/source.rs b/src/runtime/time/source.rs
new file mode 100644
index 0000000..e6788ed
--- /dev/null
+++ b/src/runtime/time/source.rs
@@ -0,0 +1,42 @@
+use crate::time::{Clock, Duration, Instant};
+
+use std::convert::TryInto;
+
+/// A structure which handles conversion from Instants to u64 timestamps.
+#[derive(Debug)]
+pub(crate) struct TimeSource {
+ pub(crate) clock: Clock,
+ start_time: Instant,
+}
+
+impl TimeSource {
+ pub(crate) fn new(clock: Clock) -> Self {
+ Self {
+ start_time: clock.now(),
+ clock,
+ }
+ }
+
+ pub(crate) fn deadline_to_tick(&self, t: Instant) -> u64 {
+ // Round up to the end of a ms
+ self.instant_to_tick(t + Duration::from_nanos(999_999))
+ }
+
+ pub(crate) fn instant_to_tick(&self, t: Instant) -> u64 {
+ // round up
+ let dur: Duration = t
+ .checked_duration_since(self.start_time)
+ .unwrap_or_else(|| Duration::from_secs(0));
+ let ms = dur.as_millis();
+
+ ms.try_into().unwrap_or(u64::MAX)
+ }
+
+ pub(crate) fn tick_to_duration(&self, t: u64) -> Duration {
+ Duration::from_millis(t)
+ }
+
+ pub(crate) fn now(&self) -> u64 {
+ self.instant_to_tick(self.clock.now())
+ }
+}