1 // Copyright 2012-2014 The Rust Project Developers. See the COPYRIGHT
2 // file at the top-level directory of this distribution and at
3 // http://rust-lang.org/COPYRIGHT.
4 //
5 // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
6 // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
7 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
8 // option. This file may not be copied, modified, or distributed
9 // except according to those terms.
10
11 //! Temporal quantification
12
13 use std::{fmt, i64};
14 use std::error::Error;
15 use std::ops::{Add, Sub, Mul, Div, Neg};
16 use std::time::Duration as StdDuration;
17
18 /// The number of nanoseconds in a microsecond.
19 const NANOS_PER_MICRO: i32 = 1000;
20 /// The number of nanoseconds in a millisecond.
21 const NANOS_PER_MILLI: i32 = 1000_000;
22 /// The number of nanoseconds in seconds.
23 const NANOS_PER_SEC: i32 = 1_000_000_000;
24 /// The number of microseconds per second.
25 const MICROS_PER_SEC: i64 = 1000_000;
26 /// The number of milliseconds per second.
27 const MILLIS_PER_SEC: i64 = 1000;
28 /// The number of seconds in a minute.
29 const SECS_PER_MINUTE: i64 = 60;
30 /// The number of seconds in an hour.
31 const SECS_PER_HOUR: i64 = 3600;
32 /// The number of (non-leap) seconds in days.
33 const SECS_PER_DAY: i64 = 86400;
34 /// The number of (non-leap) seconds in a week.
35 const SECS_PER_WEEK: i64 = 604800;
36
37 macro_rules! try_opt {
38 ($e:expr) => (match $e { Some(v) => v, None => return None })
39 }
40
41
42 /// ISO 8601 time duration with nanosecond precision.
43 /// This also allows for the negative duration; see individual methods for details.
44 #[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Debug)]
45 pub struct Duration {
46 secs: i64,
47 nanos: i32, // Always 0 <= nanos < NANOS_PER_SEC
48 }
49
50 /// The minimum possible `Duration`: `i64::MIN` milliseconds.
51 pub const MIN: Duration = Duration {
52 secs: i64::MIN / MILLIS_PER_SEC - 1,
53 nanos: NANOS_PER_SEC + (i64::MIN % MILLIS_PER_SEC) as i32 * NANOS_PER_MILLI
54 };
55
56 /// The maximum possible `Duration`: `i64::MAX` milliseconds.
57 pub const MAX: Duration = Duration {
58 secs: i64::MAX / MILLIS_PER_SEC,
59 nanos: (i64::MAX % MILLIS_PER_SEC) as i32 * NANOS_PER_MILLI
60 };
61
62 impl Duration {
63 /// Makes a new `Duration` with given number of weeks.
64 /// Equivalent to `Duration::seconds(weeks * 7 * 24 * 60 * 60)` with overflow checks.
65 /// Panics when the duration is out of bounds.
66 #[inline]
weeks(weeks: i64) -> Duration67 pub fn weeks(weeks: i64) -> Duration {
68 let secs = weeks.checked_mul(SECS_PER_WEEK).expect("Duration::weeks out of bounds");
69 Duration::seconds(secs)
70 }
71
72 /// Makes a new `Duration` with given number of days.
73 /// Equivalent to `Duration::seconds(days * 24 * 60 * 60)` with overflow checks.
74 /// Panics when the duration is out of bounds.
75 #[inline]
days(days: i64) -> Duration76 pub fn days(days: i64) -> Duration {
77 let secs = days.checked_mul(SECS_PER_DAY).expect("Duration::days out of bounds");
78 Duration::seconds(secs)
79 }
80
81 /// Makes a new `Duration` with given number of hours.
82 /// Equivalent to `Duration::seconds(hours * 60 * 60)` with overflow checks.
83 /// Panics when the duration is out of bounds.
84 #[inline]
hours(hours: i64) -> Duration85 pub fn hours(hours: i64) -> Duration {
86 let secs = hours.checked_mul(SECS_PER_HOUR).expect("Duration::hours ouf of bounds");
87 Duration::seconds(secs)
88 }
89
90 /// Makes a new `Duration` with given number of minutes.
91 /// Equivalent to `Duration::seconds(minutes * 60)` with overflow checks.
92 /// Panics when the duration is out of bounds.
93 #[inline]
minutes(minutes: i64) -> Duration94 pub fn minutes(minutes: i64) -> Duration {
95 let secs = minutes.checked_mul(SECS_PER_MINUTE).expect("Duration::minutes out of bounds");
96 Duration::seconds(secs)
97 }
98
99 /// Makes a new `Duration` with given number of seconds.
100 /// Panics when the duration is more than `i64::MAX` milliseconds
101 /// or less than `i64::MIN` milliseconds.
102 #[inline]
seconds(seconds: i64) -> Duration103 pub fn seconds(seconds: i64) -> Duration {
104 let d = Duration { secs: seconds, nanos: 0 };
105 if d < MIN || d > MAX {
106 panic!("Duration::seconds out of bounds");
107 }
108 d
109 }
110
111 /// Makes a new `Duration` with given number of milliseconds.
112 #[inline]
milliseconds(milliseconds: i64) -> Duration113 pub fn milliseconds(milliseconds: i64) -> Duration {
114 let (secs, millis) = div_mod_floor_64(milliseconds, MILLIS_PER_SEC);
115 let nanos = millis as i32 * NANOS_PER_MILLI;
116 Duration { secs: secs, nanos: nanos }
117 }
118
119 /// Makes a new `Duration` with given number of microseconds.
120 #[inline]
microseconds(microseconds: i64) -> Duration121 pub fn microseconds(microseconds: i64) -> Duration {
122 let (secs, micros) = div_mod_floor_64(microseconds, MICROS_PER_SEC);
123 let nanos = micros as i32 * NANOS_PER_MICRO;
124 Duration { secs: secs, nanos: nanos }
125 }
126
127 /// Makes a new `Duration` with given number of nanoseconds.
128 #[inline]
nanoseconds(nanos: i64) -> Duration129 pub fn nanoseconds(nanos: i64) -> Duration {
130 let (secs, nanos) = div_mod_floor_64(nanos, NANOS_PER_SEC as i64);
131 Duration { secs: secs, nanos: nanos as i32 }
132 }
133
134 /// Returns the total number of whole weeks in the duration.
135 #[inline]
num_weeks(&self) -> i64136 pub fn num_weeks(&self) -> i64 {
137 self.num_days() / 7
138 }
139
140 /// Returns the total number of whole days in the duration.
num_days(&self) -> i64141 pub fn num_days(&self) -> i64 {
142 self.num_seconds() / SECS_PER_DAY
143 }
144
145 /// Returns the total number of whole hours in the duration.
146 #[inline]
num_hours(&self) -> i64147 pub fn num_hours(&self) -> i64 {
148 self.num_seconds() / SECS_PER_HOUR
149 }
150
151 /// Returns the total number of whole minutes in the duration.
152 #[inline]
num_minutes(&self) -> i64153 pub fn num_minutes(&self) -> i64 {
154 self.num_seconds() / SECS_PER_MINUTE
155 }
156
157 /// Returns the total number of whole seconds in the duration.
num_seconds(&self) -> i64158 pub fn num_seconds(&self) -> i64 {
159 // If secs is negative, nanos should be subtracted from the duration.
160 if self.secs < 0 && self.nanos > 0 {
161 self.secs + 1
162 } else {
163 self.secs
164 }
165 }
166
167 /// Returns the number of nanoseconds such that
168 /// `nanos_mod_sec() + num_seconds() * NANOS_PER_SEC` is the total number of
169 /// nanoseconds in the duration.
nanos_mod_sec(&self) -> i32170 fn nanos_mod_sec(&self) -> i32 {
171 if self.secs < 0 && self.nanos > 0 {
172 self.nanos - NANOS_PER_SEC
173 } else {
174 self.nanos
175 }
176 }
177
178 /// Returns the total number of whole milliseconds in the duration,
num_milliseconds(&self) -> i64179 pub fn num_milliseconds(&self) -> i64 {
180 // A proper Duration will not overflow, because MIN and MAX are defined
181 // such that the range is exactly i64 milliseconds.
182 let secs_part = self.num_seconds() * MILLIS_PER_SEC;
183 let nanos_part = self.nanos_mod_sec() / NANOS_PER_MILLI;
184 secs_part + nanos_part as i64
185 }
186
187 /// Returns the total number of whole microseconds in the duration,
188 /// or `None` on overflow (exceeding 2^63 microseconds in either direction).
num_microseconds(&self) -> Option<i64>189 pub fn num_microseconds(&self) -> Option<i64> {
190 let secs_part = try_opt!(self.num_seconds().checked_mul(MICROS_PER_SEC));
191 let nanos_part = self.nanos_mod_sec() / NANOS_PER_MICRO;
192 secs_part.checked_add(nanos_part as i64)
193 }
194
195 /// Returns the total number of whole nanoseconds in the duration,
196 /// or `None` on overflow (exceeding 2^63 nanoseconds in either direction).
num_nanoseconds(&self) -> Option<i64>197 pub fn num_nanoseconds(&self) -> Option<i64> {
198 let secs_part = try_opt!(self.num_seconds().checked_mul(NANOS_PER_SEC as i64));
199 let nanos_part = self.nanos_mod_sec();
200 secs_part.checked_add(nanos_part as i64)
201 }
202
203 /// Add two durations, returning `None` if overflow occurred.
checked_add(&self, rhs: &Duration) -> Option<Duration>204 pub fn checked_add(&self, rhs: &Duration) -> Option<Duration> {
205 let mut secs = try_opt!(self.secs.checked_add(rhs.secs));
206 let mut nanos = self.nanos + rhs.nanos;
207 if nanos >= NANOS_PER_SEC {
208 nanos -= NANOS_PER_SEC;
209 secs = try_opt!(secs.checked_add(1));
210 }
211 let d = Duration { secs: secs, nanos: nanos };
212 // Even if d is within the bounds of i64 seconds,
213 // it might still overflow i64 milliseconds.
214 if d < MIN || d > MAX { None } else { Some(d) }
215 }
216
217 /// Subtract two durations, returning `None` if overflow occurred.
checked_sub(&self, rhs: &Duration) -> Option<Duration>218 pub fn checked_sub(&self, rhs: &Duration) -> Option<Duration> {
219 let mut secs = try_opt!(self.secs.checked_sub(rhs.secs));
220 let mut nanos = self.nanos - rhs.nanos;
221 if nanos < 0 {
222 nanos += NANOS_PER_SEC;
223 secs = try_opt!(secs.checked_sub(1));
224 }
225 let d = Duration { secs: secs, nanos: nanos };
226 // Even if d is within the bounds of i64 seconds,
227 // it might still overflow i64 milliseconds.
228 if d < MIN || d > MAX { None } else { Some(d) }
229 }
230
231 /// The minimum possible `Duration`: `i64::MIN` milliseconds.
232 #[inline]
min_value() -> Duration233 pub fn min_value() -> Duration { MIN }
234
235 /// The maximum possible `Duration`: `i64::MAX` milliseconds.
236 #[inline]
max_value() -> Duration237 pub fn max_value() -> Duration { MAX }
238
239 /// A duration where the stored seconds and nanoseconds are equal to zero.
240 #[inline]
zero() -> Duration241 pub fn zero() -> Duration {
242 Duration { secs: 0, nanos: 0 }
243 }
244
245 /// Returns `true` if the duration equals `Duration::zero()`.
246 #[inline]
is_zero(&self) -> bool247 pub fn is_zero(&self) -> bool {
248 self.secs == 0 && self.nanos == 0
249 }
250
251 /// Creates a `time::Duration` object from `std::time::Duration`
252 ///
253 /// This function errors when original duration is larger than the maximum
254 /// value supported for this type.
from_std(duration: StdDuration) -> Result<Duration, OutOfRangeError>255 pub fn from_std(duration: StdDuration) -> Result<Duration, OutOfRangeError> {
256 // We need to check secs as u64 before coercing to i64
257 if duration.as_secs() > MAX.secs as u64 {
258 return Err(OutOfRangeError(()));
259 }
260 let d = Duration {
261 secs: duration.as_secs() as i64,
262 nanos: duration.subsec_nanos() as i32,
263 };
264 if d > MAX {
265 return Err(OutOfRangeError(()));
266 }
267 Ok(d)
268 }
269
270 /// Creates a `std::time::Duration` object from `time::Duration`
271 ///
272 /// This function errors when duration is less than zero. As standard
273 /// library implementation is limited to non-negative values.
to_std(&self) -> Result<StdDuration, OutOfRangeError>274 pub fn to_std(&self) -> Result<StdDuration, OutOfRangeError> {
275 if self.secs < 0 {
276 return Err(OutOfRangeError(()));
277 }
278 Ok(StdDuration::new(self.secs as u64, self.nanos as u32))
279 }
280 }
281
282 impl Neg for Duration {
283 type Output = Duration;
284
285 #[inline]
neg(self) -> Duration286 fn neg(self) -> Duration {
287 if self.nanos == 0 {
288 Duration { secs: -self.secs, nanos: 0 }
289 } else {
290 Duration { secs: -self.secs - 1, nanos: NANOS_PER_SEC - self.nanos }
291 }
292 }
293 }
294
295 impl Add for Duration {
296 type Output = Duration;
297
add(self, rhs: Duration) -> Duration298 fn add(self, rhs: Duration) -> Duration {
299 let mut secs = self.secs + rhs.secs;
300 let mut nanos = self.nanos + rhs.nanos;
301 if nanos >= NANOS_PER_SEC {
302 nanos -= NANOS_PER_SEC;
303 secs += 1;
304 }
305 Duration { secs: secs, nanos: nanos }
306 }
307 }
308
309 impl Sub for Duration {
310 type Output = Duration;
311
sub(self, rhs: Duration) -> Duration312 fn sub(self, rhs: Duration) -> Duration {
313 let mut secs = self.secs - rhs.secs;
314 let mut nanos = self.nanos - rhs.nanos;
315 if nanos < 0 {
316 nanos += NANOS_PER_SEC;
317 secs -= 1;
318 }
319 Duration { secs: secs, nanos: nanos }
320 }
321 }
322
323 impl Mul<i32> for Duration {
324 type Output = Duration;
325
mul(self, rhs: i32) -> Duration326 fn mul(self, rhs: i32) -> Duration {
327 // Multiply nanoseconds as i64, because it cannot overflow that way.
328 let total_nanos = self.nanos as i64 * rhs as i64;
329 let (extra_secs, nanos) = div_mod_floor_64(total_nanos, NANOS_PER_SEC as i64);
330 let secs = self.secs * rhs as i64 + extra_secs;
331 Duration { secs: secs, nanos: nanos as i32 }
332 }
333 }
334
335 impl Div<i32> for Duration {
336 type Output = Duration;
337
div(self, rhs: i32) -> Duration338 fn div(self, rhs: i32) -> Duration {
339 let mut secs = self.secs / rhs as i64;
340 let carry = self.secs - secs * rhs as i64;
341 let extra_nanos = carry * NANOS_PER_SEC as i64 / rhs as i64;
342 let mut nanos = self.nanos / rhs + extra_nanos as i32;
343 if nanos >= NANOS_PER_SEC {
344 nanos -= NANOS_PER_SEC;
345 secs += 1;
346 }
347 if nanos < 0 {
348 nanos += NANOS_PER_SEC;
349 secs -= 1;
350 }
351 Duration { secs: secs, nanos: nanos }
352 }
353 }
354
355 impl fmt::Display for Duration {
fmt(&self, f: &mut fmt::Formatter) -> fmt::Result356 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
357 // technically speaking, negative duration is not valid ISO 8601,
358 // but we need to print it anyway.
359 let (abs, sign) = if self.secs < 0 { (-*self, "-") } else { (*self, "") };
360
361 let days = abs.secs / SECS_PER_DAY;
362 let secs = abs.secs - days * SECS_PER_DAY;
363 let hasdate = days != 0;
364 let hastime = (secs != 0 || abs.nanos != 0) || !hasdate;
365
366 try!(write!(f, "{}P", sign));
367
368 if hasdate {
369 try!(write!(f, "{}D", days));
370 }
371 if hastime {
372 if abs.nanos == 0 {
373 try!(write!(f, "T{}S", secs));
374 } else if abs.nanos % NANOS_PER_MILLI == 0 {
375 try!(write!(f, "T{}.{:03}S", secs, abs.nanos / NANOS_PER_MILLI));
376 } else if abs.nanos % NANOS_PER_MICRO == 0 {
377 try!(write!(f, "T{}.{:06}S", secs, abs.nanos / NANOS_PER_MICRO));
378 } else {
379 try!(write!(f, "T{}.{:09}S", secs, abs.nanos));
380 }
381 }
382 Ok(())
383 }
384 }
385
386 /// Represents error when converting `Duration` to/from a standard library
387 /// implementation
388 ///
389 /// The `std::time::Duration` supports a range from zero to `u64::MAX`
390 /// *seconds*, while this module supports signed range of up to
391 /// `i64::MAX` of *milliseconds*.
392 #[derive(Debug, Clone, Copy, PartialEq, Eq)]
393 pub struct OutOfRangeError(());
394
395 impl fmt::Display for OutOfRangeError {
fmt(&self, f: &mut fmt::Formatter) -> fmt::Result396 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
397 write!(f, "{}", self.description())
398 }
399 }
400
401 impl Error for OutOfRangeError {
description(&self) -> &str402 fn description(&self) -> &str {
403 "Source duration value is out of range for the target type"
404 }
405 }
406
407 // Copied from libnum
408 #[inline]
div_mod_floor_64(this: i64, other: i64) -> (i64, i64)409 fn div_mod_floor_64(this: i64, other: i64) -> (i64, i64) {
410 (div_floor_64(this, other), mod_floor_64(this, other))
411 }
412
413 #[inline]
div_floor_64(this: i64, other: i64) -> i64414 fn div_floor_64(this: i64, other: i64) -> i64 {
415 match div_rem_64(this, other) {
416 (d, r) if (r > 0 && other < 0)
417 || (r < 0 && other > 0) => d - 1,
418 (d, _) => d,
419 }
420 }
421
422 #[inline]
mod_floor_64(this: i64, other: i64) -> i64423 fn mod_floor_64(this: i64, other: i64) -> i64 {
424 match this % other {
425 r if (r > 0 && other < 0)
426 || (r < 0 && other > 0) => r + other,
427 r => r,
428 }
429 }
430
431 #[inline]
div_rem_64(this: i64, other: i64) -> (i64, i64)432 fn div_rem_64(this: i64, other: i64) -> (i64, i64) {
433 (this / other, this % other)
434 }
435
436 #[cfg(test)]
437 mod tests {
438 use super::{Duration, MIN, MAX, OutOfRangeError};
439 use std::{i32, i64};
440 use std::time::Duration as StdDuration;
441
442 #[test]
test_duration()443 fn test_duration() {
444 assert!(Duration::seconds(1) != Duration::zero());
445 assert_eq!(Duration::seconds(1) + Duration::seconds(2), Duration::seconds(3));
446 assert_eq!(Duration::seconds(86399) + Duration::seconds(4),
447 Duration::days(1) + Duration::seconds(3));
448 assert_eq!(Duration::days(10) - Duration::seconds(1000), Duration::seconds(863000));
449 assert_eq!(Duration::days(10) - Duration::seconds(1000000), Duration::seconds(-136000));
450 assert_eq!(Duration::days(2) + Duration::seconds(86399) +
451 Duration::nanoseconds(1234567890),
452 Duration::days(3) + Duration::nanoseconds(234567890));
453 assert_eq!(-Duration::days(3), Duration::days(-3));
454 assert_eq!(-(Duration::days(3) + Duration::seconds(70)),
455 Duration::days(-4) + Duration::seconds(86400-70));
456 }
457
458 #[test]
test_duration_num_days()459 fn test_duration_num_days() {
460 assert_eq!(Duration::zero().num_days(), 0);
461 assert_eq!(Duration::days(1).num_days(), 1);
462 assert_eq!(Duration::days(-1).num_days(), -1);
463 assert_eq!(Duration::seconds(86399).num_days(), 0);
464 assert_eq!(Duration::seconds(86401).num_days(), 1);
465 assert_eq!(Duration::seconds(-86399).num_days(), 0);
466 assert_eq!(Duration::seconds(-86401).num_days(), -1);
467 assert_eq!(Duration::days(i32::MAX as i64).num_days(), i32::MAX as i64);
468 assert_eq!(Duration::days(i32::MIN as i64).num_days(), i32::MIN as i64);
469 }
470
471 #[test]
test_duration_num_seconds()472 fn test_duration_num_seconds() {
473 assert_eq!(Duration::zero().num_seconds(), 0);
474 assert_eq!(Duration::seconds(1).num_seconds(), 1);
475 assert_eq!(Duration::seconds(-1).num_seconds(), -1);
476 assert_eq!(Duration::milliseconds(999).num_seconds(), 0);
477 assert_eq!(Duration::milliseconds(1001).num_seconds(), 1);
478 assert_eq!(Duration::milliseconds(-999).num_seconds(), 0);
479 assert_eq!(Duration::milliseconds(-1001).num_seconds(), -1);
480 }
481
482 #[test]
test_duration_num_milliseconds()483 fn test_duration_num_milliseconds() {
484 assert_eq!(Duration::zero().num_milliseconds(), 0);
485 assert_eq!(Duration::milliseconds(1).num_milliseconds(), 1);
486 assert_eq!(Duration::milliseconds(-1).num_milliseconds(), -1);
487 assert_eq!(Duration::microseconds(999).num_milliseconds(), 0);
488 assert_eq!(Duration::microseconds(1001).num_milliseconds(), 1);
489 assert_eq!(Duration::microseconds(-999).num_milliseconds(), 0);
490 assert_eq!(Duration::microseconds(-1001).num_milliseconds(), -1);
491 assert_eq!(Duration::milliseconds(i64::MAX).num_milliseconds(), i64::MAX);
492 assert_eq!(Duration::milliseconds(i64::MIN).num_milliseconds(), i64::MIN);
493 assert_eq!(MAX.num_milliseconds(), i64::MAX);
494 assert_eq!(MIN.num_milliseconds(), i64::MIN);
495 }
496
497 #[test]
test_duration_num_microseconds()498 fn test_duration_num_microseconds() {
499 assert_eq!(Duration::zero().num_microseconds(), Some(0));
500 assert_eq!(Duration::microseconds(1).num_microseconds(), Some(1));
501 assert_eq!(Duration::microseconds(-1).num_microseconds(), Some(-1));
502 assert_eq!(Duration::nanoseconds(999).num_microseconds(), Some(0));
503 assert_eq!(Duration::nanoseconds(1001).num_microseconds(), Some(1));
504 assert_eq!(Duration::nanoseconds(-999).num_microseconds(), Some(0));
505 assert_eq!(Duration::nanoseconds(-1001).num_microseconds(), Some(-1));
506 assert_eq!(Duration::microseconds(i64::MAX).num_microseconds(), Some(i64::MAX));
507 assert_eq!(Duration::microseconds(i64::MIN).num_microseconds(), Some(i64::MIN));
508 assert_eq!(MAX.num_microseconds(), None);
509 assert_eq!(MIN.num_microseconds(), None);
510
511 // overflow checks
512 const MICROS_PER_DAY: i64 = 86400_000_000;
513 assert_eq!(Duration::days(i64::MAX / MICROS_PER_DAY).num_microseconds(),
514 Some(i64::MAX / MICROS_PER_DAY * MICROS_PER_DAY));
515 assert_eq!(Duration::days(i64::MIN / MICROS_PER_DAY).num_microseconds(),
516 Some(i64::MIN / MICROS_PER_DAY * MICROS_PER_DAY));
517 assert_eq!(Duration::days(i64::MAX / MICROS_PER_DAY + 1).num_microseconds(), None);
518 assert_eq!(Duration::days(i64::MIN / MICROS_PER_DAY - 1).num_microseconds(), None);
519 }
520
521 #[test]
test_duration_num_nanoseconds()522 fn test_duration_num_nanoseconds() {
523 assert_eq!(Duration::zero().num_nanoseconds(), Some(0));
524 assert_eq!(Duration::nanoseconds(1).num_nanoseconds(), Some(1));
525 assert_eq!(Duration::nanoseconds(-1).num_nanoseconds(), Some(-1));
526 assert_eq!(Duration::nanoseconds(i64::MAX).num_nanoseconds(), Some(i64::MAX));
527 assert_eq!(Duration::nanoseconds(i64::MIN).num_nanoseconds(), Some(i64::MIN));
528 assert_eq!(MAX.num_nanoseconds(), None);
529 assert_eq!(MIN.num_nanoseconds(), None);
530
531 // overflow checks
532 const NANOS_PER_DAY: i64 = 86400_000_000_000;
533 assert_eq!(Duration::days(i64::MAX / NANOS_PER_DAY).num_nanoseconds(),
534 Some(i64::MAX / NANOS_PER_DAY * NANOS_PER_DAY));
535 assert_eq!(Duration::days(i64::MIN / NANOS_PER_DAY).num_nanoseconds(),
536 Some(i64::MIN / NANOS_PER_DAY * NANOS_PER_DAY));
537 assert_eq!(Duration::days(i64::MAX / NANOS_PER_DAY + 1).num_nanoseconds(), None);
538 assert_eq!(Duration::days(i64::MIN / NANOS_PER_DAY - 1).num_nanoseconds(), None);
539 }
540
541 #[test]
test_duration_checked_ops()542 fn test_duration_checked_ops() {
543 assert_eq!(Duration::milliseconds(i64::MAX - 1).checked_add(&Duration::microseconds(999)),
544 Some(Duration::milliseconds(i64::MAX - 2) + Duration::microseconds(1999)));
545 assert!(Duration::milliseconds(i64::MAX).checked_add(&Duration::microseconds(1000))
546 .is_none());
547
548 assert_eq!(Duration::milliseconds(i64::MIN).checked_sub(&Duration::milliseconds(0)),
549 Some(Duration::milliseconds(i64::MIN)));
550 assert!(Duration::milliseconds(i64::MIN).checked_sub(&Duration::milliseconds(1))
551 .is_none());
552 }
553
554 #[test]
test_duration_mul()555 fn test_duration_mul() {
556 assert_eq!(Duration::zero() * i32::MAX, Duration::zero());
557 assert_eq!(Duration::zero() * i32::MIN, Duration::zero());
558 assert_eq!(Duration::nanoseconds(1) * 0, Duration::zero());
559 assert_eq!(Duration::nanoseconds(1) * 1, Duration::nanoseconds(1));
560 assert_eq!(Duration::nanoseconds(1) * 1_000_000_000, Duration::seconds(1));
561 assert_eq!(Duration::nanoseconds(1) * -1_000_000_000, -Duration::seconds(1));
562 assert_eq!(-Duration::nanoseconds(1) * 1_000_000_000, -Duration::seconds(1));
563 assert_eq!(Duration::nanoseconds(30) * 333_333_333,
564 Duration::seconds(10) - Duration::nanoseconds(10));
565 assert_eq!((Duration::nanoseconds(1) + Duration::seconds(1) + Duration::days(1)) * 3,
566 Duration::nanoseconds(3) + Duration::seconds(3) + Duration::days(3));
567 assert_eq!(Duration::milliseconds(1500) * -2, Duration::seconds(-3));
568 assert_eq!(Duration::milliseconds(-1500) * 2, Duration::seconds(-3));
569 }
570
571 #[test]
test_duration_div()572 fn test_duration_div() {
573 assert_eq!(Duration::zero() / i32::MAX, Duration::zero());
574 assert_eq!(Duration::zero() / i32::MIN, Duration::zero());
575 assert_eq!(Duration::nanoseconds(123_456_789) / 1, Duration::nanoseconds(123_456_789));
576 assert_eq!(Duration::nanoseconds(123_456_789) / -1, -Duration::nanoseconds(123_456_789));
577 assert_eq!(-Duration::nanoseconds(123_456_789) / -1, Duration::nanoseconds(123_456_789));
578 assert_eq!(-Duration::nanoseconds(123_456_789) / 1, -Duration::nanoseconds(123_456_789));
579 assert_eq!(Duration::seconds(1) / 3, Duration::nanoseconds(333_333_333));
580 assert_eq!(Duration::seconds(4) / 3, Duration::nanoseconds(1_333_333_333));
581 assert_eq!(Duration::seconds(-1) / 2, Duration::milliseconds(-500));
582 assert_eq!(Duration::seconds(1) / -2, Duration::milliseconds(-500));
583 assert_eq!(Duration::seconds(-1) / -2, Duration::milliseconds(500));
584 assert_eq!(Duration::seconds(-4) / 3, Duration::nanoseconds(-1_333_333_333));
585 assert_eq!(Duration::seconds(-4) / -3, Duration::nanoseconds(1_333_333_333));
586 }
587
588 #[test]
test_duration_fmt()589 fn test_duration_fmt() {
590 assert_eq!(Duration::zero().to_string(), "PT0S");
591 assert_eq!(Duration::days(42).to_string(), "P42D");
592 assert_eq!(Duration::days(-42).to_string(), "-P42D");
593 assert_eq!(Duration::seconds(42).to_string(), "PT42S");
594 assert_eq!(Duration::milliseconds(42).to_string(), "PT0.042S");
595 assert_eq!(Duration::microseconds(42).to_string(), "PT0.000042S");
596 assert_eq!(Duration::nanoseconds(42).to_string(), "PT0.000000042S");
597 assert_eq!((Duration::days(7) + Duration::milliseconds(6543)).to_string(),
598 "P7DT6.543S");
599 assert_eq!(Duration::seconds(-86401).to_string(), "-P1DT1S");
600 assert_eq!(Duration::nanoseconds(-1).to_string(), "-PT0.000000001S");
601
602 // the format specifier should have no effect on `Duration`
603 assert_eq!(format!("{:30}", Duration::days(1) + Duration::milliseconds(2345)),
604 "P1DT2.345S");
605 }
606
607 #[test]
test_to_std()608 fn test_to_std() {
609 assert_eq!(Duration::seconds(1).to_std(), Ok(StdDuration::new(1, 0)));
610 assert_eq!(Duration::seconds(86401).to_std(), Ok(StdDuration::new(86401, 0)));
611 assert_eq!(Duration::milliseconds(123).to_std(), Ok(StdDuration::new(0, 123000000)));
612 assert_eq!(Duration::milliseconds(123765).to_std(), Ok(StdDuration::new(123, 765000000)));
613 assert_eq!(Duration::nanoseconds(777).to_std(), Ok(StdDuration::new(0, 777)));
614 assert_eq!(MAX.to_std(), Ok(StdDuration::new(9223372036854775, 807000000)));
615 assert_eq!(Duration::seconds(-1).to_std(),
616 Err(OutOfRangeError(())));
617 assert_eq!(Duration::milliseconds(-1).to_std(),
618 Err(OutOfRangeError(())));
619 }
620
621 #[test]
test_from_std()622 fn test_from_std() {
623 assert_eq!(Ok(Duration::seconds(1)),
624 Duration::from_std(StdDuration::new(1, 0)));
625 assert_eq!(Ok(Duration::seconds(86401)),
626 Duration::from_std(StdDuration::new(86401, 0)));
627 assert_eq!(Ok(Duration::milliseconds(123)),
628 Duration::from_std(StdDuration::new(0, 123000000)));
629 assert_eq!(Ok(Duration::milliseconds(123765)),
630 Duration::from_std(StdDuration::new(123, 765000000)));
631 assert_eq!(Ok(Duration::nanoseconds(777)),
632 Duration::from_std(StdDuration::new(0, 777)));
633 assert_eq!(Ok(MAX),
634 Duration::from_std(StdDuration::new(9223372036854775, 807000000)));
635 assert_eq!(Duration::from_std(StdDuration::new(9223372036854776, 0)),
636 Err(OutOfRangeError(())));
637 assert_eq!(Duration::from_std(StdDuration::new(9223372036854775, 807000001)),
638 Err(OutOfRangeError(())));
639 }
640 }
641