Skip to main content

ctrader_connector/common/
time.rs

1//! Points in time as the wire carries them: milliseconds since the Unix epoch, in UTC.
2//!
3//! ```
4//! use std::time::Duration;
5//!
6//! use ctrader_connector::common::time::Timestamp;
7//!
8//! let start = Timestamp::from_millis(1_700_000_000_000)?;
9//! let end = start.checked_add(Duration::from_secs(60)).unwrap_or(start);
10//! assert_eq!(end.as_millis(), 1_700_000_060_000);
11//! assert!(start < end);
12//! # Ok::<(), ctrader_connector::common::errors::ValueError>(())
13//! ```
14
15use std::fmt;
16use std::time::{Duration, SystemTime, UNIX_EPOCH};
17
18use crate::common::errors::ValueError;
19
20const TIMESTAMP: &str = "timestamp";
21const MILLIS_PER_MINUTE: i64 = 60_000;
22
23/// Moment in UTC with millisecond resolution; never before the Unix epoch.
24#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord)]
25pub struct Timestamp(i64);
26
27impl Timestamp {
28    /// The Unix epoch.
29    pub const EPOCH: Self = Self(0);
30
31    /// Wraps a number of milliseconds since the Unix epoch.
32    ///
33    /// # Errors
34    ///
35    /// Returns [`ValueError::OutOfRange`] when the number is negative.
36    pub const fn from_millis(millis: i64) -> Result<Self, ValueError> {
37        if millis < 0 {
38            Err(ValueError::OutOfRange { kind: TIMESTAMP })
39        } else {
40            Ok(Self(millis))
41        }
42    }
43
44    /// Converts a number of minutes since the Unix epoch, as trendbars carry it.
45    #[must_use]
46    pub fn from_minutes(minutes: u32) -> Self {
47        Self(i64::from(minutes).saturating_mul(MILLIS_PER_MINUTE))
48    }
49
50    /// Returns the current time of the system clock.
51    ///
52    /// A clock set before the Unix epoch yields the epoch.
53    #[must_use]
54    pub fn now() -> Self {
55        Self::try_from(SystemTime::now()).unwrap_or(Self::EPOCH)
56    }
57
58    /// Returns the number of milliseconds since the Unix epoch.
59    #[must_use]
60    pub const fn as_millis(self) -> i64 {
61        self.0
62    }
63
64    /// Returns the moment `duration` later, or `None` when it cannot be represented.
65    #[must_use]
66    pub fn checked_add(self, duration: Duration) -> Option<Self> {
67        let millis = i64::try_from(duration.as_millis()).ok()?;
68        self.0.checked_add(millis).map(Self)
69    }
70
71    /// Returns the moment `duration` earlier, or `None` when it lies before the Unix epoch.
72    #[must_use]
73    pub fn checked_sub(self, duration: Duration) -> Option<Self> {
74        let millis = i64::try_from(duration.as_millis()).ok()?;
75        Self::from_millis(self.0.checked_sub(millis)?).ok()
76    }
77}
78
79impl TryFrom<SystemTime> for Timestamp {
80    type Error = ValueError;
81
82    fn try_from(time: SystemTime) -> Result<Self, Self::Error> {
83        let out_of_range = ValueError::OutOfRange { kind: TIMESTAMP };
84        let elapsed = time
85            .duration_since(UNIX_EPOCH)
86            .map_err(|_| out_of_range.clone())?;
87        i64::try_from(elapsed.as_millis())
88            .map(Self)
89            .map_err(|_| out_of_range)
90    }
91}
92
93impl TryFrom<Timestamp> for SystemTime {
94    type Error = ValueError;
95
96    fn try_from(timestamp: Timestamp) -> Result<Self, Self::Error> {
97        UNIX_EPOCH
98            .checked_add(Duration::from_millis(timestamp.0.unsigned_abs()))
99            .ok_or(ValueError::OutOfRange { kind: TIMESTAMP })
100    }
101}
102
103impl fmt::Display for Timestamp {
104    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
105        self.0.fmt(f)
106    }
107}
108
109/// Span of time between two moments, both included.
110#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
111pub struct TimeRange {
112    from: Timestamp,
113    to: Timestamp,
114}
115
116impl TimeRange {
117    /// Builds the range that starts at `from` and ends at `to`.
118    ///
119    /// # Errors
120    ///
121    /// Returns [`ValueError::InvertedRange`] when `to` lies before `from`.
122    pub const fn new(from: Timestamp, to: Timestamp) -> Result<Self, ValueError> {
123        if to.0 < from.0 {
124            Err(ValueError::InvertedRange {
125                from: from.0,
126                to: to.0,
127            })
128        } else {
129            Ok(Self { from, to })
130        }
131    }
132
133    /// Builds the range of the given length that ends at `to`; it starts at the Unix epoch when
134    /// the length reaches further back.
135    #[must_use]
136    pub fn ending_at(to: Timestamp, length: Duration) -> Self {
137        Self {
138            from: to.checked_sub(length).unwrap_or(Timestamp::EPOCH),
139            to,
140        }
141    }
142
143    /// Returns the first moment of the range.
144    #[must_use]
145    pub const fn from(&self) -> Timestamp {
146        self.from
147    }
148
149    /// Returns the last moment of the range.
150    #[must_use]
151    pub const fn to(&self) -> Timestamp {
152        self.to
153    }
154
155    /// Tells whether the moment lies inside the range.
156    #[must_use]
157    pub const fn contains(&self, moment: Timestamp) -> bool {
158        self.from.0 <= moment.0 && moment.0 <= self.to.0
159    }
160}
161
162#[cfg(test)]
163mod tests {
164    use std::time::{Duration, SystemTime, UNIX_EPOCH};
165
166    use super::{TimeRange, Timestamp};
167    use crate::common::errors::ValueError;
168
169    const OUT_OF_RANGE: ValueError = ValueError::OutOfRange { kind: "timestamp" };
170
171    #[test]
172    fn range_keeps_its_ends_in_order() {
173        let at = |millis| Timestamp::from_millis(millis).expect("timestamp");
174        let range = TimeRange::new(at(10), at(20)).expect("range");
175        assert_eq!((range.from(), range.to()), (at(10), at(20)));
176        assert!(range.contains(at(10)) && range.contains(at(20)));
177        assert!(!range.contains(at(9)) && !range.contains(at(21)));
178        assert!(TimeRange::new(at(10), at(10)).is_ok());
179        let inverted = TimeRange::new(at(20), at(10));
180        assert_eq!(
181            inverted,
182            Err(ValueError::InvertedRange { from: 20, to: 10 })
183        );
184        assert_eq!(
185            inverted.map_err(|error| error.to_string()),
186            Err("range from 20 ends before it starts, at 10".to_owned())
187        );
188        let tail = TimeRange::ending_at(at(5_000), Duration::from_secs(2));
189        assert_eq!((tail.from(), tail.to()), (at(3_000), at(5_000)));
190        assert_eq!(
191            TimeRange::ending_at(at(5_000), Duration::from_secs(9)).from(),
192            Timestamp::EPOCH
193        );
194    }
195
196    #[test]
197    fn milliseconds_round_trip_and_negative_ones_are_rejected() {
198        let timestamp = Timestamp::from_millis(1_700_000_000_123).expect("timestamp");
199        assert_eq!(timestamp.as_millis(), 1_700_000_000_123);
200        assert_eq!(timestamp.to_string(), "1700000000123");
201        assert_eq!(Timestamp::from_millis(0), Ok(Timestamp::EPOCH));
202        assert_eq!(Timestamp::from_millis(-1), Err(OUT_OF_RANGE));
203    }
204
205    #[test]
206    fn minutes_convert_to_milliseconds() {
207        assert_eq!(Timestamp::from_minutes(0), Timestamp::EPOCH);
208        assert_eq!(Timestamp::from_minutes(2).as_millis(), 120_000);
209        assert_eq!(
210            Timestamp::from_minutes(u32::MAX).as_millis(),
211            i64::from(u32::MAX) * 60_000
212        );
213    }
214
215    #[test]
216    fn arithmetic_stays_within_the_representable_range() {
217        let start = Timestamp::from_millis(1_000).expect("timestamp");
218        let later = start.checked_add(Duration::from_millis(500));
219        assert_eq!(later.map(Timestamp::as_millis), Some(1_500));
220        let earlier = start.checked_sub(Duration::from_millis(1_000));
221        assert_eq!(earlier, Some(Timestamp::EPOCH));
222        assert_eq!(start.checked_sub(Duration::from_millis(1_001)), None);
223        assert_eq!(start.checked_add(Duration::MAX), None);
224        assert_eq!(start.checked_sub(Duration::MAX), None);
225        let last = Timestamp::from_millis(i64::MAX).expect("timestamp");
226        assert_eq!(last.checked_add(Duration::from_millis(1)), None);
227        assert!(start < last);
228    }
229
230    #[test]
231    fn system_time_converts_both_ways() {
232        let time = UNIX_EPOCH + Duration::from_millis(42);
233        let timestamp = Timestamp::try_from(time).expect("timestamp");
234        assert_eq!(timestamp.as_millis(), 42);
235        assert_eq!(SystemTime::try_from(timestamp), Ok(time));
236        let last = Timestamp::from_millis(i64::MAX).expect("timestamp");
237        match SystemTime::try_from(last) {
238            Ok(time) => assert_eq!(Timestamp::try_from(time), Ok(last)),
239            Err(error) => assert_eq!(error, OUT_OF_RANGE),
240        }
241        assert_eq!(
242            Timestamp::try_from(UNIX_EPOCH - Duration::from_secs(1)),
243            Err(OUT_OF_RANGE)
244        );
245        assert!(Timestamp::now() > timestamp);
246    }
247}