Skip to content

Commit

Permalink
Merge pull request #57 from pitdicker/jitterrng_apple
Browse files Browse the repository at this point in the history
Fix `JitterRng` on Mac OS
  • Loading branch information
dhardy authored Nov 21, 2017
2 parents e7335be + 0ccaa6b commit 03ff2d6
Show file tree
Hide file tree
Showing 2 changed files with 17 additions and 3 deletions.
4 changes: 3 additions & 1 deletion .travis.yml
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
16 changes: 14 additions & 2 deletions src/jitter_rng.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down Expand Up @@ -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};

Expand All @@ -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<T>(dummy: T) -> T {
Expand Down

0 comments on commit 03ff2d6

Please sign in to comment.