Skip to content

Commit

Permalink
Add wasm support
Browse files Browse the repository at this point in the history
  • Loading branch information
aochagavia committed Dec 2, 2017
1 parent 48e4e6f commit cbd99e5
Show file tree
Hide file tree
Showing 2 changed files with 32 additions and 4 deletions.
16 changes: 12 additions & 4 deletions src/jitter.rs
Original file line number Diff line number Diff line change
Expand Up @@ -171,11 +171,11 @@ impl JitterRng {

ec
}

/// Configures how many rounds are used to generate each 64-bit value.
/// This must be greater than zero, and has a big impact on performance
/// and output quality.
///
///
/// `new_with_timer` conservatively uses 64 rounds, but often less rounds
/// can be used. The `test_timer()` function returns the minimum number of
/// rounds required for full strength (platform dependent), so one may use
Expand Down Expand Up @@ -437,6 +437,9 @@ impl JitterRng {
// or check for `CONFIG_X86_TSC`, but it does not make much sense as the
// following sanity checks verify that we have a high-resolution timer.

#[cfg(all(target_arch = "wasm32", not(target_os = "emscripten")))]
return Err(TimerError::NoTimer);

let mut delta_sum = 0;
let mut old_delta = 0;

Expand Down Expand Up @@ -549,7 +552,7 @@ impl JitterRng {

const FACTOR: u32 = 3;
fn log2(x: u64) -> u32 { 64 - x.leading_zeros() }

// pow(δ, FACTOR) must be representable; if you have overflow reduce FACTOR
Ok(64 * 2 * FACTOR / (log2(delta_average.pow(FACTOR)) + 1))
}
Expand Down Expand Up @@ -654,7 +657,7 @@ impl JitterRng {
}
}

#[cfg(not(any(target_os = "macos", target_os = "ios", target_os = "windows")))]
#[cfg(not(any(target_os = "macos", target_os = "ios", target_os = "windows", all(target_arch = "wasm32", not(target_os = "emscripten")))))]
fn get_nstime() -> u64 {
use std::time::{SystemTime, UNIX_EPOCH};

Expand Down Expand Up @@ -693,6 +696,11 @@ fn get_nstime() -> u64 {
t as u64
}

#[cfg(all(target_arch = "wasm32", not(target_os = "emscripten")))]
fn get_nstime() -> u64 {
unreachable!()
}

// 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
20 changes: 20 additions & 0 deletions src/os.rs
Original file line number Diff line number Diff line change
Expand Up @@ -544,6 +544,26 @@ mod imp {
}
}

#[cfg(all(target_arch = "wasm32", not(target_os = "emscripten")))]
mod imp {
use std::io;
use Rng;

#[derive(Debug)]
pub struct OsRng;

impl OsRng {
pub fn new() -> io::Result<OsRng> {
Err(io::Error::new(io::ErrorKind::Other, "Not supported"))
}
}

impl Rng for OsRng {
fn next_u32(&mut self) -> u32 {
panic!("Not supported")
}
}
}

#[cfg(test)]
mod test {
Expand Down

0 comments on commit cbd99e5

Please sign in to comment.