1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
//! Timeline
//!
//! A [`Timeline`] represents a frame of reference relative to a point in earth time
use crate::units::DurationSeconds;
use std::time::{Duration, SystemTime};

/// Represent a timeline with a specific start point rooted on earth time.
#[derive(Debug, Clone)]
pub struct Timeline(pub(crate) SystemTime);

/// Represent an offset in time units in the timeline
#[derive(Debug, Clone)]
pub struct TimeOffset(pub(crate) Duration);

/// Represent an offset in seconds in the timeline
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
#[cfg_attr(
    any(test, feature = "property-test-api"),
    derive(test_strategy::Arbitrary)
)]
pub struct TimeOffsetSeconds(pub(crate) DurationSeconds);

impl From<SystemTime> for Timeline {
    fn from(s: SystemTime) -> Self {
        Timeline(s)
    }
}

impl From<DurationSeconds> for TimeOffsetSeconds {
    fn from(v: DurationSeconds) -> Self {
        TimeOffsetSeconds(v)
    }
}

impl From<TimeOffsetSeconds> for TimeOffset {
    fn from(v: TimeOffsetSeconds) -> TimeOffset {
        TimeOffset(v.0.into())
    }
}

impl From<TimeOffsetSeconds> for u64 {
    fn from(v: TimeOffsetSeconds) -> Self {
        v.0.into()
    }
}

impl Timeline {
    /// Create a new timeline, which is a time starting point
    pub fn new(start_time: SystemTime) -> Self {
        Timeline(start_time)
    }

    /// Return the duration since the creation of the timeline
    ///
    /// If the time is earlier than the start of this timeline,
    /// then None is returned.
    pub fn differential(&self, t: &SystemTime) -> Option<TimeOffset> {
        match t.duration_since(self.0) {
            Ok(duration) => Some(TimeOffset(duration)),
            Err(_) => None,
        }
    }

    /// Advance a timeline, and create a new timeline starting at
    /// timeline + duration
    pub fn advance(&self, d: Duration) -> Self {
        Timeline(self.0 + d)
    }
}