From 0ccaa6bea90d72946be8d88fbed584bd7bd64563 Mon Sep 17 00:00:00 2001 From: Paul Dicker Date: Mon, 20 Nov 2017 21:00:20 +0100 Subject: [PATCH] Fix `JitterRng` on Mac OS --- .travis.yml | 4 +++- src/jitter_rng.rs | 16 ++++++++++++++-- 2 files changed, 17 insertions(+), 3 deletions(-) diff --git a/.travis.yml b/.travis.yml index 9704ea6cfd3..9ec7cbc232b 100644 --- a/.travis.yml +++ b/.travis.yml @@ -78,9 +78,11 @@ matrix: rust: nightly # Testing other channels - # Don't run nightly tests on darwin: JitterRng bench fails due to low-res timer - env: TARGET=x86_64-unknown-linux-gnu NIGHTLY=1 rust: nightly + - env: TARGET=x86_64-apple-darwin NIGHTLY=1 + os: osx + rust: nightly before_install: - set -e diff --git a/src/jitter_rng.rs b/src/jitter_rng.rs index 78d8e250c37..d36cf79aafe 100644 --- a/src/jitter_rng.rs +++ b/src/jitter_rng.rs @@ -611,7 +611,7 @@ impl JitterRng { /// times. This measures the absolute worst-case, and gives a lower bound /// for the available entropy. /// - /// ```no_run + /// ```rust,no_run /// use rand::JitterRng; /// /// # use std::error::Error; @@ -670,7 +670,7 @@ impl JitterRng { } } -#[cfg(feature="std")] +#[cfg(all(feature="std", not(any(target_os = "macos", target_os = "ios"))))] fn get_nstime() -> u64 { use std::time::{SystemTime, UNIX_EPOCH}; @@ -682,6 +682,18 @@ fn get_nstime() -> u64 { dur.as_secs() << 30 | dur.subsec_nanos() as u64 } +#[cfg(all(feature="std", any(target_os = "macos", target_os = "ios")))] +fn get_nstime() -> u64 { + extern crate libc; + // On Mac OS and iOS std::time::SystemTime only has 1000ns resolution. + // We use `mach_absolute_time` instead. This provides a CPU dependent unit, + // to get real nanoseconds the result should by multiplied by numer/denom + // from `mach_timebase_info`. + // But we are not interested in the exact nanoseconds, just entropy. So we + // use the raw result. + unsafe { libc::mach_absolute_time() } +} + // A function that is opaque to the optimizer to assist in avoiding dead-code // elimination. Taken from `bencher`. fn black_box(dummy: T) -> T {