Skip to content

Commit 785a624

Browse files
committed
library: sub_timespec use arithmetic to avoid overflow
1 parent 1b70588 commit 785a624

File tree

1 file changed

+14
-4
lines changed
  • library/std/src/sys/pal/unix

1 file changed

+14
-4
lines changed

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

Lines changed: 14 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -139,10 +139,20 @@ impl Timespec {
139139
#[rustc_const_unstable(feature = "const_system_time", issue = "144517")]
140140
pub const fn sub_timespec(&self, other: &Timespec) -> Result<Duration, Duration> {
141141
// FIXME: const PartialOrd
142-
let mut cmp = self.tv_sec - other.tv_sec;
143-
if cmp == 0 {
144-
cmp = self.tv_nsec.as_inner() as i64 - other.tv_nsec.as_inner() as i64;
145-
}
142+
// Use saturating arithmetic to avoid overflow when comparing extreme values
143+
let sec_cmp = if self.tv_sec < other.tv_sec {
144+
-1
145+
} else if self.tv_sec > other.tv_sec {
146+
1
147+
} else {
148+
0
149+
};
150+
151+
let cmp = if sec_cmp == 0 {
152+
self.tv_nsec.as_inner() as i64 - other.tv_nsec.as_inner() as i64
153+
} else {
154+
sec_cmp
155+
};
146156

147157
if cmp >= 0 {
148158
// NOTE(eddyb) two aspects of this `if`-`else` are required for LLVM

0 commit comments

Comments
 (0)