Skip to content

Commit b1bcd18

Browse files
author
Eugene Bulkin
committed
Implement add, sub, mul and div methods using checked methods for Duration
1 parent 07b41b5 commit b1bcd18

File tree

1 file changed

+4
-35
lines changed

1 file changed

+4
-35
lines changed

src/libstd/time/duration.rs

Lines changed: 4 additions & 35 deletions
Original file line numberDiff line numberDiff line change
@@ -228,15 +228,7 @@ impl Add for Duration {
228228
type Output = Duration;
229229

230230
fn add(self, rhs: Duration) -> Duration {
231-
let mut secs = self.secs.checked_add(rhs.secs)
232-
.expect("overflow when adding durations");
233-
let mut nanos = self.nanos + rhs.nanos;
234-
if nanos >= NANOS_PER_SEC {
235-
nanos -= NANOS_PER_SEC;
236-
secs = secs.checked_add(1).expect("overflow when adding durations");
237-
}
238-
debug_assert!(nanos < NANOS_PER_SEC);
239-
Duration { secs: secs, nanos: nanos }
231+
self.checked_add(rhs).expect("overflow when adding durations")
240232
}
241233
}
242234

@@ -252,17 +244,7 @@ impl Sub for Duration {
252244
type Output = Duration;
253245

254246
fn sub(self, rhs: Duration) -> Duration {
255-
let mut secs = self.secs.checked_sub(rhs.secs)
256-
.expect("overflow when subtracting durations");
257-
let nanos = if self.nanos >= rhs.nanos {
258-
self.nanos - rhs.nanos
259-
} else {
260-
secs = secs.checked_sub(1)
261-
.expect("overflow when subtracting durations");
262-
self.nanos + NANOS_PER_SEC - rhs.nanos
263-
};
264-
debug_assert!(nanos < NANOS_PER_SEC);
265-
Duration { secs: secs, nanos: nanos }
247+
self.checked_sub(rhs).expect("overflow when subtracting durations")
266248
}
267249
}
268250

@@ -278,15 +260,7 @@ impl Mul<u32> for Duration {
278260
type Output = Duration;
279261

280262
fn mul(self, rhs: u32) -> Duration {
281-
// Multiply nanoseconds as u64, because it cannot overflow that way.
282-
let total_nanos = self.nanos as u64 * rhs as u64;
283-
let extra_secs = total_nanos / (NANOS_PER_SEC as u64);
284-
let nanos = (total_nanos % (NANOS_PER_SEC as u64)) as u32;
285-
let secs = self.secs.checked_mul(rhs as u64)
286-
.and_then(|s| s.checked_add(extra_secs))
287-
.expect("overflow when multiplying duration");
288-
debug_assert!(nanos < NANOS_PER_SEC);
289-
Duration { secs: secs, nanos: nanos }
263+
self.checked_mul(rhs).expect("overflow when multiplying duration by scalar")
290264
}
291265
}
292266

@@ -302,12 +276,7 @@ impl Div<u32> for Duration {
302276
type Output = Duration;
303277

304278
fn div(self, rhs: u32) -> Duration {
305-
let secs = self.secs / (rhs as u64);
306-
let carry = self.secs - secs * (rhs as u64);
307-
let extra_nanos = carry * (NANOS_PER_SEC as u64) / (rhs as u64);
308-
let nanos = self.nanos / rhs + (extra_nanos as u32);
309-
debug_assert!(nanos < NANOS_PER_SEC);
310-
Duration { secs: secs, nanos: nanos }
279+
self.checked_div(rhs).expect("divide by zero error when dividing duration by scalar")
311280
}
312281
}
313282

0 commit comments

Comments
 (0)