]> git.lizzy.rs Git - rust.git/commitdiff
libtime: convert `Timespec` binops to by value
authorJorge Aparicio <japaricious@gmail.com>
Mon, 1 Dec 2014 19:54:31 +0000 (14:54 -0500)
committerJorge Aparicio <japaricious@gmail.com>
Sun, 14 Dec 2014 01:15:39 +0000 (20:15 -0500)
src/libtime/lib.rs

index e293c547944d535a204b08f9e439228ee52d502f..4129086e9ec975ae92ea370e3d169562b4a06bba 100644 (file)
@@ -99,6 +99,8 @@ pub fn new(sec: i64, nsec: i32) -> Timespec {
     }
 }
 
+// NOTE(stage0): Remove impl after a snapshot
+#[cfg(stage0)]
 impl Add<Duration, Timespec> for Timespec {
     fn add(&self, other: &Duration) -> Timespec {
         let d_sec = other.num_seconds();
@@ -119,6 +121,29 @@ fn add(&self, other: &Duration) -> Timespec {
     }
 }
 
+#[cfg(not(stage0))]  // NOTE(stage0): Remove cfg after a snapshot
+impl Add<Duration, Timespec> for Timespec {
+    fn add(self, other: Duration) -> Timespec {
+        let d_sec = other.num_seconds();
+        // It is safe to unwrap the nanoseconds, because there cannot be
+        // more than one second left, which fits in i64 and in i32.
+        let d_nsec = (other - Duration::seconds(d_sec))
+                     .num_nanoseconds().unwrap() as i32;
+        let mut sec = self.sec + d_sec;
+        let mut nsec = self.nsec + d_nsec;
+        if nsec >= NSEC_PER_SEC {
+            nsec -= NSEC_PER_SEC;
+            sec += 1;
+        } else if nsec < 0 {
+            nsec += NSEC_PER_SEC;
+            sec -= 1;
+        }
+        Timespec::new(sec, nsec)
+    }
+}
+
+// NOTE(stage0): Remove impl after a snapshot
+#[cfg(stage0)]
 impl Sub<Timespec, Duration> for Timespec {
     fn sub(&self, other: &Timespec) -> Duration {
         let sec = self.sec - other.sec;
@@ -127,6 +152,15 @@ fn sub(&self, other: &Timespec) -> Duration {
     }
 }
 
+#[cfg(not(stage0))]  // NOTE(stage0): Remove cfg after a snapshot
+impl Sub<Timespec, Duration> for Timespec {
+    fn sub(self, other: Timespec) -> Duration {
+        let sec = self.sec - other.sec;
+        let nsec = self.nsec - other.nsec;
+        Duration::seconds(sec) + Duration::nanoseconds(nsec as i64)
+    }
+}
+
 /// Returns the current time as a `timespec` containing the seconds and
 /// nanoseconds since 1970-01-01T00:00:00Z.
 pub fn get_time() -> Timespec {