Skip to main content

trading_toolkit/types/
time.rs

1use std::ops::{Add, AddAssign, Sub, SubAssign};
2use std::time::{SystemTime, UNIX_EPOCH};
3
4static SEC_IN_MILLISEC: u128 = 1000u128;
5static MINUTE_IN_MILLISEC: u128 = 60 * SEC_IN_MILLISEC;
6static HOUR_IN_MILLISEC: u128 = 60 * MINUTE_IN_MILLISEC;
7static DAY_IN_MILLISEC: u128 = 24 * HOUR_IN_MILLISEC;
8
9/// Time
10/// it's basically a milliseconds value
11/// it can mean certain time or duration of time
12///
13/// example)
14/// ```
15/// use trading_toolkit::types::time::Time;
16/// use std::time::{SystemTime, UNIX_EPOCH};
17///
18/// let now = Time::now().unwrap();
19/// assert_eq!(
20///     now.inner(),
21///     SystemTime::now().duration_since(UNIX_EPOCH).unwrap().as_millis(),
22/// );
23///
24/// let days = 2;
25/// let days_in_time = Time::from_days(days);
26/// assert_eq!(days_in_time.inner(), (days as u128) * 24 * 60 * 60 * 1000 as u128);
27/// ```
28#[derive(Debug, Eq, Clone, Ord, PartialOrd)]
29pub struct Time(u128);
30
31impl From<u128> for Time {
32    fn from(epoch: u128) -> Self {
33        Self(epoch)
34    }
35}
36
37impl<'a> std::fmt::Display for Time {
38    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
39        write!(f, "{}", self.inner())
40    }
41}
42
43impl Time {
44    /// return passed milliseconds as Time
45    /// from UNIX_EPOCH(1970-01-01T00:00:00.000Z)
46    pub fn now() -> Result<Self, std::time::SystemTimeError> {
47        Ok(Self(
48            SystemTime::now().duration_since(UNIX_EPOCH)?.as_millis(),
49        ))
50    }
51
52    /// return duration of days
53    pub fn from_days(days: usize) -> Self {
54        Self(days as u128 * DAY_IN_MILLISEC)
55    }
56
57    /// return duration of hours
58    pub fn from_hours(hours: usize) -> Self {
59        Self(hours as u128 * HOUR_IN_MILLISEC)
60    }
61
62    /// return duration of minutes
63    pub fn from_minutes(minutes: usize) -> Self {
64        Self(minutes as u128 * MINUTE_IN_MILLISEC)
65    }
66
67    /// return duration of seconds
68    pub fn from_seconds(seconds: usize) -> Self {
69        Self(seconds as u128 * SEC_IN_MILLISEC)
70    }
71
72    /// return inner milliseconds value
73    pub fn inner(&self) -> u128 {
74        self.0
75    }
76}
77
78impl Add for Time {
79    type Output = Self;
80
81    fn add(self, rhs: Self) -> Self {
82        Self(self.0 + rhs.0)
83    }
84}
85
86impl AddAssign for Time {
87    fn add_assign(&mut self, rhs: Self) {
88        self.0 += rhs.0;
89    }
90}
91
92impl Sub for Time {
93    type Output = Self;
94
95    fn sub(self, rhs: Self) -> Self {
96        Self(self.0 - rhs.0)
97    }
98}
99
100impl SubAssign for Time {
101    fn sub_assign(&mut self, rhs: Self) {
102        self.0 -= rhs.0;
103    }
104}
105
106impl PartialEq for Time {
107    fn eq(&self, other: &Self) -> bool {
108        self.0 == other.0
109    }
110}
111
112impl Copy for Time {}