Skip to content

Commit 5008a31

Browse files
committed
Fix non-associativity of Instant math on aarch64-apple-darwin targets
1 parent e4d6307 commit 5008a31

File tree

2 files changed

+23
-3
lines changed

2 files changed

+23
-3
lines changed

Diff for: library/std/src/sys/unix/time.rs

+15-3
Original file line numberDiff line numberDiff line change
@@ -149,7 +149,11 @@ impl From<libc::timespec> for Timespec {
149149
}
150150
}
151151

152-
#[cfg(any(target_os = "macos", target_os = "ios", target_os = "watchos"))]
152+
#[cfg(any(
153+
all(target_os = "macos", not(target_arch = "aarch64")),
154+
target_os = "ios",
155+
target_os = "watchos"
156+
))]
153157
mod inner {
154158
use crate::sync::atomic::{AtomicU64, Ordering};
155159
use crate::sys::cvt;
@@ -265,7 +269,11 @@ mod inner {
265269
}
266270
}
267271

268-
#[cfg(not(any(target_os = "macos", target_os = "ios", target_os = "watchos")))]
272+
#[cfg(not(any(
273+
all(target_os = "macos", not(target_arch = "aarch64")),
274+
target_os = "ios",
275+
target_os = "watchos"
276+
)))]
269277
mod inner {
270278
use crate::fmt;
271279
use crate::mem::MaybeUninit;
@@ -281,7 +289,11 @@ mod inner {
281289

282290
impl Instant {
283291
pub fn now() -> Instant {
284-
Instant { t: Timespec::now(libc::CLOCK_MONOTONIC) }
292+
#[cfg(target_os = "macos")]
293+
const clock_id: clock_t = libc::CLOCK_UPTIME_RAW;
294+
#[cfg(not(target_os = "macos"))]
295+
const clock_id: clock_t = libc::CLOCK_MONOTONIC;
296+
Instant { t: Timespec::now(clock_id) }
285297
}
286298

287299
pub fn checked_sub_instant(&self, other: &Instant) -> Option<Duration> {

Diff for: library/std/src/time/tests.rs

+8
Original file line numberDiff line numberDiff line change
@@ -88,6 +88,14 @@ fn instant_math_is_associative() {
8888
// Changing the order of instant math shouldn't change the results,
8989
// especially when the expression reduces to X + identity.
9090
assert_eq!((now + offset) - now, (now - now) + offset);
91+
92+
// On any platform, `Instant` should have the same resolution as `Duration` (e.g. 1 nanosecond)
93+
// or better. Otherwise, math will be non-associative (see #91417).
94+
let now = Instant::now();
95+
let provided_offset = Duration::from_nanos(1);
96+
let later = now + provided_offset;
97+
let measured_offset = later - now;
98+
assert_eq!(measured_offset, provided_offset);
9199
}
92100

93101
#[test]

0 commit comments

Comments
 (0)