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
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
use std::ops::Add;
use std::ops::Sub;

/// A representation of a timestamp (seconds and nanos since the Unix epoch).
///
/// Timestamps are able to be easily converted into chrono DateTimes.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, PartialOrd, Ord)]
pub struct Timestamp {
  /// The number of seconds since the Unix epoch.
  pub(crate) seconds: i64,

  /// The number of nanoseconds since the Unix epoch.
  pub(crate) nanos: u32,
}

impl Timestamp {
  /// Create a new timestamp from the given number of `seconds` and `nanos`
  /// (nanoseconds).
  ///
  /// The use of the `ts!()` macro in the `unix-ts-macros` crate is advised
  /// in lieu of calling this method directly for most situations.
  ///
  /// Note: For negative timestamps, the `nanos` argument is _always_ a
  /// positive offset. Therefore, the correct way to represent a timestamp
  /// of `-0.25 seconds` is to call `new(-1, 750_000_000)`.
  pub const fn new(mut seconds: i64, mut nanos: u32) -> Timestamp {
    while nanos >= 1_000_000_000 {
      seconds += 1;
      nanos -= 1_000_000_000;
    }
    Timestamp { seconds, nanos }
  }

  /// Create a timestamp from the given number of nanoseconds.
  pub const fn from_nanos(nanos: i128) -> Timestamp {
    let seconds: i64 = (nanos / 1_000_000_000) as i64;
    // .try_into()
    // .expect("Timestamp value out of range.");
    let nanos = if seconds >= 0 {
      (nanos % 1_000_000_000) as u32
    }
    else {
      (1_000_000_000 - (nanos % 1_000_000_000).abs()) as u32
    };
    Timestamp { seconds, nanos }
  }

  /// Create a timestamp from the given number of microseconds.
  pub const fn from_micros(micros: i64) -> Timestamp {
    Timestamp::from_nanos(micros as i128 * 1_000)
  }

  /// Create a timestamp from the given number of milliseconds.
  pub const fn from_millis(millis: i64) -> Timestamp {
    Timestamp::from_nanos(millis as i128 * 1_000_000)
  }

  /// Return the seconds since the Unix epoch.
  /// Sub-second values are discarded.
  ///
  /// # Examples
  ///
  /// ```
  /// use unix_ts::Timestamp;
  ///
  /// let t = Timestamp::from(1335020400);
  /// assert_eq!(t.seconds(), 1335020400);
  /// ```
  pub const fn seconds(&self) -> i64 {
    self.seconds
  }

  /// Return the time since the Unix epoch, as an integer, with the given
  /// precision.
  ///
  /// # Arguments
  ///
  /// - `e` (`u8`) - The precision for the returned integer, as a power of 10.
  ///   (ex. 3 for milliseconds, 6 for microseconds, etc.). Must be a value
  ///   between 0 and 9.
  ///
  /// # Examples
  ///
  /// ```
  /// use unix_ts::Timestamp;
  ///
  /// let t = Timestamp::from(1335020400);
  /// assert_eq!(t.at_precision(3), 1335020400_000);
  /// assert_eq!(t.at_precision(6), 1335020400_000_000);
  /// ```
  pub const fn at_precision(&self, e: u8) -> i128 {
    (self.seconds as i128) * 10i128.pow(e as u32)
      + (self.nanos as i128) / 10i128.pow(9 - (e as u32))
  }

  /// Return the subsecond component at the specified precision
  /// (ex. 3 for milliseconds, 6 for microseconds); max precision is 9.
  ///
  /// # Arguments
  ///
  /// - `e` (`u8`) - The precision for the returned subsecond value, as a power
  ///   of 10 (ex. 3 for milliseconds, 6 for microseconds, etc.). Must be a
  ///   value between 0 and 9.
  ///
  /// # Examples
  ///
  /// ```
  /// use unix_ts::Timestamp;
  ///
  /// let t = Timestamp::new(1335020400, 500_000_000);
  /// assert_eq!(t.subsec(1), 5);
  /// assert_eq!(t.subsec(3), 500);
  /// ```
  pub fn subsec(&self, e: u8) -> u32 {
    self.nanos / 10u32.pow(9 - u32::from(e))
  }
}

impl Add for Timestamp {
  type Output = Self;

  /// Add two timestamps to one another and return the result.
  fn add(self, other: Timestamp) -> Timestamp {
    Timestamp::new(self.seconds + other.seconds, self.nanos + other.nanos)
  }
}

impl Sub for Timestamp {
  type Output = Self;

  /// Subtract the provided timestamp from this one and return the result.
  fn sub(self, other: Timestamp) -> Timestamp {
    if other.nanos > self.nanos {
      return Timestamp::new(
        self.seconds - other.seconds - 1,
        self.nanos + 1_000_000_000 - other.nanos,
      );
    }
    Timestamp::new(self.seconds - other.seconds, self.nanos - other.nanos)
  }
}

#[cfg(test)]
#[allow(clippy::inconsistent_digit_grouping)]
mod tests {
  use super::*;
  use assert2::check;

  #[test]
  fn test_cmp() {
    check!(Timestamp::from(1335020400) < Timestamp::from(1335024000));
    check!(Timestamp::from(1335020400) == Timestamp::from(1335020400));
    check!(
      Timestamp::new(1335020400, 500_000_000)
        < Timestamp::new(1335020400, 750_000_000)
    );
    check!(Timestamp::new(1, 999_999_999) < Timestamp::from(2));
  }

  #[test]
  fn test_from_nanos() {
    check!(
      Timestamp::from_nanos(1335020400_000_000_000i128)
        == Timestamp::new(1335020400, 0)
    );
    check!(
      Timestamp::from_nanos(1335020400_500_000_000i128)
        == Timestamp::new(1335020400, 500_000_000)
    );
    check!(
      Timestamp::from_nanos(-1_750_000_000) == Timestamp::new(-1, 250_000_000)
    );
  }

  #[test]
  fn test_from_micros() {
    check!(
      Timestamp::from_micros(1335020400_000_000i64)
        == Timestamp::new(1335020400, 0)
    );
    check!(
      Timestamp::from_micros(1335020400_500_000i64)
        == Timestamp::new(1335020400, 500_000_000)
    );
    check!(
      Timestamp::from_micros(-1_750_000) == Timestamp::new(-1, 250_000_000)
    );
  }

  #[test]
  fn test_from_millis() {
    check!(
      Timestamp::from_millis(1335020400_000i64)
        == Timestamp::new(1335020400, 0)
    );
    check!(
      Timestamp::from_millis(1335020400_500i64)
        == Timestamp::new(1335020400, 500_000_000)
    );
    check!(Timestamp::from_millis(-1_750) == Timestamp::new(-1, 250_000_000));
  }

  #[test]
  fn test_seconds() {
    assert_eq!(Timestamp::from(1335020400).seconds, 1335020400);
  }

  #[test]
  fn test_at_precision() {
    let ts = Timestamp::new(1335020400, 123456789);
    assert_eq!(ts.at_precision(3), 1335020400123);
    assert_eq!(ts.at_precision(6), 1335020400123456);
    assert_eq!(ts.at_precision(9), 1335020400123456789);
  }

  #[test]
  fn test_subsec() {
    let ts = Timestamp::new(1335020400, 123456789);
    assert_eq!(ts.subsec(3), 123);
    assert_eq!(ts.subsec(6), 123456);
    assert_eq!(ts.subsec(9), 123456789);
  }

  #[test]
  fn test_add() {
    let ts = Timestamp::from(1335020400) + Timestamp::new(86400, 1_000_000);
    assert_eq!(ts.seconds(), 1335020400 + 86400);
    assert_eq!(ts.subsec(3), 1);
  }

  #[test]
  fn test_sub() {
    let ts = Timestamp::from(1335020400) - Timestamp::new(86400, 0);
    assert_eq!(ts.seconds(), 1335020400 - 86400);
    assert_eq!(ts.nanos, 0);
  }

  #[test]
  fn test_sub_nano_overflow() {
    let ts = Timestamp::from(1335020400) - Timestamp::new(0, 500_000_000);
    assert_eq!(ts.seconds(), 1335020399);
    assert_eq!(ts.subsec(1), 5);
  }
}