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
use std::ops::Add;
use std::ops::AddAssign;
use std::ops::Sub;
use std::ops::SubAssign;

use crate::timestamp::Timestamp;

pub trait Int {}
impl Int for f64 {}
impl Int for f32 {}
impl Int for i64 {}
impl Int for i32 {}
impl Int for i16 {}
impl Int for i8 {}
impl Int for isize {}
impl Int for u32 {}
impl Int for u16 {}
impl Int for u8 {}
impl Int for usize {}

impl<T: Into<i64> + Int> From<T> for Timestamp {
  /// Create a new timestamp for the given number of seconds.
  fn from(secs: T) -> Self {
    Timestamp { seconds: secs.into(), nanos: 0 }
  }
}

impl<T: Into<i64> + Int> Add<T> for Timestamp {
  type Output = Self;

  /// Add the provided duration to the timestamp.
  fn add(self, other: T) -> Timestamp {
    Timestamp::new(self.seconds + other.into(), self.nanos)
  }
}

impl<T: Into<i64> + Int> AddAssign<T> for Timestamp {
  /// Add the provided duration to the timestamp, in-place.
  fn add_assign(&mut self, other: T) {
    self.seconds += other.into();
  }
}

impl<T: Into<i64> + Int> Sub<T> for Timestamp {
  type Output = Self;

  /// Subtract the provided duration to the timestamp.
  fn sub(self, other: T) -> Timestamp {
    Timestamp::new(self.seconds - other.into(), self.nanos)
  }
}

impl<T: Into<i64> + Int> SubAssign<T> for Timestamp {
  /// Subtract the provided duration to the timestamp, in-place.
  fn sub_assign(&mut self, other: T) {
    self.seconds -= other.into();
  }
}

#[cfg(test)]
mod tests {
  use super::*;

  #[test]
  fn test_from() {
    let ts: Timestamp = 1335020400.into();
    assert_eq!(ts.seconds, 1335020400);
    assert_eq!(ts.nanos, 0);
  }

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

  #[test]
  fn test_add_assign() {
    let mut ts = Timestamp::new(1335020400, 500_000_000);
    ts += 86400;
    assert_eq!(ts.seconds, 1335020400 + 86400);
    assert_eq!(ts.nanos, 500_000_000);
  }

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

  #[test]
  fn test_sub_assign() {
    let mut ts = Timestamp::new(1335020400, 500_000_000);
    ts -= 86400;
    assert_eq!(ts.seconds, 1335020400 - 86400);
    assert_eq!(ts.nanos, 500_000_000);
  }
}