Skip to content

Commit 162ee46

Browse files
committed
Repro duration_since regression from issue 146228
1 parent d1ed52b commit 162ee46

File tree

3 files changed

+20
-4
lines changed

3 files changed

+20
-4
lines changed

library/std/src/sys/pal/hermit/time.rs

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -29,12 +29,12 @@ impl Timespec {
2929
if self >= other {
3030
Ok(if self.t.tv_nsec >= other.t.tv_nsec {
3131
Duration::new(
32-
(self.t.tv_sec - other.t.tv_sec) as u64,
32+
self.t.tv_sec.wrapping_sub(other.t.tv_sec) as u64,
3333
(self.t.tv_nsec - other.t.tv_nsec) as u32,
3434
)
3535
} else {
3636
Duration::new(
37-
(self.t.tv_sec - 1 - other.t.tv_sec) as u64,
37+
(self.t.tv_sec - 1).wrapping_sub(other.t.tv_sec) as u64,
3838
(self.t.tv_nsec + NSEC_PER_SEC - other.t.tv_nsec) as u32,
3939
)
4040
})

library/std/src/sys/pal/unix/time.rs

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -150,12 +150,12 @@ impl Timespec {
150150
// directly expresses the lower-cost behavior we want from it.
151151
let (secs, nsec) = if self.tv_nsec.as_inner() >= other.tv_nsec.as_inner() {
152152
(
153-
(self.tv_sec - other.tv_sec) as u64,
153+
self.tv_sec.wrapping_sub(other.tv_sec) as u64,
154154
self.tv_nsec.as_inner() - other.tv_nsec.as_inner(),
155155
)
156156
} else {
157157
(
158-
(self.tv_sec - other.tv_sec - 1) as u64,
158+
(self.tv_sec - 1).wrapping_sub(other.tv_sec) as u64,
159159
self.tv_nsec.as_inner() + (NSEC_PER_SEC as u32) - other.tv_nsec.as_inner(),
160160
)
161161
};

library/std/tests/time.rs

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -227,3 +227,19 @@ fn big_math() {
227227
check(instant.checked_add(Duration::from_secs(100)), Instant::checked_sub);
228228
check(instant.checked_add(Duration::from_secs(i64::MAX as _)), Instant::checked_sub);
229229
}
230+
231+
#[test]
232+
#[cfg(unix)]
233+
fn system_time_duration_since_max_range_on_unix() {
234+
// Repro regression https://github.com/rust-lang/rust/issues/146228
235+
236+
// Min and max values of `SystemTime` on Unix.
237+
let min = SystemTime::UNIX_EPOCH - (Duration::new(i64::MAX as u64 + 1, 0));
238+
let max = SystemTime::UNIX_EPOCH + (Duration::new(i64::MAX as u64, 999_999_999));
239+
240+
let delta_a = max.duration_since(min).expect("duration_since overflow");
241+
let delta_b = min.duration_since(max).expect_err("duration_since overflow").duration();
242+
243+
assert_eq!(Duration::MAX, delta_a);
244+
assert_eq!(Duration::MAX, delta_b);
245+
}

0 commit comments

Comments
 (0)