diff options
Diffstat (limited to 'rand/src')
37 files changed, 0 insertions, 10387 deletions
diff --git a/rand/src/deprecated.rs b/rand/src/deprecated.rs deleted file mode 100644 index 88eb09f..0000000 --- a/rand/src/deprecated.rs +++ /dev/null @@ -1,544 +0,0 @@ -// Copyright 2018 Developers of the Rand project. -// -// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or -// https://www.apache.org/licenses/LICENSE-2.0> or the MIT license -// <LICENSE-MIT or https://opensource.org/licenses/MIT>, at your -// option. This file may not be copied, modified, or distributed -// except according to those terms. - -//! Deprecated re-exports (we can't add deprecation warnings otherwise) - -#![allow(deprecated)] - -use rngs; -use {RngCore, CryptoRng, SeedableRng, Error}; -use rand_core::block::BlockRngCore; -use rand_isaac; -use rand_chacha; -use rand_hc; - -#[cfg(feature="std")] -use std::io::Read; - -#[derive(Clone, Debug)] -#[deprecated(since="0.6.0", - note="import from rand_isaac crate instead, or use the newer Hc128Rng")] -pub struct IsaacRng(rand_isaac::IsaacRng); - -impl RngCore for IsaacRng { - #[inline(always)] - fn next_u32(&mut self) -> u32 { - self.0.next_u32() - } - - #[inline(always)] - fn next_u64(&mut self) -> u64 { - self.0.next_u64() - } - - #[inline(always)] - fn fill_bytes(&mut self, dest: &mut [u8]) { - self.0.fill_bytes(dest); - } - - #[inline(always)] - fn try_fill_bytes(&mut self, dest: &mut [u8]) -> Result<(), Error> { - self.0.try_fill_bytes(dest) - } -} - -impl SeedableRng for IsaacRng { - type Seed = <rand_isaac::IsaacRng as SeedableRng>::Seed; - - fn from_seed(seed: Self::Seed) -> Self { - IsaacRng(rand_isaac::IsaacRng::from_seed(seed)) - } - - fn from_rng<R: RngCore>(rng: R) -> Result<Self, Error> { - rand_isaac::IsaacRng::from_rng(rng).map(IsaacRng) - } -} - -impl IsaacRng { - pub fn new_from_u64(seed: u64) -> Self { - IsaacRng(rand_isaac::IsaacRng::new_from_u64(seed)) - } -} - - -#[derive(Clone, Debug)] -#[deprecated(since="0.6.0", - note="import from rand_isaac crate instead, or use newer Hc128Rng")] -pub struct Isaac64Rng(rand_isaac::Isaac64Rng); - -impl RngCore for Isaac64Rng { - #[inline(always)] - fn next_u32(&mut self) -> u32 { - self.0.next_u32() - } - - #[inline(always)] - fn next_u64(&mut self) -> u64 { - self.0.next_u64() - } - - #[inline(always)] - fn fill_bytes(&mut self, dest: &mut [u8]) { - self.0.fill_bytes(dest); - } - - #[inline(always)] - fn try_fill_bytes(&mut self, dest: &mut [u8]) -> Result<(), Error> { - self.0.try_fill_bytes(dest) - } -} - -impl SeedableRng for Isaac64Rng { - type Seed = <rand_isaac::Isaac64Rng as SeedableRng>::Seed; - - fn from_seed(seed: Self::Seed) -> Self { - Isaac64Rng(rand_isaac::Isaac64Rng::from_seed(seed)) - } - - fn from_rng<R: RngCore>(rng: R) -> Result<Self, Error> { - rand_isaac::Isaac64Rng::from_rng(rng).map(Isaac64Rng) - } -} - -impl Isaac64Rng { - pub fn new_from_u64(seed: u64) -> Self { - Isaac64Rng(rand_isaac::Isaac64Rng::new_from_u64(seed)) - } -} - - -#[derive(Clone, Debug)] -#[deprecated(since="0.6.0", note="import from rand_chacha crate instead")] -pub struct ChaChaRng(rand_chacha::ChaChaRng); - -impl RngCore for ChaChaRng { - #[inline(always)] - fn next_u32(&mut self) -> u32 { - self.0.next_u32() - } - - #[inline(always)] - fn next_u64(&mut self) -> u64 { - self.0.next_u64() - } - - #[inline(always)] - fn fill_bytes(&mut self, dest: &mut [u8]) { - self.0.fill_bytes(dest); - } - - #[inline(always)] - fn try_fill_bytes(&mut self, dest: &mut [u8]) -> Result<(), Error> { - self.0.try_fill_bytes(dest) - } -} - -impl SeedableRng for ChaChaRng { - type Seed = <rand_chacha::ChaChaRng as SeedableRng>::Seed; - - fn from_seed(seed: Self::Seed) -> Self { - ChaChaRng(rand_chacha::ChaChaRng::from_seed(seed)) - } - - fn from_rng<R: RngCore>(rng: R) -> Result<Self, Error> { - rand_chacha::ChaChaRng::from_rng(rng).map(ChaChaRng) - } -} - -impl ChaChaRng { - #[cfg(all(rustc_1_26, not(target_os = "emscripten")))] - pub fn get_word_pos(&self) -> u128 { - self.0.get_word_pos() - } - - #[cfg(all(rustc_1_26, not(target_os = "emscripten")))] - pub fn set_word_pos(&mut self, word_offset: u128) { - self.0.set_word_pos(word_offset) - } - - pub fn set_stream(&mut self, stream: u64) { - self.0.set_stream(stream) - } -} - -impl CryptoRng for ChaChaRng {} - - -#[derive(Clone, Debug)] -#[deprecated(since="0.6.0", note="import from rand_hc crate instead")] -pub struct Hc128Rng(rand_hc::Hc128Rng); - -impl RngCore for Hc128Rng { - #[inline(always)] - fn next_u32(&mut self) -> u32 { - self.0.next_u32() - } - - #[inline(always)] - fn next_u64(&mut self) -> u64 { - self.0.next_u64() - } - - #[inline(always)] - fn fill_bytes(&mut self, dest: &mut [u8]) { - self.0.fill_bytes(dest); - } - - #[inline(always)] - fn try_fill_bytes(&mut self, dest: &mut [u8]) -> Result<(), Error> { - self.0.try_fill_bytes(dest) - } -} - -impl SeedableRng for Hc128Rng { - type Seed = <rand_hc::Hc128Rng as SeedableRng>::Seed; - - fn from_seed(seed: Self::Seed) -> Self { - Hc128Rng(rand_hc::Hc128Rng::from_seed(seed)) - } - - fn from_rng<R: RngCore>(rng: R) -> Result<Self, Error> { - rand_hc::Hc128Rng::from_rng(rng).map(Hc128Rng) - } -} - -impl CryptoRng for Hc128Rng {} - - -#[derive(Clone, Debug)] -#[deprecated(since="0.6.0", note="import from rand_xorshift crate instead")] -pub struct XorShiftRng(::rand_xorshift::XorShiftRng); - -impl RngCore for XorShiftRng { - #[inline(always)] - fn next_u32(&mut self) -> u32 { - self.0.next_u32() - } - - #[inline(always)] - fn next_u64(&mut self) -> u64 { - self.0.next_u64() - } - - #[inline(always)] - fn fill_bytes(&mut self, dest: &mut [u8]) { - self.0.fill_bytes(dest); - } - - #[inline(always)] - fn try_fill_bytes(&mut self, dest: &mut [u8]) -> Result<(), Error> { - self.0.try_fill_bytes(dest) - } -} - -impl SeedableRng for XorShiftRng { - type Seed = <::rand_xorshift::XorShiftRng as SeedableRng>::Seed; - - fn from_seed(seed: Self::Seed) -> Self { - XorShiftRng(::rand_xorshift::XorShiftRng::from_seed(seed)) - } - - fn from_rng<R: RngCore>(rng: R) -> Result<Self, Error> { - ::rand_xorshift::XorShiftRng::from_rng(rng).map(XorShiftRng) - } -} - - -#[derive(Clone, Debug)] -#[deprecated(since="0.6.0", - note="import with rand::prelude::* or rand::rngs::StdRng instead")] -pub struct StdRng(rngs::StdRng); - -impl RngCore for StdRng { - #[inline(always)] - fn next_u32(&mut self) -> u32 { - self.0.next_u32() - } - - #[inline(always)] - fn next_u64(&mut self) -> u64 { - self.0.next_u64() - } - - #[inline(always)] - fn fill_bytes(&mut self, dest: &mut [u8]) { - self.0.fill_bytes(dest); - } - - #[inline(always)] - fn try_fill_bytes(&mut self, dest: &mut [u8]) -> Result<(), Error> { - self.0.try_fill_bytes(dest) - } -} - -impl SeedableRng for StdRng { - type Seed = <rngs::StdRng as SeedableRng>::Seed; - - fn from_seed(seed: Self::Seed) -> Self { - StdRng(rngs::StdRng::from_seed(seed)) - } - - fn from_rng<R: RngCore>(rng: R) -> Result<Self, Error> { - rngs::StdRng::from_rng(rng).map(StdRng) - } -} - -impl CryptoRng for StdRng {} - - -#[cfg(feature="rand_os")] -#[derive(Clone, Debug)] -#[deprecated(since="0.6.0", note="import with rand::rngs::OsRng instead")] -pub struct OsRng(rngs::OsRng); - -#[cfg(feature="rand_os")] -impl RngCore for OsRng { - #[inline(always)] - fn next_u32(&mut self) -> u32 { - self.0.next_u32() - } - - #[inline(always)] - fn next_u64(&mut self) -> u64 { - self.0.next_u64() - } - - #[inline(always)] - fn fill_bytes(&mut self, dest: &mut [u8]) { - self.0.fill_bytes(dest); - } - - #[inline(always)] - fn try_fill_bytes(&mut self, dest: &mut [u8]) -> Result<(), Error> { - self.0.try_fill_bytes(dest) - } -} - -#[cfg(feature="rand_os")] -impl OsRng { - pub fn new() -> Result<Self, Error> { - rngs::OsRng::new().map(OsRng) - } -} - -#[cfg(feature="rand_os")] -impl CryptoRng for OsRng {} - - -#[cfg(feature="std")] -#[derive(Debug)] -#[deprecated(since="0.6.0", note="import with rand::rngs::EntropyRng instead")] -pub struct EntropyRng(rngs::EntropyRng); - -#[cfg(feature="std")] -impl RngCore for EntropyRng { - #[inline(always)] - fn next_u32(&mut self) -> u32 { - self.0.next_u32() - } - - #[inline(always)] - fn next_u64(&mut self) -> u64 { - self.0.next_u64() - } - - #[inline(always)] - fn fill_bytes(&mut self, dest: &mut [u8]) { - self.0.fill_bytes(dest); - } - - #[inline(always)] - fn try_fill_bytes(&mut self, dest: &mut [u8]) -> Result<(), Error> { - self.0.try_fill_bytes(dest) - } -} - -#[cfg(feature="std")] -impl EntropyRng { - pub fn new() -> Self { - EntropyRng(rngs::EntropyRng::new()) - } -} - -#[cfg(feature="std")] -impl Default for EntropyRng { - fn default() -> Self { - EntropyRng::new() - } -} - -#[cfg(feature="std")] -impl CryptoRng for EntropyRng {} - - -#[derive(Clone, Debug)] -#[deprecated(since="0.6.0", note="import with rand::rngs::JitterRng instead")] -pub struct JitterRng(rngs::JitterRng); - -impl RngCore for JitterRng { - #[inline(always)] - fn next_u32(&mut self) -> u32 { - self.0.next_u32() - } - - #[inline(always)] - fn next_u64(&mut self) -> u64 { - self.0.next_u64() - } - - #[inline(always)] - fn fill_bytes(&mut self, dest: &mut [u8]) { - self.0.fill_bytes(dest); - } - - #[inline(always)] - fn try_fill_bytes(&mut self, dest: &mut [u8]) -> Result<(), Error> { - self.0.try_fill_bytes(dest) - } -} - -impl JitterRng { - #[cfg(all(feature="std", not(target_arch = "wasm32")))] - pub fn new() -> Result<JitterRng, rngs::TimerError> { - rngs::JitterRng::new().map(JitterRng) - } - - pub fn new_with_timer(timer: fn() -> u64) -> JitterRng { - JitterRng(rngs::JitterRng::new_with_timer(timer)) - } - - pub fn set_rounds(&mut self, rounds: u8) { - self.0.set_rounds(rounds) - } - - pub fn test_timer(&mut self) -> Result<u8, rngs::TimerError> { - self.0.test_timer() - } - - #[cfg(feature="std")] - pub fn timer_stats(&mut self, var_rounds: bool) -> i64 { - self.0.timer_stats(var_rounds) - } -} - -impl CryptoRng for JitterRng {} - - -#[cfg(feature="std")] -#[derive(Clone, Debug)] -#[deprecated(since="0.6.0", - note="import with rand::prelude::* or rand::rngs::ThreadRng instead")] -pub struct ThreadRng(rngs::ThreadRng); - -#[cfg(feature="std")] -impl RngCore for ThreadRng { - #[inline(always)] - fn next_u32(&mut self) -> u32 { - self.0.next_u32() - } - - #[inline(always)] - fn next_u64(&mut self) -> u64 { - self.0.next_u64() - } - - #[inline(always)] - fn fill_bytes(&mut self, dest: &mut [u8]) { - self.0.fill_bytes(dest); - } - - #[inline(always)] - fn try_fill_bytes(&mut self, dest: &mut [u8]) -> Result<(), Error> { - self.0.try_fill_bytes(dest) - } -} - -#[cfg(feature="std")] -impl CryptoRng for ThreadRng {} - - -#[cfg(feature="std")] -#[derive(Debug)] -#[deprecated(since="0.6.0", note="import with rand::rngs::adapter::ReadRng instead")] -pub struct ReadRng<R>(rngs::adapter::ReadRng<R>); - -#[cfg(feature="std")] -impl<R: Read> RngCore for ReadRng<R> { - #[inline(always)] - fn next_u32(&mut self) -> u32 { - self.0.next_u32() - } - - #[inline(always)] - fn next_u64(&mut self) -> u64 { - self.0.next_u64() - } - - #[inline(always)] - fn fill_bytes(&mut self, dest: &mut [u8]) { - self.0.fill_bytes(dest); - } - - #[inline(always)] - fn try_fill_bytes(&mut self, dest: &mut [u8]) -> Result<(), Error> { - self.0.try_fill_bytes(dest) - } -} - -#[cfg(feature="std")] -impl<R: Read> ReadRng<R> { - pub fn new(r: R) -> ReadRng<R> { - ReadRng(rngs::adapter::ReadRng::new(r)) - } -} - - -#[derive(Clone, Debug)] -pub struct ReseedingRng<R, Rsdr>(rngs::adapter::ReseedingRng<R, Rsdr>) -where R: BlockRngCore + SeedableRng, - Rsdr: RngCore; - -impl<R, Rsdr: RngCore> RngCore for ReseedingRng<R, Rsdr> -where R: BlockRngCore<Item = u32> + SeedableRng, - <R as BlockRngCore>::Results: AsRef<[u32]> + AsMut<[u32]> -{ - #[inline(always)] - fn next_u32(&mut self) -> u32 { - self.0.next_u32() - } - - #[inline(always)] - fn next_u64(&mut self) -> u64 { - self.0.next_u64() - } - - fn fill_bytes(&mut self, dest: &mut [u8]) { - self.0.fill_bytes(dest) - } - - fn try_fill_bytes(&mut self, dest: &mut [u8]) -> Result<(), Error> { - self.0.try_fill_bytes(dest) - } -} - -impl<R, Rsdr> ReseedingRng<R, Rsdr> -where R: BlockRngCore + SeedableRng, - Rsdr: RngCore -{ - pub fn new(rng: R, threshold: u64, reseeder: Rsdr) -> Self { - ReseedingRng(rngs::adapter::ReseedingRng::new(rng, threshold, reseeder)) - } - - pub fn reseed(&mut self) -> Result<(), Error> { - self.0.reseed() - } -} - -impl<R, Rsdr> CryptoRng for ReseedingRng<R, Rsdr> -where R: BlockRngCore + SeedableRng + CryptoRng, - Rsdr: RngCore + CryptoRng {} diff --git a/rand/src/distributions/bernoulli.rs b/rand/src/distributions/bernoulli.rs deleted file mode 100644 index f49618c..0000000 --- a/rand/src/distributions/bernoulli.rs +++ /dev/null @@ -1,165 +0,0 @@ -// Copyright 2018 Developers of the Rand project. -// -// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or -// https://www.apache.org/licenses/LICENSE-2.0> or the MIT license -// <LICENSE-MIT or https://opensource.org/licenses/MIT>, at your -// option. This file may not be copied, modified, or distributed -// except according to those terms. - -//! The Bernoulli distribution. - -use Rng; -use distributions::Distribution; - -/// The Bernoulli distribution. -/// -/// This is a special case of the Binomial distribution where `n = 1`. -/// -/// # Example -/// -/// ```rust -/// use rand::distributions::{Bernoulli, Distribution}; -/// -/// let d = Bernoulli::new(0.3); -/// let v = d.sample(&mut rand::thread_rng()); -/// println!("{} is from a Bernoulli distribution", v); -/// ``` -/// -/// # Precision -/// -/// This `Bernoulli` distribution uses 64 bits from the RNG (a `u64`), -/// so only probabilities that are multiples of 2<sup>-64</sup> can be -/// represented. -#[derive(Clone, Copy, Debug)] -pub struct Bernoulli { - /// Probability of success, relative to the maximal integer. - p_int: u64, -} - -// To sample from the Bernoulli distribution we use a method that compares a -// random `u64` value `v < (p * 2^64)`. -// -// If `p == 1.0`, the integer `v` to compare against can not represented as a -// `u64`. We manually set it to `u64::MAX` instead (2^64 - 1 instead of 2^64). -// Note that value of `p < 1.0` can never result in `u64::MAX`, because an -// `f64` only has 53 bits of precision, and the next largest value of `p` will -// result in `2^64 - 2048`. -// -// Also there is a 100% theoretical concern: if someone consistenly wants to -// generate `true` using the Bernoulli distribution (i.e. by using a probability -// of `1.0`), just using `u64::MAX` is not enough. On average it would return -// false once every 2^64 iterations. Some people apparently care about this -// case. -// -// That is why we special-case `u64::MAX` to always return `true`, without using -// the RNG, and pay the performance price for all uses that *are* reasonable. -// Luckily, if `new()` and `sample` are close, the compiler can optimize out the -// extra check. -const ALWAYS_TRUE: u64 = ::core::u64::MAX; - -// This is just `2.0.powi(64)`, but written this way because it is not available -// in `no_std` mode. -const SCALE: f64 = 2.0 * (1u64 << 63) as f64; - -impl Bernoulli { - /// Construct a new `Bernoulli` with the given probability of success `p`. - /// - /// # Panics - /// - /// If `p < 0` or `p > 1`. - /// - /// # Precision - /// - /// For `p = 1.0`, the resulting distribution will always generate true. - /// For `p = 0.0`, the resulting distribution will always generate false. - /// - /// This method is accurate for any input `p` in the range `[0, 1]` which is - /// a multiple of 2<sup>-64</sup>. (Note that not all multiples of - /// 2<sup>-64</sup> in `[0, 1]` can be represented as a `f64`.) - #[inline] - pub fn new(p: f64) -> Bernoulli { - if p < 0.0 || p >= 1.0 { - if p == 1.0 { return Bernoulli { p_int: ALWAYS_TRUE } } - panic!("Bernoulli::new not called with 0.0 <= p <= 1.0"); - } - Bernoulli { p_int: (p * SCALE) as u64 } - } - - /// Construct a new `Bernoulli` with the probability of success of - /// `numerator`-in-`denominator`. I.e. `new_ratio(2, 3)` will return - /// a `Bernoulli` with a 2-in-3 chance, or about 67%, of returning `true`. - /// - /// If `numerator == denominator` then the returned `Bernoulli` will always - /// return `true`. If `numerator == 0` it will always return `false`. - /// - /// # Panics - /// - /// If `denominator == 0` or `numerator > denominator`. - /// - #[inline] - pub fn from_ratio(numerator: u32, denominator: u32) -> Bernoulli { - assert!(numerator <= denominator); - if numerator == denominator { - return Bernoulli { p_int: ::core::u64::MAX } - } - let p_int = ((numerator as f64 / denominator as f64) * SCALE) as u64; - Bernoulli { p_int } - } -} - -impl Distribution<bool> for Bernoulli { - #[inline] - fn sample<R: Rng + ?Sized>(&self, rng: &mut R) -> bool { - // Make sure to always return true for p = 1.0. - if self.p_int == ALWAYS_TRUE { return true; } - let v: u64 = rng.gen(); - v < self.p_int - } -} - -#[cfg(test)] -mod test { - use Rng; - use distributions::Distribution; - use super::Bernoulli; - - #[test] - fn test_trivial() { - let mut r = ::test::rng(1); - let always_false = Bernoulli::new(0.0); - let always_true = Bernoulli::new(1.0); - for _ in 0..5 { - assert_eq!(r.sample::<bool, _>(&always_false), false); - assert_eq!(r.sample::<bool, _>(&always_true), true); - assert_eq!(Distribution::<bool>::sample(&always_false, &mut r), false); - assert_eq!(Distribution::<bool>::sample(&always_true, &mut r), true); - } - } - - #[test] - fn test_average() { - const P: f64 = 0.3; - const NUM: u32 = 3; - const DENOM: u32 = 10; - let d1 = Bernoulli::new(P); - let d2 = Bernoulli::from_ratio(NUM, DENOM); - const N: u32 = 100_000; - - let mut sum1: u32 = 0; - let mut sum2: u32 = 0; - let mut rng = ::test::rng(2); - for _ in 0..N { - if d1.sample(&mut rng) { - sum1 += 1; - } - if d2.sample(&mut rng) { - sum2 += 1; - } - } - let avg1 = (sum1 as f64) / (N as f64); - assert!((avg1 - P).abs() < 5e-3); - - let avg2 = (sum2 as f64) / (N as f64); - assert!((avg2 - (NUM as f64)/(DENOM as f64)).abs() < 5e-3); - } -} diff --git a/rand/src/distributions/binomial.rs b/rand/src/distributions/binomial.rs deleted file mode 100644 index 2df393e..0000000 --- a/rand/src/distributions/binomial.rs +++ /dev/null @@ -1,177 +0,0 @@ -// Copyright 2018 Developers of the Rand project. -// Copyright 2016-2017 The Rust Project Developers. -// -// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or -// https://www.apache.org/licenses/LICENSE-2.0> or the MIT license -// <LICENSE-MIT or https://opensource.org/licenses/MIT>, at your -// option. This file may not be copied, modified, or distributed -// except according to those terms. - -//! The binomial distribution. - -use Rng; -use distributions::{Distribution, Bernoulli, Cauchy}; -use distributions::utils::log_gamma; - -/// The binomial distribution `Binomial(n, p)`. -/// -/// This distribution has density function: -/// `f(k) = n!/(k! (n-k)!) p^k (1-p)^(n-k)` for `k >= 0`. -/// -/// # Example -/// -/// ``` -/// use rand::distributions::{Binomial, Distribution}; -/// -/// let bin = Binomial::new(20, 0.3); -/// let v = bin.sample(&mut rand::thread_rng()); -/// println!("{} is from a binomial distribution", v); -/// ``` -#[derive(Clone, Copy, Debug)] -pub struct Binomial { - /// Number of trials. - n: u64, - /// Probability of success. - p: f64, -} - -impl Binomial { - /// Construct a new `Binomial` with the given shape parameters `n` (number - /// of trials) and `p` (probability of success). - /// - /// Panics if `p < 0` or `p > 1`. - pub fn new(n: u64, p: f64) -> Binomial { - assert!(p >= 0.0, "Binomial::new called with p < 0"); - assert!(p <= 1.0, "Binomial::new called with p > 1"); - Binomial { n, p } - } -} - -impl Distribution<u64> for Binomial { - fn sample<R: Rng + ?Sized>(&self, rng: &mut R) -> u64 { - // Handle these values directly. - if self.p == 0.0 { - return 0; - } else if self.p == 1.0 { - return self.n; - } - - // For low n, it is faster to sample directly. For both methods, - // performance is independent of p. On Intel Haswell CPU this method - // appears to be faster for approx n < 300. - if self.n < 300 { - let mut result = 0; - let d = Bernoulli::new(self.p); - for _ in 0 .. self.n { - result += rng.sample(d) as u32; - } - return result as u64; - } - - // binomial distribution is symmetrical with respect to p -> 1-p, k -> n-k - // switch p so that it is less than 0.5 - this allows for lower expected values - // we will just invert the result at the end - let p = if self.p <= 0.5 { - self.p - } else { - 1.0 - self.p - }; - - // prepare some cached values - let float_n = self.n as f64; - let ln_fact_n = log_gamma(float_n + 1.0); - let pc = 1.0 - p; - let log_p = p.ln(); - let log_pc = pc.ln(); - let expected = self.n as f64 * p; - let sq = (expected * (2.0 * pc)).sqrt(); - - let mut lresult; - - // we use the Cauchy distribution as the comparison distribution - // f(x) ~ 1/(1+x^2) - let cauchy = Cauchy::new(0.0, 1.0); - loop { - let mut comp_dev: f64; - loop { - // draw from the Cauchy distribution - comp_dev = rng.sample(cauchy); - // shift the peak of the comparison ditribution - lresult = expected + sq * comp_dev; - // repeat the drawing until we are in the range of possible values - if lresult >= 0.0 && lresult < float_n + 1.0 { - break; - } - } - - // the result should be discrete - lresult = lresult.floor(); - - let log_binomial_dist = ln_fact_n - log_gamma(lresult+1.0) - - log_gamma(float_n - lresult + 1.0) + lresult*log_p + (float_n - lresult)*log_pc; - // this is the binomial probability divided by the comparison probability - // we will generate a uniform random value and if it is larger than this, - // we interpret it as a value falling out of the distribution and repeat - let comparison_coeff = (log_binomial_dist.exp() * sq) * (1.2 * (1.0 + comp_dev*comp_dev)); - - if comparison_coeff >= rng.gen() { - break; - } - } - - // invert the result for p < 0.5 - if p != self.p { - self.n - lresult as u64 - } else { - lresult as u64 - } - } -} - -#[cfg(test)] -mod test { - use Rng; - use distributions::Distribution; - use super::Binomial; - - fn test_binomial_mean_and_variance<R: Rng>(n: u64, p: f64, rng: &mut R) { - let binomial = Binomial::new(n, p); - - let expected_mean = n as f64 * p; - let expected_variance = n as f64 * p * (1.0 - p); - - let mut results = [0.0; 1000]; - for i in results.iter_mut() { *i = binomial.sample(rng) as f64; } - - let mean = results.iter().sum::<f64>() / results.len() as f64; - assert!((mean as f64 - expected_mean).abs() < expected_mean / 50.0); - - let variance = - results.iter().map(|x| (x - mean) * (x - mean)).sum::<f64>() - / results.len() as f64; - assert!((variance - expected_variance).abs() < expected_variance / 10.0); - } - - #[test] - fn test_binomial() { - let mut rng = ::test::rng(351); - test_binomial_mean_and_variance(150, 0.1, &mut rng); - test_binomial_mean_and_variance(70, 0.6, &mut rng); - test_binomial_mean_and_variance(40, 0.5, &mut rng); - test_binomial_mean_and_variance(20, 0.7, &mut rng); - test_binomial_mean_and_variance(20, 0.5, &mut rng); - } - - #[test] - fn test_binomial_end_points() { - let mut rng = ::test::rng(352); - assert_eq!(rng.sample(Binomial::new(20, 0.0)), 0); - assert_eq!(rng.sample(Binomial::new(20, 1.0)), 20); - } - - #[test] - #[should_panic] - fn test_binomial_invalid_lambda_neg() { - Binomial::new(20, -10.0); - } -} diff --git a/rand/src/distributions/cauchy.rs b/rand/src/distributions/cauchy.rs deleted file mode 100644 index feef015..0000000 --- a/rand/src/distributions/cauchy.rs +++ /dev/null @@ -1,115 +0,0 @@ -// Copyright 2018 Developers of the Rand project. -// Copyright 2016-2017 The Rust Project Developers. -// -// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or -// https://www.apache.org/licenses/LICENSE-2.0> or the MIT license -// <LICENSE-MIT or https://opensource.org/licenses/MIT>, at your -// option. This file may not be copied, modified, or distributed -// except according to those terms. - -//! The Cauchy distribution. - -use Rng; -use distributions::Distribution; -use std::f64::consts::PI; - -/// The Cauchy distribution `Cauchy(median, scale)`. -/// -/// This distribution has a density function: -/// `f(x) = 1 / (pi * scale * (1 + ((x - median) / scale)^2))` -/// -/// # Example -/// -/// ``` -/// use rand::distributions::{Cauchy, Distribution}; -/// -/// let cau = Cauchy::new(2.0, 5.0); -/// let v = cau.sample(&mut rand::thread_rng()); -/// println!("{} is from a Cauchy(2, 5) distribution", v); -/// ``` -#[derive(Clone, Copy, Debug)] -pub struct Cauchy { - median: f64, - scale: f64 -} - -impl Cauchy { - /// Construct a new `Cauchy` with the given shape parameters - /// `median` the peak location and `scale` the scale factor. - /// Panics if `scale <= 0`. - pub fn new(median: f64, scale: f64) -> Cauchy { - assert!(scale > 0.0, "Cauchy::new called with scale factor <= 0"); - Cauchy { - median, - scale - } - } -} - -impl Distribution<f64> for Cauchy { - fn sample<R: Rng + ?Sized>(&self, rng: &mut R) -> f64 { - // sample from [0, 1) - let x = rng.gen::<f64>(); - // get standard cauchy random number - // note that π/2 is not exactly representable, even if x=0.5 the result is finite - let comp_dev = (PI * x).tan(); - // shift and scale according to parameters - let result = self.median + self.scale * comp_dev; - result - } -} - -#[cfg(test)] -mod test { - use distributions::Distribution; - use super::Cauchy; - - fn median(mut numbers: &mut [f64]) -> f64 { - sort(&mut numbers); - let mid = numbers.len() / 2; - numbers[mid] - } - - fn sort(numbers: &mut [f64]) { - numbers.sort_by(|a, b| a.partial_cmp(b).unwrap()); - } - - #[test] - fn test_cauchy_median() { - let cauchy = Cauchy::new(10.0, 5.0); - let mut rng = ::test::rng(123); - let mut numbers: [f64; 1000] = [0.0; 1000]; - for i in 0..1000 { - numbers[i] = cauchy.sample(&mut rng); - } - let median = median(&mut numbers); - println!("Cauchy median: {}", median); - assert!((median - 10.0).abs() < 0.5); // not 100% certain, but probable enough - } - - #[test] - fn test_cauchy_mean() { - let cauchy = Cauchy::new(10.0, 5.0); - let mut rng = ::test::rng(123); - let mut sum = 0.0; - for _ in 0..1000 { - sum += cauchy.sample(&mut rng); - } - let mean = sum / 1000.0; - println!("Cauchy mean: {}", mean); - // for a Cauchy distribution the mean should not converge - assert!((mean - 10.0).abs() > 0.5); // not 100% certain, but probable enough - } - - #[test] - #[should_panic] - fn test_cauchy_invalid_scale_zero() { - Cauchy::new(0.0, 0.0); - } - - #[test] - #[should_panic] - fn test_cauchy_invalid_scale_neg() { - Cauchy::new(0.0, -10.0); - } -} diff --git a/rand/src/distributions/dirichlet.rs b/rand/src/distributions/dirichlet.rs deleted file mode 100644 index 19384b8..0000000 --- a/rand/src/distributions/dirichlet.rs +++ /dev/null @@ -1,137 +0,0 @@ -// Copyright 2018 Developers of the Rand project. -// Copyright 2013 The Rust Project Developers. -// -// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or -// https://www.apache.org/licenses/LICENSE-2.0> or the MIT license -// <LICENSE-MIT or https://opensource.org/licenses/MIT>, at your -// option. This file may not be copied, modified, or distributed -// except according to those terms. - -//! The dirichlet distribution. - -use Rng; -use distributions::Distribution; -use distributions::gamma::Gamma; - -/// The dirichelet distribution `Dirichlet(alpha)`. -/// -/// The Dirichlet distribution is a family of continuous multivariate -/// probability distributions parameterized by a vector alpha of positive reals. -/// It is a multivariate generalization of the beta distribution. -/// -/// # Example -/// -/// ``` -/// use rand::prelude::*; -/// use rand::distributions::Dirichlet; -/// -/// let dirichlet = Dirichlet::new(vec![1.0, 2.0, 3.0]); -/// let samples = dirichlet.sample(&mut rand::thread_rng()); -/// println!("{:?} is from a Dirichlet([1.0, 2.0, 3.0]) distribution", samples); -/// ``` - -#[derive(Clone, Debug)] -pub struct Dirichlet { - /// Concentration parameters (alpha) - alpha: Vec<f64>, -} - -impl Dirichlet { - /// Construct a new `Dirichlet` with the given alpha parameter `alpha`. - /// - /// # Panics - /// - if `alpha.len() < 2` - /// - #[inline] - pub fn new<V: Into<Vec<f64>>>(alpha: V) -> Dirichlet { - let a = alpha.into(); - assert!(a.len() > 1); - for i in 0..a.len() { - assert!(a[i] > 0.0); - } - - Dirichlet { alpha: a } - } - - /// Construct a new `Dirichlet` with the given shape parameter `alpha` and `size`. - /// - /// # Panics - /// - if `alpha <= 0.0` - /// - if `size < 2` - /// - #[inline] - pub fn new_with_param(alpha: f64, size: usize) -> Dirichlet { - assert!(alpha > 0.0); - assert!(size > 1); - Dirichlet { - alpha: vec![alpha; size], - } - } -} - -impl Distribution<Vec<f64>> for Dirichlet { - fn sample<R: Rng + ?Sized>(&self, rng: &mut R) -> Vec<f64> { - let n = self.alpha.len(); - let mut samples = vec![0.0f64; n]; - let mut sum = 0.0f64; - - for i in 0..n { - let g = Gamma::new(self.alpha[i], 1.0); - samples[i] = g.sample(rng); - sum += samples[i]; - } - let invacc = 1.0 / sum; - for i in 0..n { - samples[i] *= invacc; - } - samples - } -} - -#[cfg(test)] -mod test { - use super::Dirichlet; - use distributions::Distribution; - - #[test] - fn test_dirichlet() { - let d = Dirichlet::new(vec![1.0, 2.0, 3.0]); - let mut rng = ::test::rng(221); - let samples = d.sample(&mut rng); - let _: Vec<f64> = samples - .into_iter() - .map(|x| { - assert!(x > 0.0); - x - }) - .collect(); - } - - #[test] - fn test_dirichlet_with_param() { - let alpha = 0.5f64; - let size = 2; - let d = Dirichlet::new_with_param(alpha, size); - let mut rng = ::test::rng(221); - let samples = d.sample(&mut rng); - let _: Vec<f64> = samples - .into_iter() - .map(|x| { - assert!(x > 0.0); - x - }) - .collect(); - } - - #[test] - #[should_panic] - fn test_dirichlet_invalid_length() { - Dirichlet::new_with_param(0.5f64, 1); - } - - #[test] - #[should_panic] - fn test_dirichlet_invalid_alpha() { - Dirichlet::new_with_param(0.0f64, 2); - } -} diff --git a/rand/src/distributions/exponential.rs b/rand/src/distributions/exponential.rs deleted file mode 100644 index a7d0500..0000000 --- a/rand/src/distributions/exponential.rs +++ /dev/null @@ -1,124 +0,0 @@ -// Copyright 2018 Developers of the Rand project. -// Copyright 2013 The Rust Project Developers. -// -// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or -// https://www.apache.org/licenses/LICENSE-2.0> or the MIT license -// <LICENSE-MIT or https://opensource.org/licenses/MIT>, at your -// option. This file may not be copied, modified, or distributed -// except according to those terms. - -//! The exponential distribution. - -use {Rng}; -use distributions::{ziggurat_tables, Distribution}; -use distributions::utils::ziggurat; - -/// Samples floating-point numbers according to the exponential distribution, -/// with rate parameter `λ = 1`. This is equivalent to `Exp::new(1.0)` or -/// sampling with `-rng.gen::<f64>().ln()`, but faster. -/// -/// See `Exp` for the general exponential distribution. -/// -/// Implemented via the ZIGNOR variant[^1] of the Ziggurat method. The exact -/// description in the paper was adjusted to use tables for the exponential -/// distribution rather than normal. -/// -/// [^1]: Jurgen A. Doornik (2005). [*An Improved Ziggurat Method to -/// Generate Normal Random Samples*]( -/// https://www.doornik.com/research/ziggurat.pdf). -/// Nuffield College, Oxford -/// -/// # Example -/// ``` -/// use rand::prelude::*; -/// use rand::distributions::Exp1; -/// -/// let val: f64 = SmallRng::from_entropy().sample(Exp1); -/// println!("{}", val); -/// ``` -#[derive(Clone, Copy, Debug)] -pub struct Exp1; - -// This could be done via `-rng.gen::<f64>().ln()` but that is slower. -impl Distribution<f64> for Exp1 { - #[inline] - fn sample<R: Rng + ?Sized>(&self, rng: &mut R) -> f64 { - #[inline] - fn pdf(x: f64) -> f64 { - (-x).exp() - } - #[inline] - fn zero_case<R: Rng + ?Sized>(rng: &mut R, _u: f64) -> f64 { - ziggurat_tables::ZIG_EXP_R - rng.gen::<f64>().ln() - } - - ziggurat(rng, false, - &ziggurat_tables::ZIG_EXP_X, - &ziggurat_tables::ZIG_EXP_F, - pdf, zero_case) - } -} - -/// The exponential distribution `Exp(lambda)`. -/// -/// This distribution has density function: `f(x) = lambda * exp(-lambda * x)` -/// for `x > 0`. -/// -/// Note that [`Exp1`](struct.Exp1.html) is an optimised implementation for `lambda = 1`. -/// -/// # Example -/// -/// ``` -/// use rand::distributions::{Exp, Distribution}; -/// -/// let exp = Exp::new(2.0); -/// let v = exp.sample(&mut rand::thread_rng()); -/// println!("{} is from a Exp(2) distribution", v); -/// ``` -#[derive(Clone, Copy, Debug)] -pub struct Exp { - /// `lambda` stored as `1/lambda`, since this is what we scale by. - lambda_inverse: f64 -} - -impl Exp { - /// Construct a new `Exp` with the given shape parameter - /// `lambda`. Panics if `lambda <= 0`. - #[inline] - pub fn new(lambda: f64) -> Exp { - assert!(lambda > 0.0, "Exp::new called with `lambda` <= 0"); - Exp { lambda_inverse: 1.0 / lambda } - } -} - -impl Distribution<f64> for Exp { - fn sample<R: Rng + ?Sized>(&self, rng: &mut R) -> f64 { - let n: f64 = rng.sample(Exp1); - n * self.lambda_inverse - } -} - -#[cfg(test)] -mod test { - use distributions::Distribution; - use super::Exp; - - #[test] - fn test_exp() { - let exp = Exp::new(10.0); - let mut rng = ::test::rng(221); - for _ in 0..1000 { - assert!(exp.sample(&mut rng) >= 0.0); - } - } - #[test] - #[should_panic] - fn test_exp_invalid_lambda_zero() { - Exp::new(0.0); - } - #[test] - #[should_panic] - fn test_exp_invalid_lambda_neg() { - Exp::new(-10.0); - } -} diff --git a/rand/src/distributions/float.rs b/rand/src/distributions/float.rs deleted file mode 100644 index ece12f5..0000000 --- a/rand/src/distributions/float.rs +++ /dev/null @@ -1,259 +0,0 @@ -// Copyright 2018 Developers of the Rand project. -// -// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or -// https://www.apache.org/licenses/LICENSE-2.0> or the MIT license -// <LICENSE-MIT or https://opensource.org/licenses/MIT>, at your -// option. This file may not be copied, modified, or distributed -// except according to those terms. - -//! Basic floating-point number distributions - -use core::mem; -use Rng; -use distributions::{Distribution, Standard}; -use distributions::utils::FloatSIMDUtils; -#[cfg(feature="simd_support")] -use packed_simd::*; - -/// A distribution to sample floating point numbers uniformly in the half-open -/// interval `(0, 1]`, i.e. including 1 but not 0. -/// -/// All values that can be generated are of the form `n * ε/2`. For `f32` -/// the 23 most significant random bits of a `u32` are used and for `f64` the -/// 53 most significant bits of a `u64` are used. The conversion uses the -/// multiplicative method. -/// -/// See also: [`Standard`] which samples from `[0, 1)`, [`Open01`] -/// which samples from `(0, 1)` and [`Uniform`] which samples from arbitrary -/// ranges. -/// -/// # Example -/// ``` -/// use rand::{thread_rng, Rng}; -/// use rand::distributions::OpenClosed01; -/// -/// let val: f32 = thread_rng().sample(OpenClosed01); -/// println!("f32 from (0, 1): {}", val); -/// ``` -/// -/// [`Standard`]: struct.Standard.html -/// [`Open01`]: struct.Open01.html -/// [`Uniform`]: uniform/struct.Uniform.html -#[derive(Clone, Copy, Debug)] -pub struct OpenClosed01; - -/// A distribution to sample floating point numbers uniformly in the open -/// interval `(0, 1)`, i.e. not including either endpoint. -/// -/// All values that can be generated are of the form `n * ε + ε/2`. For `f32` -/// the 22 most significant random bits of an `u32` are used, for `f64` 52 from -/// an `u64`. The conversion uses a transmute-based method. -/// -/// See also: [`Standard`] which samples from `[0, 1)`, [`OpenClosed01`] -/// which samples from `(0, 1]` and [`Uniform`] which samples from arbitrary -/// ranges. -/// -/// # Example -/// ``` -/// use rand::{thread_rng, Rng}; -/// use rand::distributions::Open01; -/// -/// let val: f32 = thread_rng().sample(Open01); -/// println!("f32 from (0, 1): {}", val); -/// ``` -/// -/// [`Standard`]: struct.Standard.html -/// [`OpenClosed01`]: struct.OpenClosed01.html -/// [`Uniform`]: uniform/struct.Uniform.html -#[derive(Clone, Copy, Debug)] -pub struct Open01; - - -pub(crate) trait IntoFloat { - type F; - - /// Helper method to combine the fraction and a contant exponent into a - /// float. - /// - /// Only the least significant bits of `self` may be set, 23 for `f32` and - /// 52 for `f64`. - /// The resulting value will fall in a range that depends on the exponent. - /// As an example the range with exponent 0 will be - /// [2<sup>0</sup>..2<sup>1</sup>), which is [1..2). - fn into_float_with_exponent(self, exponent: i32) -> Self::F; -} - -macro_rules! float_impls { - ($ty:ident, $uty:ident, $f_scalar:ident, $u_scalar:ty, - $fraction_bits:expr, $exponent_bias:expr) => { - impl IntoFloat for $uty { - type F = $ty; - #[inline(always)] - fn into_float_with_exponent(self, exponent: i32) -> $ty { - // The exponent is encoded using an offset-binary representation - let exponent_bits: $u_scalar = - (($exponent_bias + exponent) as $u_scalar) << $fraction_bits; - // TODO: use from_bits when min compiler > 1.25 (see #545) - // $ty::from_bits(self | exponent_bits) - unsafe{ mem::transmute(self | exponent_bits) } - } - } - - impl Distribution<$ty> for Standard { - fn sample<R: Rng + ?Sized>(&self, rng: &mut R) -> $ty { - // Multiply-based method; 24/53 random bits; [0, 1) interval. - // We use the most significant bits because for simple RNGs - // those are usually more random. - let float_size = mem::size_of::<$f_scalar>() as u32 * 8; - let precision = $fraction_bits + 1; - let scale = 1.0 / ((1 as $u_scalar << precision) as $f_scalar); - - let value: $uty = rng.gen(); - let value = value >> (float_size - precision); - scale * $ty::cast_from_int(value) - } - } - - impl Distribution<$ty> for OpenClosed01 { - fn sample<R: Rng + ?Sized>(&self, rng: &mut R) -> $ty { - // Multiply-based method; 24/53 random bits; (0, 1] interval. - // We use the most significant bits because for simple RNGs - // those are usually more random. - let float_size = mem::size_of::<$f_scalar>() as u32 * 8; - let precision = $fraction_bits + 1; - let scale = 1.0 / ((1 as $u_scalar << precision) as $f_scalar); - - let value: $uty = rng.gen(); - let value = value >> (float_size - precision); - // Add 1 to shift up; will not overflow because of right-shift: - scale * $ty::cast_from_int(value + 1) - } - } - - impl Distribution<$ty> for Open01 { - fn sample<R: Rng + ?Sized>(&self, rng: &mut R) -> $ty { - // Transmute-based method; 23/52 random bits; (0, 1) interval. - // We use the most significant bits because for simple RNGs - // those are usually more random. - use core::$f_scalar::EPSILON; - let float_size = mem::size_of::<$f_scalar>() as u32 * 8; - - let value: $uty = rng.gen(); - let fraction = value >> (float_size - $fraction_bits); - fraction.into_float_with_exponent(0) - (1.0 - EPSILON / 2.0) - } - } - } -} - -float_impls! { f32, u32, f32, u32, 23, 127 } -float_impls! { f64, u64, f64, u64, 52, 1023 } - -#[cfg(feature="simd_support")] -float_impls! { f32x2, u32x2, f32, u32, 23, 127 } -#[cfg(feature="simd_support")] -float_impls! { f32x4, u32x4, f32, u32, 23, 127 } -#[cfg(feature="simd_support")] -float_impls! { f32x8, u32x8, f32, u32, 23, 127 } -#[cfg(feature="simd_support")] -float_impls! { f32x16, u32x16, f32, u32, 23, 127 } - -#[cfg(feature="simd_support")] -float_impls! { f64x2, u64x2, f64, u64, 52, 1023 } -#[cfg(feature="simd_support")] -float_impls! { f64x4, u64x4, f64, u64, 52, 1023 } -#[cfg(feature="simd_support")] -float_impls! { f64x8, u64x8, f64, u64, 52, 1023 } - - -#[cfg(test)] -mod tests { - use Rng; - use distributions::{Open01, OpenClosed01}; - use rngs::mock::StepRng; - #[cfg(feature="simd_support")] - use packed_simd::*; - - const EPSILON32: f32 = ::core::f32::EPSILON; - const EPSILON64: f64 = ::core::f64::EPSILON; - - macro_rules! test_f32 { - ($fnn:ident, $ty:ident, $ZERO:expr, $EPSILON:expr) => { - #[test] - fn $fnn() { - // Standard - let mut zeros = StepRng::new(0, 0); - assert_eq!(zeros.gen::<$ty>(), $ZERO); - let mut one = StepRng::new(1 << 8 | 1 << (8 + 32), 0); - assert_eq!(one.gen::<$ty>(), $EPSILON / 2.0); - let mut max = StepRng::new(!0, 0); - assert_eq!(max.gen::<$ty>(), 1.0 - $EPSILON / 2.0); - - // OpenClosed01 - let mut zeros = StepRng::new(0, 0); - assert_eq!(zeros.sample::<$ty, _>(OpenClosed01), - 0.0 + $EPSILON / 2.0); - let mut one = StepRng::new(1 << 8 | 1 << (8 + 32), 0); - assert_eq!(one.sample::<$ty, _>(OpenClosed01), $EPSILON); - let mut max = StepRng::new(!0, 0); - assert_eq!(max.sample::<$ty, _>(OpenClosed01), $ZERO + 1.0); - - // Open01 - let mut zeros = StepRng::new(0, 0); - assert_eq!(zeros.sample::<$ty, _>(Open01), 0.0 + $EPSILON / 2.0); - let mut one = StepRng::new(1 << 9 | 1 << (9 + 32), 0); - assert_eq!(one.sample::<$ty, _>(Open01), $EPSILON / 2.0 * 3.0); - let mut max = StepRng::new(!0, 0); - assert_eq!(max.sample::<$ty, _>(Open01), 1.0 - $EPSILON / 2.0); - } - } - } - test_f32! { f32_edge_cases, f32, 0.0, EPSILON32 } - #[cfg(feature="simd_support")] - test_f32! { f32x2_edge_cases, f32x2, f32x2::splat(0.0), f32x2::splat(EPSILON32) } - #[cfg(feature="simd_support")] - test_f32! { f32x4_edge_cases, f32x4, f32x4::splat(0.0), f32x4::splat(EPSILON32) } - #[cfg(feature="simd_support")] - test_f32! { f32x8_edge_cases, f32x8, f32x8::splat(0.0), f32x8::splat(EPSILON32) } - #[cfg(feature="simd_support")] - test_f32! { f32x16_edge_cases, f32x16, f32x16::splat(0.0), f32x16::splat(EPSILON32) } - - macro_rules! test_f64 { - ($fnn:ident, $ty:ident, $ZERO:expr, $EPSILON:expr) => { - #[test] - fn $fnn() { - // Standard - let mut zeros = StepRng::new(0, 0); - assert_eq!(zeros.gen::<$ty>(), $ZERO); - let mut one = StepRng::new(1 << 11, 0); - assert_eq!(one.gen::<$ty>(), $EPSILON / 2.0); - let mut max = StepRng::new(!0, 0); - assert_eq!(max.gen::<$ty>(), 1.0 - $EPSILON / 2.0); - - // OpenClosed01 - let mut zeros = StepRng::new(0, 0); - assert_eq!(zeros.sample::<$ty, _>(OpenClosed01), - 0.0 + $EPSILON / 2.0); - let mut one = StepRng::new(1 << 11, 0); - assert_eq!(one.sample::<$ty, _>(OpenClosed01), $EPSILON); - let mut max = StepRng::new(!0, 0); - assert_eq!(max.sample::<$ty, _>(OpenClosed01), $ZERO + 1.0); - - // Open01 - let mut zeros = StepRng::new(0, 0); - assert_eq!(zeros.sample::<$ty, _>(Open01), 0.0 + $EPSILON / 2.0); - let mut one = StepRng::new(1 << 12, 0); - assert_eq!(one.sample::<$ty, _>(Open01), $EPSILON / 2.0 * 3.0); - let mut max = StepRng::new(!0, 0); - assert_eq!(max.sample::<$ty, _>(Open01), 1.0 - $EPSILON / 2.0); - } - } - } - test_f64! { f64_edge_cases, f64, 0.0, EPSILON64 } - #[cfg(feature="simd_support")] - test_f64! { f64x2_edge_cases, f64x2, f64x2::splat(0.0), f64x2::splat(EPSILON64) } - #[cfg(feature="simd_support")] - test_f64! { f64x4_edge_cases, f64x4, f64x4::splat(0.0), f64x4::splat(EPSILON64) } - #[cfg(feature="simd_support")] - test_f64! { f64x8_edge_cases, f64x8, f64x8::splat(0.0), f64x8::splat(EPSILON64) } -} diff --git a/rand/src/distributions/gamma.rs b/rand/src/distributions/gamma.rs deleted file mode 100644 index 43ac2bc..0000000 --- a/rand/src/distributions/gamma.rs +++ /dev/null @@ -1,413 +0,0 @@ -// Copyright 2018 Developers of the Rand project. -// Copyright 2013 The Rust Project Developers. -// -// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or -// https://www.apache.org/licenses/LICENSE-2.0> or the MIT license -// <LICENSE-MIT or https://opensource.org/licenses/MIT>, at your -// option. This file may not be copied, modified, or distributed -// except according to those terms. - -//! The Gamma and derived distributions. - -use self::GammaRepr::*; -use self::ChiSquaredRepr::*; - -use Rng; -use distributions::normal::StandardNormal; -use distributions::{Distribution, Exp, Open01}; - -/// The Gamma distribution `Gamma(shape, scale)` distribution. -/// -/// The density function of this distribution is -/// -/// ```text -/// f(x) = x^(k - 1) * exp(-x / θ) / (Γ(k) * θ^k) -/// ``` -/// -/// where `Γ` is the Gamma function, `k` is the shape and `θ` is the -/// scale and both `k` and `θ` are strictly positive. -/// -/// The algorithm used is that described by Marsaglia & Tsang 2000[^1], -/// falling back to directly sampling from an Exponential for `shape -/// == 1`, and using the boosting technique described in that paper for -/// `shape < 1`. -/// -/// # Example -/// -/// ``` -/// use rand::distributions::{Distribution, Gamma}; -/// -/// let gamma = Gamma::new(2.0, 5.0); -/// let v = gamma.sample(&mut rand::thread_rng()); -/// println!("{} is from a Gamma(2, 5) distribution", v); -/// ``` -/// -/// [^1]: George Marsaglia and Wai Wan Tsang. 2000. "A Simple Method for -/// Generating Gamma Variables" *ACM Trans. Math. Softw.* 26, 3 -/// (September 2000), 363-372. -/// DOI:[10.1145/358407.358414](https://doi.acm.org/10.1145/358407.358414) -#[derive(Clone, Copy, Debug)] -pub struct Gamma { - repr: GammaRepr, -} - -#[derive(Clone, Copy, Debug)] -enum GammaRepr { - Large(GammaLargeShape), - One(Exp), - Small(GammaSmallShape) -} - -// These two helpers could be made public, but saving the -// match-on-Gamma-enum branch from using them directly (e.g. if one -// knows that the shape is always > 1) doesn't appear to be much -// faster. - -/// Gamma distribution where the shape parameter is less than 1. -/// -/// Note, samples from this require a compulsory floating-point `pow` -/// call, which makes it significantly slower than sampling from a -/// gamma distribution where the shape parameter is greater than or -/// equal to 1. -/// -/// See `Gamma` for sampling from a Gamma distribution with general -/// shape parameters. -#[derive(Clone, Copy, Debug)] -struct GammaSmallShape { - inv_shape: f64, - large_shape: GammaLargeShape -} - -/// Gamma distribution where the shape parameter is larger than 1. -/// -/// See `Gamma` for sampling from a Gamma distribution with general -/// shape parameters. -#[derive(Clone, Copy, Debug)] -struct GammaLargeShape { - scale: f64, - c: f64, - d: f64 -} - -impl Gamma { - /// Construct an object representing the `Gamma(shape, scale)` - /// distribution. - /// - /// Panics if `shape <= 0` or `scale <= 0`. - #[inline] - pub fn new(shape: f64, scale: f64) -> Gamma { - assert!(shape > 0.0, "Gamma::new called with shape <= 0"); - assert!(scale > 0.0, "Gamma::new called with scale <= 0"); - - let repr = if shape == 1.0 { - One(Exp::new(1.0 / scale)) - } else if shape < 1.0 { - Small(GammaSmallShape::new_raw(shape, scale)) - } else { - Large(GammaLargeShape::new_raw(shape, scale)) - }; - Gamma { repr } - } -} - -impl GammaSmallShape { - fn new_raw(shape: f64, scale: f64) -> GammaSmallShape { - GammaSmallShape { - inv_shape: 1. / shape, - large_shape: GammaLargeShape::new_raw(shape + 1.0, scale) - } - } -} - -impl GammaLargeShape { - fn new_raw(shape: f64, scale: f64) -> GammaLargeShape { - let d = shape - 1. / 3.; - GammaLargeShape { - scale, - c: 1. / (9. * d).sqrt(), - d - } - } -} - -impl Distribution<f64> for Gamma { - fn sample<R: Rng + ?Sized>(&self, rng: &mut R) -> f64 { - match self.repr { - Small(ref g) => g.sample(rng), - One(ref g) => g.sample(rng), - Large(ref g) => g.sample(rng), - } - } -} -impl Distribution<f64> for GammaSmallShape { - fn sample<R: Rng + ?Sized>(&self, rng: &mut R) -> f64 { - let u: f64 = rng.sample(Open01); - - self.large_shape.sample(rng) * u.powf(self.inv_shape) - } -} -impl Distribution<f64> for GammaLargeShape { - fn sample<R: Rng + ?Sized>(&self, rng: &mut R) -> f64 { - loop { - let x = rng.sample(StandardNormal); - let v_cbrt = 1.0 + self.c * x; - if v_cbrt <= 0.0 { // a^3 <= 0 iff a <= 0 - continue - } - - let v = v_cbrt * v_cbrt * v_cbrt; - let u: f64 = rng.sample(Open01); - - let x_sqr = x * x; - if u < 1.0 - 0.0331 * x_sqr * x_sqr || - u.ln() < 0.5 * x_sqr + self.d * (1.0 - v + v.ln()) { - return self.d * v * self.scale - } - } - } -} - -/// The chi-squared distribution `χ²(k)`, where `k` is the degrees of -/// freedom. -/// -/// For `k > 0` integral, this distribution is the sum of the squares -/// of `k` independent standard normal random variables. For other -/// `k`, this uses the equivalent characterisation -/// `χ²(k) = Gamma(k/2, 2)`. -/// -/// # Example -/// -/// ``` -/// use rand::distributions::{ChiSquared, Distribution}; -/// -/// let chi = ChiSquared::new(11.0); -/// let v = chi.sample(&mut rand::thread_rng()); -/// println!("{} is from a χ²(11) distribution", v) -/// ``` -#[derive(Clone, Copy, Debug)] -pub struct ChiSquared { - repr: ChiSquaredRepr, -} - -#[derive(Clone, Copy, Debug)] -enum ChiSquaredRepr { - // k == 1, Gamma(alpha, ..) is particularly slow for alpha < 1, - // e.g. when alpha = 1/2 as it would be for this case, so special- - // casing and using the definition of N(0,1)^2 is faster. - DoFExactlyOne, - DoFAnythingElse(Gamma), -} - -impl ChiSquared { - /// Create a new chi-squared distribution with degrees-of-freedom - /// `k`. Panics if `k < 0`. - pub fn new(k: f64) -> ChiSquared { - let repr = if k == 1.0 { - DoFExactlyOne - } else { - assert!(k > 0.0, "ChiSquared::new called with `k` < 0"); - DoFAnythingElse(Gamma::new(0.5 * k, 2.0)) - }; - ChiSquared { repr } - } -} -impl Distribution<f64> for ChiSquared { - fn sample<R: Rng + ?Sized>(&self, rng: &mut R) -> f64 { - match self.repr { - DoFExactlyOne => { - // k == 1 => N(0,1)^2 - let norm = rng.sample(StandardNormal); - norm * norm - } - DoFAnythingElse(ref g) => g.sample(rng) - } - } -} - -/// The Fisher F distribution `F(m, n)`. -/// -/// This distribution is equivalent to the ratio of two normalised -/// chi-squared distributions, that is, `F(m,n) = (χ²(m)/m) / -/// (χ²(n)/n)`. -/// -/// # Example -/// -/// ``` -/// use rand::distributions::{FisherF, Distribution}; -/// -/// let f = FisherF::new(2.0, 32.0); -/// let v = f.sample(&mut rand::thread_rng()); -/// println!("{} is from an F(2, 32) distribution", v) -/// ``` -#[derive(Clone, Copy, Debug)] -pub struct FisherF { - numer: ChiSquared, - denom: ChiSquared, - // denom_dof / numer_dof so that this can just be a straight - // multiplication, rather than a division. - dof_ratio: f64, -} - -impl FisherF { - /// Create a new `FisherF` distribution, with the given - /// parameter. Panics if either `m` or `n` are not positive. - pub fn new(m: f64, n: f64) -> FisherF { - assert!(m > 0.0, "FisherF::new called with `m < 0`"); - assert!(n > 0.0, "FisherF::new called with `n < 0`"); - - FisherF { - numer: ChiSquared::new(m), - denom: ChiSquared::new(n), - dof_ratio: n / m - } - } -} -impl Distribution<f64> for FisherF { - fn sample<R: Rng + ?Sized>(&self, rng: &mut R) -> f64 { - self.numer.sample(rng) / self.denom.sample(rng) * self.dof_ratio - } -} - -/// The Student t distribution, `t(nu)`, where `nu` is the degrees of -/// freedom. -/// -/// # Example -/// -/// ``` -/// use rand::distributions::{StudentT, Distribution}; -/// -/// let t = StudentT::new(11.0); -/// let v = t.sample(&mut rand::thread_rng()); -/// println!("{} is from a t(11) distribution", v) -/// ``` -#[derive(Clone, Copy, Debug)] -pub struct StudentT { - chi: ChiSquared, - dof: f64 -} - -impl StudentT { - /// Create a new Student t distribution with `n` degrees of - /// freedom. Panics if `n <= 0`. - pub fn new(n: f64) -> StudentT { - assert!(n > 0.0, "StudentT::new called with `n <= 0`"); - StudentT { - chi: ChiSquared::new(n), - dof: n - } - } -} -impl Distribution<f64> for StudentT { - fn sample<R: Rng + ?Sized>(&self, rng: &mut R) -> f64 { - let norm = rng.sample(StandardNormal); - norm * (self.dof / self.chi.sample(rng)).sqrt() - } -} - -/// The Beta distribution with shape parameters `alpha` and `beta`. -/// -/// # Example -/// -/// ``` -/// use rand::distributions::{Distribution, Beta}; -/// -/// let beta = Beta::new(2.0, 5.0); -/// let v = beta.sample(&mut rand::thread_rng()); -/// println!("{} is from a Beta(2, 5) distribution", v); -/// ``` -#[derive(Clone, Copy, Debug)] -pub struct Beta { - gamma_a: Gamma, - gamma_b: Gamma, -} - -impl Beta { - /// Construct an object representing the `Beta(alpha, beta)` - /// distribution. - /// - /// Panics if `shape <= 0` or `scale <= 0`. - pub fn new(alpha: f64, beta: f64) -> Beta { - assert!((alpha > 0.) & (beta > 0.)); - Beta { - gamma_a: Gamma::new(alpha, 1.), - gamma_b: Gamma::new(beta, 1.), - } - } -} - -impl Distribution<f64> for Beta { - fn sample<R: Rng + ?Sized>(&self, rng: &mut R) -> f64 { - let x = self.gamma_a.sample(rng); - let y = self.gamma_b.sample(rng); - x / (x + y) - } -} - -#[cfg(test)] -mod test { - use distributions::Distribution; - use super::{Beta, ChiSquared, StudentT, FisherF}; - - #[test] - fn test_chi_squared_one() { - let chi = ChiSquared::new(1.0); - let mut rng = ::test::rng(201); - for _ in 0..1000 { - chi.sample(&mut rng); - } - } - #[test] - fn test_chi_squared_small() { - let chi = ChiSquared::new(0.5); - let mut rng = ::test::rng(202); - for _ in 0..1000 { - chi.sample(&mut rng); - } - } - #[test] - fn test_chi_squared_large() { - let chi = ChiSquared::new(30.0); - let mut rng = ::test::rng(203); - for _ in 0..1000 { - chi.sample(&mut rng); - } - } - #[test] - #[should_panic] - fn test_chi_squared_invalid_dof() { - ChiSquared::new(-1.0); - } - - #[test] - fn test_f() { - let f = FisherF::new(2.0, 32.0); - let mut rng = ::test::rng(204); - for _ in 0..1000 { - f.sample(&mut rng); - } - } - - #[test] - fn test_t() { - let t = StudentT::new(11.0); - let mut rng = ::test::rng(205); - for _ in 0..1000 { - t.sample(&mut rng); - } - } - - #[test] - fn test_beta() { - let beta = Beta::new(1.0, 2.0); - let mut rng = ::test::rng(201); - for _ in 0..1000 { - beta.sample(&mut rng); - } - } - - #[test] - #[should_panic] - fn test_beta_invalid_dof() { - Beta::new(0., 0.); - } -} diff --git a/rand/src/distributions/integer.rs b/rand/src/distributions/integer.rs deleted file mode 100644 index 7e408db..0000000 --- a/rand/src/distributions/integer.rs +++ /dev/null @@ -1,161 +0,0 @@ -// Copyright 2018 Developers of the Rand project. -// -// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or -// https://www.apache.org/licenses/LICENSE-2.0> or the MIT license -// <LICENSE-MIT or https://opensource.org/licenses/MIT>, at your -// option. This file may not be copied, modified, or distributed -// except according to those terms. - -//! The implementations of the `Standard` distribution for integer types. - -use {Rng}; -use distributions::{Distribution, Standard}; -#[cfg(feature="simd_support")] -use packed_simd::*; -#[cfg(all(target_arch = "x86", feature="nightly"))] -use core::arch::x86::*; -#[cfg(all(target_arch = "x86_64", feature="nightly"))] -use core::arch::x86_64::*; - -impl Distribution<u8> for Standard { - #[inline] - fn sample<R: Rng + ?Sized>(&self, rng: &mut R) -> u8 { - rng.next_u32() as u8 - } -} - -impl Distribution<u16> for Standard { - #[inline] - fn sample<R: Rng + ?Sized>(&self, rng: &mut R) -> u16 { - rng.next_u32() as u16 - } -} - -impl Distribution<u32> for Standard { - #[inline] - fn sample<R: Rng + ?Sized>(&self, rng: &mut R) -> u32 { - rng.next_u32() - } -} - -impl Distribution<u64> for Standard { - #[inline] - fn sample<R: Rng + ?Sized>(&self, rng: &mut R) -> u64 { - rng.next_u64() - } -} - -#[cfg(all(rustc_1_26, not(target_os = "emscripten")))] -impl Distribution<u128> for Standard { - #[inline] - fn sample<R: Rng + ?Sized>(&self, rng: &mut R) -> u128 { - // Use LE; we explicitly generate one value before the next. - let x = rng.next_u64() as u128; - let y = rng.next_u64() as u128; - (y << 64) | x - } -} - -impl Distribution<usize> for Standard { - #[inline] - #[cfg(any(target_pointer_width = "32", target_pointer_width = "16"))] - fn sample<R: Rng + ?Sized>(&self, rng: &mut R) -> usize { - rng.next_u32() as usize - } - - #[inline] - #[cfg(target_pointer_width = "64")] - fn sample<R: Rng + ?Sized>(&self, rng: &mut R) -> usize { - rng.next_u64() as usize - } -} - -macro_rules! impl_int_from_uint { - ($ty:ty, $uty:ty) => { - impl Distribution<$ty> for Standard { - #[inline] - fn sample<R: Rng + ?Sized>(&self, rng: &mut R) -> $ty { - rng.gen::<$uty>() as $ty - } - } - } -} - -impl_int_from_uint! { i8, u8 } -impl_int_from_uint! { i16, u16 } -impl_int_from_uint! { i32, u32 } -impl_int_from_uint! { i64, u64 } -#[cfg(all(rustc_1_26, not(target_os = "emscripten")))] impl_int_from_uint! { i128, u128 } -impl_int_from_uint! { isize, usize } - -#[cfg(feature="simd_support")] -macro_rules! simd_impl { - ($(($intrinsic:ident, $vec:ty),)+) => {$( - impl Distribution<$intrinsic> for Standard { - #[inline] - fn sample<R: Rng + ?Sized>(&self, rng: &mut R) -> $intrinsic { - $intrinsic::from_bits(rng.gen::<$vec>()) - } - } - )+}; - - ($bits:expr,) => {}; - ($bits:expr, $ty:ty, $($ty_more:ty,)*) => { - simd_impl!($bits, $($ty_more,)*); - - impl Distribution<$ty> for Standard { - #[inline] - fn sample<R: Rng + ?Sized>(&self, rng: &mut R) -> $ty { - let mut vec: $ty = Default::default(); - unsafe { - let ptr = &mut vec; - let b_ptr = &mut *(ptr as *mut $ty as *mut [u8; $bits/8]); - rng.fill_bytes(b_ptr); - } - vec.to_le() - } - } - }; -} - -#[cfg(feature="simd_support")] -simd_impl!(16, u8x2, i8x2,); -#[cfg(feature="simd_support")] -simd_impl!(32, u8x4, i8x4, u16x2, i16x2,); -#[cfg(feature="simd_support")] -simd_impl!(64, u8x8, i8x8, u16x4, i16x4, u32x2, i32x2,); -#[cfg(feature="simd_support")] -simd_impl!(128, u8x16, i8x16, u16x8, i16x8, u32x4, i32x4, u64x2, i64x2,); -#[cfg(feature="simd_support")] -simd_impl!(256, u8x32, i8x32, u16x16, i16x16, u32x8, i32x8, u64x4, i64x4,); -#[cfg(feature="simd_support")] -simd_impl!(512, u8x64, i8x64, u16x32, i16x32, u32x16, i32x16, u64x8, i64x8,); -#[cfg(all(feature="simd_support", feature="nightly", any(target_arch="x86", target_arch="x86_64")))] -simd_impl!((__m64, u8x8), (__m128i, u8x16), (__m256i, u8x32),); - -#[cfg(test)] -mod tests { - use Rng; - use distributions::{Standard}; - - #[test] - fn test_integers() { - let mut rng = ::test::rng(806); - - rng.sample::<isize, _>(Standard); - rng.sample::<i8, _>(Standard); - rng.sample::<i16, _>(Standard); - rng.sample::<i32, _>(Standard); - rng.sample::<i64, _>(Standard); - #[cfg(all(rustc_1_26, not(target_os = "emscripten")))] - rng.sample::<i128, _>(Standard); - - rng.sample::<usize, _>(Standard); - rng.sample::<u8, _>(Standard); - rng.sample::<u16, _>(Standard); - rng.sample::<u32, _>(Standard); - rng.sample::<u64, _>(Standard); - #[cfg(all(rustc_1_26, not(target_os = "emscripten")))] - rng.sample::<u128, _>(Standard); - } -} diff --git a/rand/src/distributions/mod.rs b/rand/src/distributions/mod.rs deleted file mode 100644 index 5e879cb..0000000 --- a/rand/src/distributions/mod.rs +++ /dev/null @@ -1,621 +0,0 @@ -// Copyright 2018 Developers of the Rand project. -// Copyright 2013-2017 The Rust Project Developers. -// -// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or -// https://www.apache.org/licenses/LICENSE-2.0> or the MIT license -// <LICENSE-MIT or https://opensource.org/licenses/MIT>, at your -// option. This file may not be copied, modified, or distributed -// except according to those terms. - -//! Generating random samples from probability distributions. -//! -//! This module is the home of the [`Distribution`] trait and several of its -//! implementations. It is the workhorse behind some of the convenient -//! functionality of the [`Rng`] trait, including [`gen`], [`gen_range`] and -//! of course [`sample`]. -//! -//! Abstractly, a [probability distribution] describes the probability of -//! occurance of each value in its sample space. -//! -//! More concretely, an implementation of `Distribution<T>` for type `X` is an -//! algorithm for choosing values from the sample space (a subset of `T`) -//! according to the distribution `X` represents, using an external source of -//! randomness (an RNG supplied to the `sample` function). -//! -//! A type `X` may implement `Distribution<T>` for multiple types `T`. -//! Any type implementing [`Distribution`] is stateless (i.e. immutable), -//! but it may have internal parameters set at construction time (for example, -//! [`Uniform`] allows specification of its sample space as a range within `T`). -//! -//! -//! # The `Standard` distribution -//! -//! The [`Standard`] distribution is important to mention. This is the -//! distribution used by [`Rng::gen()`] and represents the "default" way to -//! produce a random value for many different types, including most primitive -//! types, tuples, arrays, and a few derived types. See the documentation of -//! [`Standard`] for more details. -//! -//! Implementing `Distribution<T>` for [`Standard`] for user types `T` makes it -//! possible to generate type `T` with [`Rng::gen()`], and by extension also -//! with the [`random()`] function. -//! -//! -//! # Distribution to sample from a `Uniform` range -//! -//! The [`Uniform`] distribution is more flexible than [`Standard`], but also -//! more specialised: it supports fewer target types, but allows the sample -//! space to be specified as an arbitrary range within its target type `T`. -//! Both [`Standard`] and [`Uniform`] are in some sense uniform distributions. -//! -//! Values may be sampled from this distribution using [`Rng::gen_range`] or -//! by creating a distribution object with [`Uniform::new`], -//! [`Uniform::new_inclusive`] or `From<Range>`. When the range limits are not -//! known at compile time it is typically faster to reuse an existing -//! distribution object than to call [`Rng::gen_range`]. -//! -//! User types `T` may also implement `Distribution<T>` for [`Uniform`], -//! although this is less straightforward than for [`Standard`] (see the -//! documentation in the [`uniform` module]. Doing so enables generation of -//! values of type `T` with [`Rng::gen_range`]. -//! -//! -//! # Other distributions -//! -//! There are surprisingly many ways to uniformly generate random floats. A -//! range between 0 and 1 is standard, but the exact bounds (open vs closed) -//! and accuracy differ. In addition to the [`Standard`] distribution Rand offers -//! [`Open01`] and [`OpenClosed01`]. See [Floating point implementation] for -//! more details. -//! -//! [`Alphanumeric`] is a simple distribution to sample random letters and -//! numbers of the `char` type; in contrast [`Standard`] may sample any valid -//! `char`. -//! -//! [`WeightedIndex`] can be used to do weighted sampling from a set of items, -//! such as from an array. -//! -//! # Non-uniform probability distributions -//! -//! Rand currently provides the following probability distributions: -//! -//! - Related to real-valued quantities that grow linearly -//! (e.g. errors, offsets): -//! - [`Normal`] distribution, and [`StandardNormal`] as a primitive -//! - [`Cauchy`] distribution -//! - Related to Bernoulli trials (yes/no events, with a given probability): -//! - [`Binomial`] distribution -//! - [`Bernoulli`] distribution, similar to [`Rng::gen_bool`]. -//! - Related to positive real-valued quantities that grow exponentially -//! (e.g. prices, incomes, populations): -//! - [`LogNormal`] distribution -//! - Related to the occurrence of independent events at a given rate: -//! - [`Pareto`] distribution -//! - [`Poisson`] distribution -//! - [`Exp`]onential distribution, and [`Exp1`] as a primitive -//! - [`Weibull`] distribution -//! - Gamma and derived distributions: -//! - [`Gamma`] distribution -//! - [`ChiSquared`] distribution -//! - [`StudentT`] distribution -//! - [`FisherF`] distribution -//! - Triangular distribution: -//! - [`Beta`] distribution -//! - [`Triangular`] distribution -//! - Multivariate probability distributions -//! - [`Dirichlet`] distribution -//! - [`UnitSphereSurface`] distribution -//! - [`UnitCircle`] distribution -//! -//! # Examples -//! -//! Sampling from a distribution: -//! -//! ``` -//! use rand::{thread_rng, Rng}; -//! use rand::distributions::Exp; -//! -//! let exp = Exp::new(2.0); -//! let v = thread_rng().sample(exp); -//! println!("{} is from an Exp(2) distribution", v); -//! ``` -//! -//! Implementing the [`Standard`] distribution for a user type: -//! -//! ``` -//! # #![allow(dead_code)] -//! use rand::Rng; -//! use rand::distributions::{Distribution, Standard}; -//! -//! struct MyF32 { -//! x: f32, -//! } -//! -//! impl Distribution<MyF32> for Standard { -//! fn sample<R: Rng + ?Sized>(&self, rng: &mut R) -> MyF32 { -//! MyF32 { x: rng.gen() } -//! } -//! } -//! ``` -//! -//! -//! [probability distribution]: https://en.wikipedia.org/wiki/Probability_distribution -//! [`Distribution`]: trait.Distribution.html -//! [`gen_range`]: ../trait.Rng.html#method.gen_range -//! [`gen`]: ../trait.Rng.html#method.gen -//! [`sample`]: ../trait.Rng.html#method.sample -//! [`new_inclusive`]: struct.Uniform.html#method.new_inclusive -//! [`random()`]: ../fn.random.html -//! [`Rng::gen_bool`]: ../trait.Rng.html#method.gen_bool -//! [`Rng::gen_range`]: ../trait.Rng.html#method.gen_range -//! [`Rng::gen()`]: ../trait.Rng.html#method.gen -//! [`Rng`]: ../trait.Rng.html -//! [`uniform` module]: uniform/index.html -//! [Floating point implementation]: struct.Standard.html#floating-point-implementation -// distributions -//! [`Alphanumeric`]: struct.Alphanumeric.html -//! [`Bernoulli`]: struct.Bernoulli.html -//! [`Beta`]: struct.Beta.html -//! [`Binomial`]: struct.Binomial.html -//! [`Cauchy`]: struct.Cauchy.html -//! [`ChiSquared`]: struct.ChiSquared.html -//! [`Dirichlet`]: struct.Dirichlet.html -//! [`Exp`]: struct.Exp.html -//! [`Exp1`]: struct.Exp1.html -//! [`FisherF`]: struct.FisherF.html -//! [`Gamma`]: struct.Gamma.html -//! [`LogNormal`]: struct.LogNormal.html -//! [`Normal`]: struct.Normal.html -//! [`Open01`]: struct.Open01.html -//! [`OpenClosed01`]: struct.OpenClosed01.html -//! [`Pareto`]: struct.Pareto.html -//! [`Poisson`]: struct.Poisson.html -//! [`Standard`]: struct.Standard.html -//! [`StandardNormal`]: struct.StandardNormal.html -//! [`StudentT`]: struct.StudentT.html -//! [`Triangular`]: struct.Triangular.html -//! [`Uniform`]: struct.Uniform.html -//! [`Uniform::new`]: struct.Uniform.html#method.new -//! [`Uniform::new_inclusive`]: struct.Uniform.html#method.new_inclusive -//! [`UnitSphereSurface`]: struct.UnitSphereSurface.html -//! [`UnitCircle`]: struct.UnitCircle.html -//! [`Weibull`]: struct.Weibull.html -//! [`WeightedIndex`]: struct.WeightedIndex.html - -#[cfg(any(rustc_1_26, features="nightly"))] -use core::iter; -use Rng; - -pub use self::other::Alphanumeric; -#[doc(inline)] pub use self::uniform::Uniform; -pub use self::float::{OpenClosed01, Open01}; -pub use self::bernoulli::Bernoulli; -#[cfg(feature="alloc")] pub use self::weighted::{WeightedIndex, WeightedError}; -#[cfg(feature="std")] pub use self::unit_sphere::UnitSphereSurface; -#[cfg(feature="std")] pub use self::unit_circle::UnitCircle; -#[cfg(feature="std")] pub use self::gamma::{Gamma, ChiSquared, FisherF, - StudentT, Beta}; -#[cfg(feature="std")] pub use self::normal::{Normal, LogNormal, StandardNormal}; -#[cfg(feature="std")] pub use self::exponential::{Exp, Exp1}; -#[cfg(feature="std")] pub use self::pareto::Pareto; -#[cfg(feature="std")] pub use self::poisson::Poisson; -#[cfg(feature="std")] pub use self::binomial::Binomial; -#[cfg(feature="std")] pub use self::cauchy::Cauchy; -#[cfg(feature="std")] pub use self::dirichlet::Dirichlet; -#[cfg(feature="std")] pub use self::triangular::Triangular; -#[cfg(feature="std")] pub use self::weibull::Weibull; - -pub mod uniform; -mod bernoulli; -#[cfg(feature="alloc")] mod weighted; -#[cfg(feature="std")] mod unit_sphere; -#[cfg(feature="std")] mod unit_circle; -#[cfg(feature="std")] mod gamma; -#[cfg(feature="std")] mod normal; -#[cfg(feature="std")] mod exponential; -#[cfg(feature="std")] mod pareto; -#[cfg(feature="std")] mod poisson; -#[cfg(feature="std")] mod binomial; -#[cfg(feature="std")] mod cauchy; -#[cfg(feature="std")] mod dirichlet; -#[cfg(feature="std")] mod triangular; -#[cfg(feature="std")] mod weibull; - -mod float; -mod integer; -mod other; -mod utils; -#[cfg(feature="std")] mod ziggurat_tables; - -/// Types (distributions) that can be used to create a random instance of `T`. -/// -/// It is possible to sample from a distribution through both the -/// `Distribution` and [`Rng`] traits, via `distr.sample(&mut rng)` and -/// `rng.sample(distr)`. They also both offer the [`sample_iter`] method, which -/// produces an iterator that samples from the distribution. -/// -/// All implementations are expected to be immutable; this has the significant -/// advantage of not needing to consider thread safety, and for most -/// distributions efficient state-less sampling algorithms are available. -/// -/// [`Rng`]: ../trait.Rng.html -/// [`sample_iter`]: trait.Distribution.html#method.sample_iter -pub trait Distribution<T> { - /// Generate a random value of `T`, using `rng` as the source of randomness. - fn sample<R: Rng + ?Sized>(&self, rng: &mut R) -> T; - - /// Create an iterator that generates random values of `T`, using `rng` as - /// the source of randomness. - /// - /// # Example - /// - /// ``` - /// use rand::thread_rng; - /// use rand::distributions::{Distribution, Alphanumeric, Uniform, Standard}; - /// - /// let mut rng = thread_rng(); - /// - /// // Vec of 16 x f32: - /// let v: Vec<f32> = Standard.sample_iter(&mut rng).take(16).collect(); - /// - /// // String: - /// let s: String = Alphanumeric.sample_iter(&mut rng).take(7).collect(); - /// - /// // Dice-rolling: - /// let die_range = Uniform::new_inclusive(1, 6); - /// let mut roll_die = die_range.sample_iter(&mut rng); - /// while roll_die.next().unwrap() != 6 { - /// println!("Not a 6; rolling again!"); - /// } - /// ``` - fn sample_iter<'a, R>(&'a self, rng: &'a mut R) -> DistIter<'a, Self, R, T> - where Self: Sized, R: Rng - { - DistIter { - distr: self, - rng: rng, - phantom: ::core::marker::PhantomData, - } - } -} - -impl<'a, T, D: Distribution<T>> Distribution<T> for &'a D { - fn sample<R: Rng + ?Sized>(&self, rng: &mut R) -> T { - (*self).sample(rng) - } -} - - -/// An iterator that generates random values of `T` with distribution `D`, -/// using `R` as the source of randomness. -/// -/// This `struct` is created by the [`sample_iter`] method on [`Distribution`]. -/// See its documentation for more. -/// -/// [`Distribution`]: trait.Distribution.html -/// [`sample_iter`]: trait.Distribution.html#method.sample_iter -#[derive(Debug)] -pub struct DistIter<'a, D: 'a, R: 'a, T> { - distr: &'a D, - rng: &'a mut R, - phantom: ::core::marker::PhantomData<T>, -} - -impl<'a, D, R, T> Iterator for DistIter<'a, D, R, T> - where D: Distribution<T>, R: Rng + 'a -{ - type Item = T; - - #[inline(always)] - fn next(&mut self) -> Option<T> { - Some(self.distr.sample(self.rng)) - } - - fn size_hint(&self) -> (usize, Option<usize>) { - (usize::max_value(), None) - } -} - -#[cfg(rustc_1_26)] -impl<'a, D, R, T> iter::FusedIterator for DistIter<'a, D, R, T> - where D: Distribution<T>, R: Rng + 'a {} - -#[cfg(features = "nightly")] -impl<'a, D, R, T> iter::TrustedLen for DistIter<'a, D, R, T> - where D: Distribution<T>, R: Rng + 'a {} - - -/// A generic random value distribution, implemented for many primitive types. -/// Usually generates values with a numerically uniform distribution, and with a -/// range appropriate to the type. -/// -/// ## Built-in Implementations -/// -/// Assuming the provided `Rng` is well-behaved, these implementations -/// generate values with the following ranges and distributions: -/// -/// * Integers (`i32`, `u32`, `isize`, `usize`, etc.): Uniformly distributed -/// over all values of the type. -/// * `char`: Uniformly distributed over all Unicode scalar values, i.e. all -/// code points in the range `0...0x10_FFFF`, except for the range -/// `0xD800...0xDFFF` (the surrogate code points). This includes -/// unassigned/reserved code points. -/// * `bool`: Generates `false` or `true`, each with probability 0.5. -/// * Floating point types (`f32` and `f64`): Uniformly distributed in the -/// half-open range `[0, 1)`. See notes below. -/// * Wrapping integers (`Wrapping<T>`), besides the type identical to their -/// normal integer variants. -/// -/// The following aggregate types also implement the distribution `Standard` as -/// long as their component types implement it: -/// -/// * Tuples and arrays: Each element of the tuple or array is generated -/// independently, using the `Standard` distribution recursively. -/// * `Option<T>` where `Standard` is implemented for `T`: Returns `None` with -/// probability 0.5; otherwise generates a random `x: T` and returns `Some(x)`. -/// -/// # Example -/// ``` -/// use rand::prelude::*; -/// use rand::distributions::Standard; -/// -/// let val: f32 = SmallRng::from_entropy().sample(Standard); -/// println!("f32 from [0, 1): {}", val); -/// ``` -/// -/// # Floating point implementation -/// The floating point implementations for `Standard` generate a random value in -/// the half-open interval `[0, 1)`, i.e. including 0 but not 1. -/// -/// All values that can be generated are of the form `n * ε/2`. For `f32` -/// the 23 most significant random bits of a `u32` are used and for `f64` the -/// 53 most significant bits of a `u64` are used. The conversion uses the -/// multiplicative method: `(rng.gen::<$uty>() >> N) as $ty * (ε/2)`. -/// -/// See also: [`Open01`] which samples from `(0, 1)`, [`OpenClosed01`] which -/// samples from `(0, 1]` and `Rng::gen_range(0, 1)` which also samples from -/// `[0, 1)`. Note that `Open01` and `gen_range` (which uses [`Uniform`]) use -/// transmute-based methods which yield 1 bit less precision but may perform -/// faster on some architectures (on modern Intel CPUs all methods have -/// approximately equal performance). -/// -/// [`Open01`]: struct.Open01.html -/// [`OpenClosed01`]: struct.OpenClosed01.html -/// [`Uniform`]: uniform/struct.Uniform.html -#[derive(Clone, Copy, Debug)] -pub struct Standard; - - -/// A value with a particular weight for use with `WeightedChoice`. -#[deprecated(since="0.6.0", note="use WeightedIndex instead")] -#[allow(deprecated)] -#[derive(Copy, Clone, Debug)] -pub struct Weighted<T> { - /// The numerical weight of this item - pub weight: u32, - /// The actual item which is being weighted - pub item: T, -} - -/// A distribution that selects from a finite collection of weighted items. -/// -/// Deprecated: use [`WeightedIndex`] instead. -/// -/// [`WeightedIndex`]: struct.WeightedIndex.html -#[deprecated(since="0.6.0", note="use WeightedIndex instead")] -#[allow(deprecated)] -#[derive(Debug)] -pub struct WeightedChoice<'a, T:'a> { - items: &'a mut [Weighted<T>], - weight_range: Uniform<u32>, -} - -#[deprecated(since="0.6.0", note="use WeightedIndex instead")] -#[allow(deprecated)] -impl<'a, T: Clone> WeightedChoice<'a, T> { - /// Create a new `WeightedChoice`. - /// - /// Panics if: - /// - /// - `items` is empty - /// - the total weight is 0 - /// - the total weight is larger than a `u32` can contain. - pub fn new(items: &'a mut [Weighted<T>]) -> WeightedChoice<'a, T> { - // strictly speaking, this is subsumed by the total weight == 0 case - assert!(!items.is_empty(), "WeightedChoice::new called with no items"); - - let mut running_total: u32 = 0; - - // we convert the list from individual weights to cumulative - // weights so we can binary search. This *could* drop elements - // with weight == 0 as an optimisation. - for item in items.iter_mut() { - running_total = match running_total.checked_add(item.weight) { - Some(n) => n, - None => panic!("WeightedChoice::new called with a total weight \ - larger than a u32 can contain") - }; - - item.weight = running_total; - } - assert!(running_total != 0, "WeightedChoice::new called with a total weight of 0"); - - WeightedChoice { - items, - // we're likely to be generating numbers in this range - // relatively often, so might as well cache it - weight_range: Uniform::new(0, running_total) - } - } -} - -#[deprecated(since="0.6.0", note="use WeightedIndex instead")] -#[allow(deprecated)] -impl<'a, T: Clone> Distribution<T> for WeightedChoice<'a, T> { - fn sample<R: Rng + ?Sized>(&self, rng: &mut R) -> T { - // we want to find the first element that has cumulative - // weight > sample_weight, which we do by binary since the - // cumulative weights of self.items are sorted. - - // choose a weight in [0, total_weight) - let sample_weight = self.weight_range.sample(rng); - - // short circuit when it's the first item - if sample_weight < self.items[0].weight { - return self.items[0].item.clone(); - } - - let mut idx = 0; - let mut modifier = self.items.len(); - - // now we know that every possibility has an element to the - // left, so we can just search for the last element that has - // cumulative weight <= sample_weight, then the next one will - // be "it". (Note that this greatest element will never be the - // last element of the vector, since sample_weight is chosen - // in [0, total_weight) and the cumulative weight of the last - // one is exactly the total weight.) - while modifier > 1 { - let i = idx + modifier / 2; - if self.items[i].weight <= sample_weight { - // we're small, so look to the right, but allow this - // exact element still. - idx = i; - // we need the `/ 2` to round up otherwise we'll drop - // the trailing elements when `modifier` is odd. - modifier += 1; - } else { - // otherwise we're too big, so go left. (i.e. do - // nothing) - } - modifier /= 2; - } - self.items[idx + 1].item.clone() - } -} - -#[cfg(test)] -mod tests { - use rngs::mock::StepRng; - #[allow(deprecated)] - use super::{WeightedChoice, Weighted, Distribution}; - - #[test] - #[allow(deprecated)] - fn test_weighted_choice() { - // this makes assumptions about the internal implementation of - // WeightedChoice. It may fail when the implementation in - // `distributions::uniform::UniformInt` changes. - - macro_rules! t { - ($items:expr, $expected:expr) => {{ - let mut items = $items; - let mut total_weight = 0; - for item in &items { total_weight += item.weight; } - - let wc = WeightedChoice::new(&mut items); - let expected = $expected; - - // Use extremely large steps between the random numbers, because - // we test with small ranges and `UniformInt` is designed to prefer - // the most significant bits. - let mut rng = StepRng::new(0, !0 / (total_weight as u64)); - - for &val in expected.iter() { - assert_eq!(wc.sample(&mut rng), val) - } - }} - } - - t!([Weighted { weight: 1, item: 10}], [10]); - - // skip some - t!([Weighted { weight: 0, item: 20}, - Weighted { weight: 2, item: 21}, - Weighted { weight: 0, item: 22}, - Weighted { weight: 1, item: 23}], - [21, 21, 23]); - - // different weights - t!([Weighted { weight: 4, item: 30}, - Weighted { weight: 3, item: 31}], - [30, 31, 30, 31, 30, 31, 30]); - - // check that we're binary searching - // correctly with some vectors of odd - // length. - t!([Weighted { weight: 1, item: 40}, - Weighted { weight: 1, item: 41}, - Weighted { weight: 1, item: 42}, - Weighted { weight: 1, item: 43}, - Weighted { weight: 1, item: 44}], - [40, 41, 42, 43, 44]); - t!([Weighted { weight: 1, item: 50}, - Weighted { weight: 1, item: 51}, - Weighted { weight: 1, item: 52}, - Weighted { weight: 1, item: 53}, - Weighted { weight: 1, item: 54}, - Weighted { weight: 1, item: 55}, - Weighted { weight: 1, item: 56}], - [50, 54, 51, 55, 52, 56, 53]); - } - - #[test] - #[allow(deprecated)] - fn test_weighted_clone_initialization() { - let initial : Weighted<u32> = Weighted {weight: 1, item: 1}; - let clone = initial.clone(); - assert_eq!(initial.weight, clone.weight); - assert_eq!(initial.item, clone.item); - } - - #[test] #[should_panic] - #[allow(deprecated)] - fn test_weighted_clone_change_weight() { - let initial : Weighted<u32> = Weighted {weight: 1, item: 1}; - let mut clone = initial.clone(); - clone.weight = 5; - assert_eq!(initial.weight, clone.weight); - } - - #[test] #[should_panic] - #[allow(deprecated)] - fn test_weighted_clone_change_item() { - let initial : Weighted<u32> = Weighted {weight: 1, item: 1}; - let mut clone = initial.clone(); - clone.item = 5; - assert_eq!(initial.item, clone.item); - - } - - #[test] #[should_panic] - #[allow(deprecated)] - fn test_weighted_choice_no_items() { - WeightedChoice::<isize>::new(&mut []); - } - #[test] #[should_panic] - #[allow(deprecated)] - fn test_weighted_choice_zero_weight() { - WeightedChoice::new(&mut [Weighted { weight: 0, item: 0}, - Weighted { weight: 0, item: 1}]); - } - #[test] #[should_panic] - #[allow(deprecated)] - fn test_weighted_choice_weight_overflows() { - let x = ::core::u32::MAX / 2; // x + x + 2 is the overflow - WeightedChoice::new(&mut [Weighted { weight: x, item: 0 }, - Weighted { weight: 1, item: 1 }, - Weighted { weight: x, item: 2 }, - Weighted { weight: 1, item: 3 }]); - } - - #[cfg(feature="std")] - #[test] - fn test_distributions_iter() { - use distributions::Normal; - let mut rng = ::test::rng(210); - let distr = Normal::new(10.0, 10.0); - let results: Vec<_> = distr.sample_iter(&mut rng).take(100).collect(); - println!("{:?}", results); - } -} diff --git a/rand/src/distributions/normal.rs b/rand/src/distributions/normal.rs deleted file mode 100644 index b8d632e..0000000 --- a/rand/src/distributions/normal.rs +++ /dev/null @@ -1,197 +0,0 @@ -// Copyright 2018 Developers of the Rand project. -// Copyright 2013 The Rust Project Developers. -// -// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or -// https://www.apache.org/licenses/LICENSE-2.0> or the MIT license -// <LICENSE-MIT or https://opensource.org/licenses/MIT>, at your -// option. This file may not be copied, modified, or distributed -// except according to those terms. - -//! The normal and derived distributions. - -use Rng; -use distributions::{ziggurat_tables, Distribution, Open01}; -use distributions::utils::ziggurat; - -/// Samples floating-point numbers according to the normal distribution -/// `N(0, 1)` (a.k.a. a standard normal, or Gaussian). This is equivalent to -/// `Normal::new(0.0, 1.0)` but faster. -/// -/// See `Normal` for the general normal distribution. -/// -/// Implemented via the ZIGNOR variant[^1] of the Ziggurat method. -/// -/// [^1]: Jurgen A. Doornik (2005). [*An Improved Ziggurat Method to -/// Generate Normal Random Samples*]( -/// https://www.doornik.com/research/ziggurat.pdf). -/// Nuffield College, Oxford -/// -/// # Example -/// ``` -/// use rand::prelude::*; -/// use rand::distributions::StandardNormal; -/// -/// let val: f64 = SmallRng::from_entropy().sample(StandardNormal); -/// println!("{}", val); -/// ``` -#[derive(Clone, Copy, Debug)] -pub struct StandardNormal; - -impl Distribution<f64> for StandardNormal { - fn sample<R: Rng + ?Sized>(&self, rng: &mut R) -> f64 { - #[inline] - fn pdf(x: f64) -> f64 { - (-x*x/2.0).exp() - } - #[inline] - fn zero_case<R: Rng + ?Sized>(rng: &mut R, u: f64) -> f64 { - // compute a random number in the tail by hand - - // strange initial conditions, because the loop is not - // do-while, so the condition should be true on the first - // run, they get overwritten anyway (0 < 1, so these are - // good). - let mut x = 1.0f64; - let mut y = 0.0f64; - - while -2.0 * y < x * x { - let x_: f64 = rng.sample(Open01); - let y_: f64 = rng.sample(Open01); - - x = x_.ln() / ziggurat_tables::ZIG_NORM_R; - y = y_.ln(); - } - - if u < 0.0 { x - ziggurat_tables::ZIG_NORM_R } else { ziggurat_tables::ZIG_NORM_R - x } - } - - ziggurat(rng, true, // this is symmetric - &ziggurat_tables::ZIG_NORM_X, - &ziggurat_tables::ZIG_NORM_F, - pdf, zero_case) - } -} - -/// The normal distribution `N(mean, std_dev**2)`. -/// -/// This uses the ZIGNOR variant of the Ziggurat method, see [`StandardNormal`] -/// for more details. -/// -/// Note that [`StandardNormal`] is an optimised implementation for mean 0, and -/// standard deviation 1. -/// -/// # Example -/// -/// ``` -/// use rand::distributions::{Normal, Distribution}; -/// -/// // mean 2, standard deviation 3 -/// let normal = Normal::new(2.0, 3.0); -/// let v = normal.sample(&mut rand::thread_rng()); -/// println!("{} is from a N(2, 9) distribution", v) -/// ``` -/// -/// [`StandardNormal`]: struct.StandardNormal.html -#[derive(Clone, Copy, Debug)] -pub struct Normal { - mean: f64, - std_dev: f64, -} - -impl Normal { - /// Construct a new `Normal` distribution with the given mean and - /// standard deviation. - /// - /// # Panics - /// - /// Panics if `std_dev < 0`. - #[inline] - pub fn new(mean: f64, std_dev: f64) -> Normal { - assert!(std_dev >= 0.0, "Normal::new called with `std_dev` < 0"); - Normal { - mean, - std_dev - } - } -} -impl Distribution<f64> for Normal { - fn sample<R: Rng + ?Sized>(&self, rng: &mut R) -> f64 { - let n = rng.sample(StandardNormal); - self.mean + self.std_dev * n - } -} - - -/// The log-normal distribution `ln N(mean, std_dev**2)`. -/// -/// If `X` is log-normal distributed, then `ln(X)` is `N(mean, std_dev**2)` -/// distributed. -/// -/// # Example -/// -/// ``` -/// use rand::distributions::{LogNormal, Distribution}; -/// -/// // mean 2, standard deviation 3 -/// let log_normal = LogNormal::new(2.0, 3.0); -/// let v = log_normal.sample(&mut rand::thread_rng()); -/// println!("{} is from an ln N(2, 9) distribution", v) -/// ``` -#[derive(Clone, Copy, Debug)] -pub struct LogNormal { - norm: Normal -} - -impl LogNormal { - /// Construct a new `LogNormal` distribution with the given mean - /// and standard deviation. - /// - /// # Panics - /// - /// Panics if `std_dev < 0`. - #[inline] - pub fn new(mean: f64, std_dev: f64) -> LogNormal { - assert!(std_dev >= 0.0, "LogNormal::new called with `std_dev` < 0"); - LogNormal { norm: Normal::new(mean, std_dev) } - } -} -impl Distribution<f64> for LogNormal { - fn sample<R: Rng + ?Sized>(&self, rng: &mut R) -> f64 { - self.norm.sample(rng).exp() - } -} - -#[cfg(test)] -mod tests { - use distributions::Distribution; - use super::{Normal, LogNormal}; - - #[test] - fn test_normal() { - let norm = Normal::new(10.0, 10.0); - let mut rng = ::test::rng(210); - for _ in 0..1000 { - norm.sample(&mut rng); - } - } - #[test] - #[should_panic] - fn test_normal_invalid_sd() { - Normal::new(10.0, -1.0); - } - - - #[test] - fn test_log_normal() { - let lnorm = LogNormal::new(10.0, 10.0); - let mut rng = ::test::rng(211); - for _ in 0..1000 { - lnorm.sample(&mut rng); - } - } - #[test] - #[should_panic] - fn test_log_normal_invalid_sd() { - LogNormal::new(10.0, -1.0); - } -} diff --git a/rand/src/distributions/other.rs b/rand/src/distributions/other.rs deleted file mode 100644 index 2295f79..0000000 --- a/rand/src/distributions/other.rs +++ /dev/null @@ -1,219 +0,0 @@ -// Copyright 2018 Developers of the Rand project. -// -// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or -// https://www.apache.org/licenses/LICENSE-2.0> or the MIT license -// <LICENSE-MIT or https://opensource.org/licenses/MIT>, at your -// option. This file may not be copied, modified, or distributed -// except according to those terms. - -//! The implementations of the `Standard` distribution for other built-in types. - -use core::char; -use core::num::Wrapping; - -use {Rng}; -use distributions::{Distribution, Standard, Uniform}; - -// ----- Sampling distributions ----- - -/// Sample a `char`, uniformly distributed over ASCII letters and numbers: -/// a-z, A-Z and 0-9. -/// -/// # Example -/// -/// ``` -/// use std::iter; -/// use rand::{Rng, thread_rng}; -/// use rand::distributions::Alphanumeric; -/// -/// let mut rng = thread_rng(); -/// let chars: String = iter::repeat(()) -/// .map(|()| rng.sample(Alphanumeric)) -/// .take(7) -/// .collect(); -/// println!("Random chars: {}", chars); -/// ``` -#[derive(Debug)] -pub struct Alphanumeric; - - -// ----- Implementations of distributions ----- - -impl Distribution<char> for Standard { - #[inline] - fn sample<R: Rng + ?Sized>(&self, rng: &mut R) -> char { - // A valid `char` is either in the interval `[0, 0xD800)` or - // `(0xDFFF, 0x11_0000)`. All `char`s must therefore be in - // `[0, 0x11_0000)` but not in the "gap" `[0xD800, 0xDFFF]` which is - // reserved for surrogates. This is the size of that gap. - const GAP_SIZE: u32 = 0xDFFF - 0xD800 + 1; - - // Uniform::new(0, 0x11_0000 - GAP_SIZE) can also be used but it - // seemed slower. - let range = Uniform::new(GAP_SIZE, 0x11_0000); - - let mut n = range.sample(rng); - if n <= 0xDFFF { - n -= GAP_SIZE; - } - unsafe { char::from_u32_unchecked(n) } - } -} - -impl Distribution<char> for Alphanumeric { - fn sample<R: Rng + ?Sized>(&self, rng: &mut R) -> char { - const RANGE: u32 = 26 + 26 + 10; - const GEN_ASCII_STR_CHARSET: &[u8] = - b"ABCDEFGHIJKLMNOPQRSTUVWXYZ\ - abcdefghijklmnopqrstuvwxyz\ - 0123456789"; - // We can pick from 62 characters. This is so close to a power of 2, 64, - // that we can do better than `Uniform`. Use a simple bitshift and - // rejection sampling. We do not use a bitmask, because for small RNGs - // the most significant bits are usually of higher quality. - loop { - let var = rng.next_u32() >> (32 - 6); - if var < RANGE { - return GEN_ASCII_STR_CHARSET[var as usize] as char - } - } - } -} - -impl Distribution<bool> for Standard { - #[inline] - fn sample<R: Rng + ?Sized>(&self, rng: &mut R) -> bool { - // We can compare against an arbitrary bit of an u32 to get a bool. - // Because the least significant bits of a lower quality RNG can have - // simple patterns, we compare against the most significant bit. This is - // easiest done using a sign test. - (rng.next_u32() as i32) < 0 - } -} - -macro_rules! tuple_impl { - // use variables to indicate the arity of the tuple - ($($tyvar:ident),* ) => { - // the trailing commas are for the 1 tuple - impl< $( $tyvar ),* > - Distribution<( $( $tyvar ),* , )> - for Standard - where $( Standard: Distribution<$tyvar> ),* - { - #[inline] - fn sample<R: Rng + ?Sized>(&self, _rng: &mut R) -> ( $( $tyvar ),* , ) { - ( - // use the $tyvar's to get the appropriate number of - // repeats (they're not actually needed) - $( - _rng.gen::<$tyvar>() - ),* - , - ) - } - } - } -} - -impl Distribution<()> for Standard { - #[inline] - fn sample<R: Rng + ?Sized>(&self, _: &mut R) -> () { () } -} -tuple_impl!{A} -tuple_impl!{A, B} -tuple_impl!{A, B, C} -tuple_impl!{A, B, C, D} -tuple_impl!{A, B, C, D, E} -tuple_impl!{A, B, C, D, E, F} -tuple_impl!{A, B, C, D, E, F, G} -tuple_impl!{A, B, C, D, E, F, G, H} -tuple_impl!{A, B, C, D, E, F, G, H, I} -tuple_impl!{A, B, C, D, E, F, G, H, I, J} -tuple_impl!{A, B, C, D, E, F, G, H, I, J, K} -tuple_impl!{A, B, C, D, E, F, G, H, I, J, K, L} - -macro_rules! array_impl { - // recursive, given at least one type parameter: - {$n:expr, $t:ident, $($ts:ident,)*} => { - array_impl!{($n - 1), $($ts,)*} - - impl<T> Distribution<[T; $n]> for Standard where Standard: Distribution<T> { - #[inline] - fn sample<R: Rng + ?Sized>(&self, _rng: &mut R) -> [T; $n] { - [_rng.gen::<$t>(), $(_rng.gen::<$ts>()),*] - } - } - }; - // empty case: - {$n:expr,} => { - impl<T> Distribution<[T; $n]> for Standard { - fn sample<R: Rng + ?Sized>(&self, _rng: &mut R) -> [T; $n] { [] } - } - }; -} - -array_impl!{32, T, T, T, T, T, T, T, T, T, T, T, T, T, T, T, T, T, T, T, T, T, T, T, T, T, T, T, T, T, T, T, T,} - -impl<T> Distribution<Option<T>> for Standard where Standard: Distribution<T> { - #[inline] - fn sample<R: Rng + ?Sized>(&self, rng: &mut R) -> Option<T> { - // UFCS is needed here: https://github.com/rust-lang/rust/issues/24066 - if rng.gen::<bool>() { - Some(rng.gen()) - } else { - None - } - } -} - -impl<T> Distribution<Wrapping<T>> for Standard where Standard: Distribution<T> { - #[inline] - fn sample<R: Rng + ?Sized>(&self, rng: &mut R) -> Wrapping<T> { - Wrapping(rng.gen()) - } -} - - -#[cfg(test)] -mod tests { - use {Rng, RngCore, Standard}; - use distributions::Alphanumeric; - #[cfg(all(not(feature="std"), feature="alloc"))] use alloc::string::String; - - #[test] - fn test_misc() { - let rng: &mut RngCore = &mut ::test::rng(820); - - rng.sample::<char, _>(Standard); - rng.sample::<bool, _>(Standard); - } - - #[cfg(feature="alloc")] - #[test] - fn test_chars() { - use core::iter; - let mut rng = ::test::rng(805); - - // Test by generating a relatively large number of chars, so we also - // take the rejection sampling path. - let word: String = iter::repeat(()) - .map(|()| rng.gen::<char>()).take(1000).collect(); - assert!(word.len() != 0); - } - - #[test] - fn test_alphanumeric() { - let mut rng = ::test::rng(806); - - // Test by generating a relatively large number of chars, so we also - // take the rejection sampling path. - let mut incorrect = false; - for _ in 0..100 { - let c = rng.sample(Alphanumeric); - incorrect |= !((c >= '0' && c <= '9') || - (c >= 'A' && c <= 'Z') || - (c >= 'a' && c <= 'z') ); - } - assert!(incorrect == false); - } -} diff --git a/rand/src/distributions/pareto.rs b/rand/src/distributions/pareto.rs deleted file mode 100644 index 744a157..0000000 --- a/rand/src/distributions/pareto.rs +++ /dev/null @@ -1,74 +0,0 @@ -// Copyright 2018 Developers of the Rand project. -// -// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or -// https://www.apache.org/licenses/LICENSE-2.0> or the MIT license -// <LICENSE-MIT or https://opensource.org/licenses/MIT>, at your -// option. This file may not be copied, modified, or distributed -// except according to those terms. - -//! The Pareto distribution. - -use Rng; -use distributions::{Distribution, OpenClosed01}; - -/// Samples floating-point numbers according to the Pareto distribution -/// -/// # Example -/// ``` -/// use rand::prelude::*; -/// use rand::distributions::Pareto; -/// -/// let val: f64 = SmallRng::from_entropy().sample(Pareto::new(1., 2.)); -/// println!("{}", val); -/// ``` -#[derive(Clone, Copy, Debug)] -pub struct Pareto { - scale: f64, - inv_neg_shape: f64, -} - -impl Pareto { - /// Construct a new Pareto distribution with given `scale` and `shape`. - /// - /// In the literature, `scale` is commonly written as x<sub>m</sub> or k and - /// `shape` is often written as α. - /// - /// # Panics - /// - /// `scale` and `shape` have to be non-zero and positive. - pub fn new(scale: f64, shape: f64) -> Pareto { - assert!((scale > 0.) & (shape > 0.)); - Pareto { scale, inv_neg_shape: -1.0 / shape } - } -} - -impl Distribution<f64> for Pareto { - fn sample<R: Rng + ?Sized>(&self, rng: &mut R) -> f64 { - let u: f64 = rng.sample(OpenClosed01); - self.scale * u.powf(self.inv_neg_shape) - } -} - -#[cfg(test)] -mod tests { - use distributions::Distribution; - use super::Pareto; - - #[test] - #[should_panic] - fn invalid() { - Pareto::new(0., 0.); - } - - #[test] - fn sample() { - let scale = 1.0; - let shape = 2.0; - let d = Pareto::new(scale, shape); - let mut rng = ::test::rng(1); - for _ in 0..1000 { - let r = d.sample(&mut rng); - assert!(r >= scale); - } - } -} diff --git a/rand/src/distributions/poisson.rs b/rand/src/distributions/poisson.rs deleted file mode 100644 index 1244caa..0000000 --- a/rand/src/distributions/poisson.rs +++ /dev/null @@ -1,157 +0,0 @@ -// Copyright 2018 Developers of the Rand project. -// Copyright 2016-2017 The Rust Project Developers. -// -// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or -// https://www.apache.org/licenses/LICENSE-2.0> or the MIT license -// <LICENSE-MIT or https://opensource.org/licenses/MIT>, at your -// option. This file may not be copied, modified, or distributed -// except according to those terms. - -//! The Poisson distribution. - -use Rng; -use distributions::{Distribution, Cauchy}; -use distributions::utils::log_gamma; - -/// The Poisson distribution `Poisson(lambda)`. -/// -/// This distribution has a density function: -/// `f(k) = lambda^k * exp(-lambda) / k!` for `k >= 0`. -/// -/// # Example -/// -/// ``` -/// use rand::distributions::{Poisson, Distribution}; -/// -/// let poi = Poisson::new(2.0); -/// let v = poi.sample(&mut rand::thread_rng()); -/// println!("{} is from a Poisson(2) distribution", v); -/// ``` -#[derive(Clone, Copy, Debug)] -pub struct Poisson { - lambda: f64, - // precalculated values - exp_lambda: f64, - log_lambda: f64, - sqrt_2lambda: f64, - magic_val: f64, -} - -impl Poisson { - /// Construct a new `Poisson` with the given shape parameter - /// `lambda`. Panics if `lambda <= 0`. - pub fn new(lambda: f64) -> Poisson { - assert!(lambda > 0.0, "Poisson::new called with lambda <= 0"); - let log_lambda = lambda.ln(); - Poisson { - lambda, - exp_lambda: (-lambda).exp(), - log_lambda, - sqrt_2lambda: (2.0 * lambda).sqrt(), - magic_val: lambda * log_lambda - log_gamma(1.0 + lambda), - } - } -} - -impl Distribution<u64> for Poisson { - fn sample<R: Rng + ?Sized>(&self, rng: &mut R) -> u64 { - // using the algorithm from Numerical Recipes in C - - // for low expected values use the Knuth method - if self.lambda < 12.0 { - let mut result = 0; - let mut p = 1.0; - while p > self.exp_lambda { - p *= rng.gen::<f64>(); - result += 1; - } - result - 1 - } - // high expected values - rejection method - else { - let mut int_result: u64; - - // we use the Cauchy distribution as the comparison distribution - // f(x) ~ 1/(1+x^2) - let cauchy = Cauchy::new(0.0, 1.0); - - loop { - let mut result; - let mut comp_dev; - - loop { - // draw from the Cauchy distribution - comp_dev = rng.sample(cauchy); - // shift the peak of the comparison ditribution - result = self.sqrt_2lambda * comp_dev + self.lambda; - // repeat the drawing until we are in the range of possible values - if result >= 0.0 { - break; - } - } - // now the result is a random variable greater than 0 with Cauchy distribution - // the result should be an integer value - result = result.floor(); - int_result = result as u64; - - // this is the ratio of the Poisson distribution to the comparison distribution - // the magic value scales the distribution function to a range of approximately 0-1 - // since it is not exact, we multiply the ratio by 0.9 to avoid ratios greater than 1 - // this doesn't change the resulting distribution, only increases the rate of failed drawings - let check = 0.9 * (1.0 + comp_dev * comp_dev) - * (result * self.log_lambda - log_gamma(1.0 + result) - self.magic_val).exp(); - - // check with uniform random value - if below the threshold, we are within the target distribution - if rng.gen::<f64>() <= check { - break; - } - } - int_result - } - } -} - -#[cfg(test)] -mod test { - use distributions::Distribution; - use super::Poisson; - - #[test] - fn test_poisson_10() { - let poisson = Poisson::new(10.0); - let mut rng = ::test::rng(123); - let mut sum = 0; - for _ in 0..1000 { - sum += poisson.sample(&mut rng); - } - let avg = (sum as f64) / 1000.0; - println!("Poisson average: {}", avg); - assert!((avg - 10.0).abs() < 0.5); // not 100% certain, but probable enough - } - - #[test] - fn test_poisson_15() { - // Take the 'high expected values' path - let poisson = Poisson::new(15.0); - let mut rng = ::test::rng(123); - let mut sum = 0; - for _ in 0..1000 { - sum += poisson.sample(&mut rng); - } - let avg = (sum as f64) / 1000.0; - println!("Poisson average: {}", avg); - assert!((avg - 15.0).abs() < 0.5); // not 100% certain, but probable enough - } - - #[test] - #[should_panic] - fn test_poisson_invalid_lambda_zero() { - Poisson::new(0.0); - } - - #[test] - #[should_panic] - fn test_poisson_invalid_lambda_neg() { - Poisson::new(-10.0); - } -} diff --git a/rand/src/distributions/triangular.rs b/rand/src/distributions/triangular.rs deleted file mode 100644 index a6eef5c..0000000 --- a/rand/src/distributions/triangular.rs +++ /dev/null @@ -1,86 +0,0 @@ -// Copyright 2018 Developers of the Rand project. -// -// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or -// https://www.apache.org/licenses/LICENSE-2.0> or the MIT license -// <LICENSE-MIT or https://opensource.org/licenses/MIT>, at your -// option. This file may not be copied, modified, or distributed -// except according to those terms. -//! The triangular distribution. - -use Rng; -use distributions::{Distribution, Standard}; - -/// The triangular distribution. -/// -/// # Example -/// -/// ```rust -/// use rand::distributions::{Triangular, Distribution}; -/// -/// let d = Triangular::new(0., 5., 2.5); -/// let v = d.sample(&mut rand::thread_rng()); -/// println!("{} is from a triangular distribution", v); -/// ``` -#[derive(Clone, Copy, Debug)] -pub struct Triangular { - min: f64, - max: f64, - mode: f64, -} - -impl Triangular { - /// Construct a new `Triangular` with minimum `min`, maximum `max` and mode - /// `mode`. - /// - /// # Panics - /// - /// If `max < mode`, `mode < max` or `max == min`. - /// - #[inline] - pub fn new(min: f64, max: f64, mode: f64) -> Triangular { - assert!(max >= mode); - assert!(mode >= min); - assert!(max != min); - Triangular { min, max, mode } - } -} - -impl Distribution<f64> for Triangular { - #[inline] - fn sample<R: Rng + ?Sized>(&self, rng: &mut R) -> f64 { - let f: f64 = rng.sample(Standard); - let diff_mode_min = self.mode - self.min; - let diff_max_min = self.max - self.min; - if f * diff_max_min < diff_mode_min { - self.min + (f * diff_max_min * diff_mode_min).sqrt() - } else { - self.max - ((1. - f) * diff_max_min * (self.max - self.mode)).sqrt() - } - } -} - -#[cfg(test)] -mod test { - use distributions::Distribution; - use super::Triangular; - - #[test] - fn test_new() { - for &(min, max, mode) in &[ - (-1., 1., 0.), (1., 2., 1.), (5., 25., 25.), (1e-5, 1e5, 1e-3), - (0., 1., 0.9), (-4., -0.5, -2.), (-13.039, 8.41, 1.17), - ] { - println!("{} {} {}", min, max, mode); - let _ = Triangular::new(min, max, mode); - } - } - - #[test] - fn test_sample() { - let norm = Triangular::new(0., 1., 0.5); - let mut rng = ::test::rng(1); - for _ in 0..1000 { - norm.sample(&mut rng); - } - } -} diff --git a/rand/src/distributions/uniform.rs b/rand/src/distributions/uniform.rs deleted file mode 100644 index ceed77d..0000000 --- a/rand/src/distributions/uniform.rs +++ /dev/null @@ -1,1298 +0,0 @@ -// Copyright 2018 Developers of the Rand project. -// Copyright 2017 The Rust Project Developers. -// -// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or -// https://www.apache.org/licenses/LICENSE-2.0> or the MIT license -// <LICENSE-MIT or https://opensource.org/licenses/MIT>, at your -// option. This file may not be copied, modified, or distributed -// except according to those terms. - -//! A distribution uniformly sampling numbers within a given range. -//! -//! [`Uniform`] is the standard distribution to sample uniformly from a range; -//! e.g. `Uniform::new_inclusive(1, 6)` can sample integers from 1 to 6, like a -//! standard die. [`Rng::gen_range`] supports any type supported by -//! [`Uniform`]. -//! -//! This distribution is provided with support for several primitive types -//! (all integer and floating-point types) as well as `std::time::Duration`, -//! and supports extension to user-defined types via a type-specific *back-end* -//! implementation. -//! -//! The types [`UniformInt`], [`UniformFloat`] and [`UniformDuration`] are the -//! back-ends supporting sampling from primitive integer and floating-point -//! ranges as well as from `std::time::Duration`; these types do not normally -//! need to be used directly (unless implementing a derived back-end). -//! -//! # Example usage -//! -//! ``` -//! use rand::{Rng, thread_rng}; -//! use rand::distributions::Uniform; -//! -//! let mut rng = thread_rng(); -//! let side = Uniform::new(-10.0, 10.0); -//! -//! // sample between 1 and 10 points -//! for _ in 0..rng.gen_range(1, 11) { -//! // sample a point from the square with sides -10 - 10 in two dimensions -//! let (x, y) = (rng.sample(side), rng.sample(side)); -//! println!("Point: {}, {}", x, y); -//! } -//! ``` -//! -//! # Extending `Uniform` to support a custom type -//! -//! To extend [`Uniform`] to support your own types, write a back-end which -//! implements the [`UniformSampler`] trait, then implement the [`SampleUniform`] -//! helper trait to "register" your back-end. See the `MyF32` example below. -//! -//! At a minimum, the back-end needs to store any parameters needed for sampling -//! (e.g. the target range) and implement `new`, `new_inclusive` and `sample`. -//! Those methods should include an assert to check the range is valid (i.e. -//! `low < high`). The example below merely wraps another back-end. -//! -//! The `new`, `new_inclusive` and `sample_single` functions use arguments of -//! type SampleBorrow<X> in order to support passing in values by reference or -//! by value. In the implementation of these functions, you can choose to -//! simply use the reference returned by [`SampleBorrow::borrow`], or you can choose -//! to copy or clone the value, whatever is appropriate for your type. -//! -//! ``` -//! use rand::prelude::*; -//! use rand::distributions::uniform::{Uniform, SampleUniform, -//! UniformSampler, UniformFloat, SampleBorrow}; -//! -//! struct MyF32(f32); -//! -//! #[derive(Clone, Copy, Debug)] -//! struct UniformMyF32 { -//! inner: UniformFloat<f32>, -//! } -//! -//! impl UniformSampler for UniformMyF32 { -//! type X = MyF32; -//! fn new<B1, B2>(low: B1, high: B2) -> Self -//! where B1: SampleBorrow<Self::X> + Sized, -//! B2: SampleBorrow<Self::X> + Sized -//! { -//! UniformMyF32 { -//! inner: UniformFloat::<f32>::new(low.borrow().0, high.borrow().0), -//! } -//! } -//! fn new_inclusive<B1, B2>(low: B1, high: B2) -> Self -//! where B1: SampleBorrow<Self::X> + Sized, -//! B2: SampleBorrow<Self::X> + Sized -//! { -//! UniformSampler::new(low, high) -//! } -//! fn sample<R: Rng + ?Sized>(&self, rng: &mut R) -> Self::X { -//! MyF32(self.inner.sample(rng)) -//! } -//! } -//! -//! impl SampleUniform for MyF32 { -//! type Sampler = UniformMyF32; -//! } -//! -//! let (low, high) = (MyF32(17.0f32), MyF32(22.0f32)); -//! let uniform = Uniform::new(low, high); -//! let x = uniform.sample(&mut thread_rng()); -//! ``` -//! -//! [`Uniform`]: struct.Uniform.html -//! [`Rng::gen_range`]: ../../trait.Rng.html#method.gen_range -//! [`SampleUniform`]: trait.SampleUniform.html -//! [`UniformSampler`]: trait.UniformSampler.html -//! [`UniformInt`]: struct.UniformInt.html -//! [`UniformFloat`]: struct.UniformFloat.html -//! [`UniformDuration`]: struct.UniformDuration.html -//! [`SampleBorrow::borrow`]: trait.SampleBorrow.html#method.borrow - -#[cfg(feature = "std")] -use std::time::Duration; -#[cfg(all(not(feature = "std"), rustc_1_25))] -use core::time::Duration; - -use Rng; -use distributions::Distribution; -use distributions::float::IntoFloat; -use distributions::utils::{WideningMultiply, FloatSIMDUtils, FloatAsSIMD, BoolAsSIMD}; - -#[cfg(not(feature = "std"))] -#[allow(unused_imports)] // rustc doesn't detect that this is actually used -use distributions::utils::Float; - - -#[cfg(feature="simd_support")] -use packed_simd::*; - -/// Sample values uniformly between two bounds. -/// -/// [`Uniform::new`] and [`Uniform::new_inclusive`] construct a uniform -/// distribution sampling from the given range; these functions may do extra -/// work up front to make sampling of multiple values faster. -/// -/// When sampling from a constant range, many calculations can happen at -/// compile-time and all methods should be fast; for floating-point ranges and -/// the full range of integer types this should have comparable performance to -/// the `Standard` distribution. -/// -/// Steps are taken to avoid bias which might be present in naive -/// implementations; for example `rng.gen::<u8>() % 170` samples from the range -/// `[0, 169]` but is twice as likely to select numbers less than 85 than other -/// values. Further, the implementations here give more weight to the high-bits -/// generated by the RNG than the low bits, since with some RNGs the low-bits -/// are of lower quality than the high bits. -/// -/// Implementations must sample in `[low, high)` range for -/// `Uniform::new(low, high)`, i.e., excluding `high`. In particular care must -/// be taken to ensure that rounding never results values `< low` or `>= high`. -/// -/// # Example -/// -/// ``` -/// use rand::distributions::{Distribution, Uniform}; -/// -/// fn main() { -/// let between = Uniform::from(10..10000); -/// let mut rng = rand::thread_rng(); -/// let mut sum = 0; -/// for _ in 0..1000 { -/// sum += between.sample(&mut rng); -/// } -/// println!("{}", sum); -/// } -/// ``` -/// -/// [`Uniform::new`]: struct.Uniform.html#method.new -/// [`Uniform::new_inclusive`]: struct.Uniform.html#method.new_inclusive -/// [`new`]: struct.Uniform.html#method.new -/// [`new_inclusive`]: struct.Uniform.html#method.new_inclusive -#[derive(Clone, Copy, Debug)] -pub struct Uniform<X: SampleUniform> { - inner: X::Sampler, -} - -impl<X: SampleUniform> Uniform<X> { - /// Create a new `Uniform` instance which samples uniformly from the half - /// open range `[low, high)` (excluding `high`). Panics if `low >= high`. - pub fn new<B1, B2>(low: B1, high: B2) -> Uniform<X> - where B1: SampleBorrow<X> + Sized, - B2: SampleBorrow<X> + Sized - { - Uniform { inner: X::Sampler::new(low, high) } - } - - /// Create a new `Uniform` instance which samples uniformly from the closed - /// range `[low, high]` (inclusive). Panics if `low > high`. - pub fn new_inclusive<B1, B2>(low: B1, high: B2) -> Uniform<X> - where B1: SampleBorrow<X> + Sized, - B2: SampleBorrow<X> + Sized - { - Uniform { inner: X::Sampler::new_inclusive(low, high) } - } -} - -impl<X: SampleUniform> Distribution<X> for Uniform<X> { - fn sample<R: Rng + ?Sized>(&self, rng: &mut R) -> X { - self.inner.sample(rng) - } -} - -/// Helper trait for creating objects using the correct implementation of -/// [`UniformSampler`] for the sampling type. -/// -/// See the [module documentation] on how to implement [`Uniform`] range -/// sampling for a custom type. -/// -/// [`UniformSampler`]: trait.UniformSampler.html -/// [module documentation]: index.html -/// [`Uniform`]: struct.Uniform.html -pub trait SampleUniform: Sized { - /// The `UniformSampler` implementation supporting type `X`. - type Sampler: UniformSampler<X = Self>; -} - -/// Helper trait handling actual uniform sampling. -/// -/// See the [module documentation] on how to implement [`Uniform`] range -/// sampling for a custom type. -/// -/// Implementation of [`sample_single`] is optional, and is only useful when -/// the implementation can be faster than `Self::new(low, high).sample(rng)`. -/// -/// [module documentation]: index.html -/// [`Uniform`]: struct.Uniform.html -/// [`sample_single`]: trait.UniformSampler.html#method.sample_single -pub trait UniformSampler: Sized { - /// The type sampled by this implementation. - type X; - - /// Construct self, with inclusive lower bound and exclusive upper bound - /// `[low, high)`. - /// - /// Usually users should not call this directly but instead use - /// `Uniform::new`, which asserts that `low < high` before calling this. - fn new<B1, B2>(low: B1, high: B2) -> Self - where B1: SampleBorrow<Self::X> + Sized, - B2: SampleBorrow<Self::X> + Sized; - - /// Construct self, with inclusive bounds `[low, high]`. - /// - /// Usually users should not call this directly but instead use - /// `Uniform::new_inclusive`, which asserts that `low <= high` before - /// calling this. - fn new_inclusive<B1, B2>(low: B1, high: B2) -> Self - where B1: SampleBorrow<Self::X> + Sized, - B2: SampleBorrow<Self::X> + Sized; - - /// Sample a value. - fn sample<R: Rng + ?Sized>(&self, rng: &mut R) -> Self::X; - - /// Sample a single value uniformly from a range with inclusive lower bound - /// and exclusive upper bound `[low, high)`. - /// - /// Usually users should not call this directly but instead use - /// `Uniform::sample_single`, which asserts that `low < high` before calling - /// this. - /// - /// Via this method, implementations can provide a method optimized for - /// sampling only a single value from the specified range. The default - /// implementation simply calls `UniformSampler::new` then `sample` on the - /// result. - fn sample_single<R: Rng + ?Sized, B1, B2>(low: B1, high: B2, rng: &mut R) - -> Self::X - where B1: SampleBorrow<Self::X> + Sized, - B2: SampleBorrow<Self::X> + Sized - { - let uniform: Self = UniformSampler::new(low, high); - uniform.sample(rng) - } -} - -impl<X: SampleUniform> From<::core::ops::Range<X>> for Uniform<X> { - fn from(r: ::core::ops::Range<X>) -> Uniform<X> { - Uniform::new(r.start, r.end) - } -} - -#[cfg(rustc_1_27)] -impl<X: SampleUniform> From<::core::ops::RangeInclusive<X>> for Uniform<X> { - fn from(r: ::core::ops::RangeInclusive<X>) -> Uniform<X> { - Uniform::new_inclusive(r.start(), r.end()) - } -} - -/// Helper trait similar to [`Borrow`] but implemented -/// only for SampleUniform and references to SampleUniform in -/// order to resolve ambiguity issues. -/// -/// [`Borrow`]: https://doc.rust-lang.org/std/borrow/trait.Borrow.html -pub trait SampleBorrow<Borrowed> { - /// Immutably borrows from an owned value. See [`Borrow::borrow`] - /// - /// [`Borrow::borrow`]: https://doc.rust-lang.org/std/borrow/trait.Borrow.html#tymethod.borrow - fn borrow(&self) -> &Borrowed; -} -impl<Borrowed> SampleBorrow<Borrowed> for Borrowed where Borrowed: SampleUniform { - #[inline(always)] - fn borrow(&self) -> &Borrowed { self } -} -impl<'a, Borrowed> SampleBorrow<Borrowed> for &'a Borrowed where Borrowed: SampleUniform { - #[inline(always)] - fn borrow(&self) -> &Borrowed { *self } -} - -//////////////////////////////////////////////////////////////////////////////// - -// What follows are all back-ends. - - -/// The back-end implementing [`UniformSampler`] for integer types. -/// -/// Unless you are implementing [`UniformSampler`] for your own type, this type -/// should not be used directly, use [`Uniform`] instead. -/// -/// # Implementation notes -/// -/// For a closed range, the number of possible numbers we should generate is -/// `range = (high - low + 1)`. It is not possible to end up with a uniform -/// distribution if we map *all* the random integers that can be generated to -/// this range. We have to map integers from a `zone` that is a multiple of the -/// range. The rest of the integers, that cause a bias, are rejected. -/// -/// The problem with `range` is that to cover the full range of the type, it has -/// to store `unsigned_max + 1`, which can't be represented. But if the range -/// covers the full range of the type, no modulus is needed. A range of size 0 -/// can't exist, so we use that to represent this special case. Wrapping -/// arithmetic even makes representing `unsigned_max + 1` as 0 simple. -/// -/// We don't calculate `zone` directly, but first calculate the number of -/// integers to reject. To handle `unsigned_max + 1` not fitting in the type, -/// we use: -/// `ints_to_reject = (unsigned_max + 1) % range;` -/// `ints_to_reject = (unsigned_max - range + 1) % range;` -/// -/// The smallest integer PRNGs generate is `u32`. That is why for small integer -/// sizes (`i8`/`u8` and `i16`/`u16`) there is an optimization: don't pick the -/// largest zone that can fit in the small type, but pick the largest zone that -/// can fit in an `u32`. `ints_to_reject` is always less than half the size of -/// the small integer. This means the first bit of `zone` is always 1, and so -/// are all the other preceding bits of a larger integer. The easiest way to -/// grow the `zone` for the larger type is to simply sign extend it. -/// -/// An alternative to using a modulus is widening multiply: After a widening -/// multiply by `range`, the result is in the high word. Then comparing the low -/// word against `zone` makes sure our distribution is uniform. -/// -/// [`UniformSampler`]: trait.UniformSampler.html -/// [`Uniform`]: struct.Uniform.html -#[derive(Clone, Copy, Debug)] -pub struct UniformInt<X> { - low: X, - range: X, - zone: X, -} - -macro_rules! uniform_int_impl { - ($ty:ty, $signed:ty, $unsigned:ident, - $i_large:ident, $u_large:ident) => { - impl SampleUniform for $ty { - type Sampler = UniformInt<$ty>; - } - - impl UniformSampler for UniformInt<$ty> { - // We play free and fast with unsigned vs signed here - // (when $ty is signed), but that's fine, since the - // contract of this macro is for $ty and $unsigned to be - // "bit-equal", so casting between them is a no-op. - - type X = $ty; - - #[inline] // if the range is constant, this helps LLVM to do the - // calculations at compile-time. - fn new<B1, B2>(low_b: B1, high_b: B2) -> Self - where B1: SampleBorrow<Self::X> + Sized, - B2: SampleBorrow<Self::X> + Sized - { - let low = *low_b.borrow(); - let high = *high_b.borrow(); - assert!(low < high, "Uniform::new called with `low >= high`"); - UniformSampler::new_inclusive(low, high - 1) - } - - #[inline] // if the range is constant, this helps LLVM to do the - // calculations at compile-time. - fn new_inclusive<B1, B2>(low_b: B1, high_b: B2) -> Self - where B1: SampleBorrow<Self::X> + Sized, - B2: SampleBorrow<Self::X> + Sized - { - let low = *low_b.borrow(); - let high = *high_b.borrow(); - assert!(low <= high, - "Uniform::new_inclusive called with `low > high`"); - let unsigned_max = ::core::$unsigned::MAX; - - let range = high.wrapping_sub(low).wrapping_add(1) as $unsigned; - let ints_to_reject = - if range > 0 { - (unsigned_max - range + 1) % range - } else { - 0 - }; - let zone = unsigned_max - ints_to_reject; - - UniformInt { - low: low, - // These are really $unsigned values, but store as $ty: - range: range as $ty, - zone: zone as $ty - } - } - - fn sample<R: Rng + ?Sized>(&self, rng: &mut R) -> Self::X { - let range = self.range as $unsigned as $u_large; - if range > 0 { - // Grow `zone` to fit a type of at least 32 bits, by - // sign-extending it (the first bit is always 1, so are all - // the preceding bits of the larger type). - // For types that already have the right size, all the - // casting is a no-op. - let zone = self.zone as $signed as $i_large as $u_large; - loop { - let v: $u_large = rng.gen(); - let (hi, lo) = v.wmul(range); - if lo <= zone { - return self.low.wrapping_add(hi as $ty); - } - } - } else { - // Sample from the entire integer range. - rng.gen() - } - } - - fn sample_single<R: Rng + ?Sized, B1, B2>(low_b: B1, high_b: B2, rng: &mut R) - -> Self::X - where B1: SampleBorrow<Self::X> + Sized, - B2: SampleBorrow<Self::X> + Sized - { - let low = *low_b.borrow(); - let high = *high_b.borrow(); - assert!(low < high, - "Uniform::sample_single called with low >= high"); - let range = high.wrapping_sub(low) as $unsigned as $u_large; - let zone = - if ::core::$unsigned::MAX <= ::core::u16::MAX as $unsigned { - // Using a modulus is faster than the approximation for - // i8 and i16. I suppose we trade the cost of one - // modulus for near-perfect branch prediction. - let unsigned_max: $u_large = ::core::$u_large::MAX; - let ints_to_reject = (unsigned_max - range + 1) % range; - unsigned_max - ints_to_reject - } else { - // conservative but fast approximation. `- 1` is necessary to allow the - // same comparison without bias. - (range << range.leading_zeros()).wrapping_sub(1) - }; - - loop { - let v: $u_large = rng.gen(); - let (hi, lo) = v.wmul(range); - if lo <= zone { - return low.wrapping_add(hi as $ty); - } - } - } - } - } -} - -uniform_int_impl! { i8, i8, u8, i32, u32 } -uniform_int_impl! { i16, i16, u16, i32, u32 } -uniform_int_impl! { i32, i32, u32, i32, u32 } -uniform_int_impl! { i64, i64, u64, i64, u64 } -#[cfg(all(rustc_1_26, not(target_os = "emscripten")))] -uniform_int_impl! { i128, i128, u128, u128, u128 } -uniform_int_impl! { isize, isize, usize, isize, usize } -uniform_int_impl! { u8, i8, u8, i32, u32 } -uniform_int_impl! { u16, i16, u16, i32, u32 } -uniform_int_impl! { u32, i32, u32, i32, u32 } -uniform_int_impl! { u64, i64, u64, i64, u64 } -uniform_int_impl! { usize, isize, usize, isize, usize } -#[cfg(all(rustc_1_26, not(target_os = "emscripten")))] -uniform_int_impl! { u128, u128, u128, i128, u128 } - -#[cfg(all(feature = "simd_support", feature = "nightly"))] -macro_rules! uniform_simd_int_impl { - ($ty:ident, $unsigned:ident, $u_scalar:ident) => { - // The "pick the largest zone that can fit in an `u32`" optimization - // is less useful here. Multiple lanes complicate things, we don't - // know the PRNG's minimal output size, and casting to a larger vector - // is generally a bad idea for SIMD performance. The user can still - // implement it manually. - - // TODO: look into `Uniform::<u32x4>::new(0u32, 100)` functionality - // perhaps `impl SampleUniform for $u_scalar`? - impl SampleUniform for $ty { - type Sampler = UniformInt<$ty>; - } - - impl UniformSampler for UniformInt<$ty> { - type X = $ty; - - #[inline] // if the range is constant, this helps LLVM to do the - // calculations at compile-time. - fn new<B1, B2>(low_b: B1, high_b: B2) -> Self - where B1: SampleBorrow<Self::X> + Sized, - B2: SampleBorrow<Self::X> + Sized - { - let low = *low_b.borrow(); - let high = *high_b.borrow(); - assert!(low.lt(high).all(), "Uniform::new called with `low >= high`"); - UniformSampler::new_inclusive(low, high - 1) - } - - #[inline] // if the range is constant, this helps LLVM to do the - // calculations at compile-time. - fn new_inclusive<B1, B2>(low_b: B1, high_b: B2) -> Self - where B1: SampleBorrow<Self::X> + Sized, - B2: SampleBorrow<Self::X> + Sized - { - let low = *low_b.borrow(); - let high = *high_b.borrow(); - assert!(low.le(high).all(), - "Uniform::new_inclusive called with `low > high`"); - let unsigned_max = ::core::$u_scalar::MAX; - - // NOTE: these may need to be replaced with explicitly - // wrapping operations if `packed_simd` changes - let range: $unsigned = ((high - low) + 1).cast(); - // `% 0` will panic at runtime. - let not_full_range = range.gt($unsigned::splat(0)); - // replacing 0 with `unsigned_max` allows a faster `select` - // with bitwise OR - let modulo = not_full_range.select(range, $unsigned::splat(unsigned_max)); - // wrapping addition - let ints_to_reject = (unsigned_max - range + 1) % modulo; - // When `range` is 0, `lo` of `v.wmul(range)` will always be - // zero which means only one sample is needed. - let zone = unsigned_max - ints_to_reject; - - UniformInt { - low: low, - // These are really $unsigned values, but store as $ty: - range: range.cast(), - zone: zone.cast(), - } - } - - fn sample<R: Rng + ?Sized>(&self, rng: &mut R) -> Self::X { - let range: $unsigned = self.range.cast(); - let zone: $unsigned = self.zone.cast(); - - // This might seem very slow, generating a whole new - // SIMD vector for every sample rejection. For most uses - // though, the chance of rejection is small and provides good - // general performance. With multiple lanes, that chance is - // multiplied. To mitigate this, we replace only the lanes of - // the vector which fail, iteratively reducing the chance of - // rejection. The replacement method does however add a little - // overhead. Benchmarking or calculating probabilities might - // reveal contexts where this replacement method is slower. - let mut v: $unsigned = rng.gen(); - loop { - let (hi, lo) = v.wmul(range); - let mask = lo.le(zone); - if mask.all() { - let hi: $ty = hi.cast(); - // wrapping addition - let result = self.low + hi; - // `select` here compiles to a blend operation - // When `range.eq(0).none()` the compare and blend - // operations are avoided. - let v: $ty = v.cast(); - return range.gt($unsigned::splat(0)).select(result, v); - } - // Replace only the failing lanes - v = mask.select(v, rng.gen()); - } - } - } - }; - - // bulk implementation - ($(($unsigned:ident, $signed:ident),)+ $u_scalar:ident) => { - $( - uniform_simd_int_impl!($unsigned, $unsigned, $u_scalar); - uniform_simd_int_impl!($signed, $unsigned, $u_scalar); - )+ - }; -} - -#[cfg(all(feature = "simd_support", feature = "nightly"))] -uniform_simd_int_impl! { - (u64x2, i64x2), - (u64x4, i64x4), - (u64x8, i64x8), - u64 -} - -#[cfg(all(feature = "simd_support", feature = "nightly"))] -uniform_simd_int_impl! { - (u32x2, i32x2), - (u32x4, i32x4), - (u32x8, i32x8), - (u32x16, i32x16), - u32 -} - -#[cfg(all(feature = "simd_support", feature = "nightly"))] -uniform_simd_int_impl! { - (u16x2, i16x2), - (u16x4, i16x4), - (u16x8, i16x8), - (u16x16, i16x16), - (u16x32, i16x32), - u16 -} - -#[cfg(all(feature = "simd_support", feature = "nightly"))] -uniform_simd_int_impl! { - (u8x2, i8x2), - (u8x4, i8x4), - (u8x8, i8x8), - (u8x16, i8x16), - (u8x32, i8x32), - (u8x64, i8x64), - u8 -} - - -/// The back-end implementing [`UniformSampler`] for floating-point types. -/// -/// Unless you are implementing [`UniformSampler`] for your own type, this type -/// should not be used directly, use [`Uniform`] instead. -/// -/// # Implementation notes -/// -/// Instead of generating a float in the `[0, 1)` range using [`Standard`], the -/// `UniformFloat` implementation converts the output of an PRNG itself. This -/// way one or two steps can be optimized out. -/// -/// The floats are first converted to a value in the `[1, 2)` interval using a -/// transmute-based method, and then mapped to the expected range with a -/// multiply and addition. Values produced this way have what equals 22 bits of -/// random digits for an `f32`, and 52 for an `f64`. -/// -/// [`UniformSampler`]: trait.UniformSampler.html -/// [`new`]: trait.UniformSampler.html#tymethod.new -/// [`new_inclusive`]: trait.UniformSampler.html#tymethod.new_inclusive -/// [`Uniform`]: struct.Uniform.html -/// [`Standard`]: ../struct.Standard.html -#[derive(Clone, Copy, Debug)] -pub struct UniformFloat<X> { - low: X, - scale: X, -} - -macro_rules! uniform_float_impl { - ($ty:ty, $uty:ident, $f_scalar:ident, $u_scalar:ident, $bits_to_discard:expr) => { - impl SampleUniform for $ty { - type Sampler = UniformFloat<$ty>; - } - - impl UniformSampler for UniformFloat<$ty> { - type X = $ty; - - fn new<B1, B2>(low_b: B1, high_b: B2) -> Self - where B1: SampleBorrow<Self::X> + Sized, - B2: SampleBorrow<Self::X> + Sized - { - let low = *low_b.borrow(); - let high = *high_b.borrow(); - assert!(low.all_lt(high), - "Uniform::new called with `low >= high`"); - assert!(low.all_finite() && high.all_finite(), - "Uniform::new called with non-finite boundaries"); - let max_rand = <$ty>::splat((::core::$u_scalar::MAX >> $bits_to_discard) - .into_float_with_exponent(0) - 1.0); - - let mut scale = high - low; - - loop { - let mask = (scale * max_rand + low).ge_mask(high); - if mask.none() { - break; - } - scale = scale.decrease_masked(mask); - } - - debug_assert!(<$ty>::splat(0.0).all_le(scale)); - - UniformFloat { low, scale } - } - - fn new_inclusive<B1, B2>(low_b: B1, high_b: B2) -> Self - where B1: SampleBorrow<Self::X> + Sized, - B2: SampleBorrow<Self::X> + Sized - { - let low = *low_b.borrow(); - let high = *high_b.borrow(); - assert!(low.all_le(high), - "Uniform::new_inclusive called with `low > high`"); - assert!(low.all_finite() && high.all_finite(), - "Uniform::new_inclusive called with non-finite boundaries"); - let max_rand = <$ty>::splat((::core::$u_scalar::MAX >> $bits_to_discard) - .into_float_with_exponent(0) - 1.0); - - let mut scale = (high - low) / max_rand; - - loop { - let mask = (scale * max_rand + low).gt_mask(high); - if mask.none() { - break; - } - scale = scale.decrease_masked(mask); - } - - debug_assert!(<$ty>::splat(0.0).all_le(scale)); - - UniformFloat { low, scale } - } - - fn sample<R: Rng + ?Sized>(&self, rng: &mut R) -> Self::X { - // Generate a value in the range [1, 2) - let value1_2 = (rng.gen::<$uty>() >> $bits_to_discard) - .into_float_with_exponent(0); - - // Get a value in the range [0, 1) in order to avoid - // overflowing into infinity when multiplying with scale - let value0_1 = value1_2 - 1.0; - - // We don't use `f64::mul_add`, because it is not available with - // `no_std`. Furthermore, it is slower for some targets (but - // faster for others). However, the order of multiplication and - // addition is important, because on some platforms (e.g. ARM) - // it will be optimized to a single (non-FMA) instruction. - value0_1 * self.scale + self.low - } - - #[inline] - fn sample_single<R: Rng + ?Sized, B1, B2>(low_b: B1, high_b: B2, rng: &mut R) - -> Self::X - where B1: SampleBorrow<Self::X> + Sized, - B2: SampleBorrow<Self::X> + Sized - { - let low = *low_b.borrow(); - let high = *high_b.borrow(); - assert!(low.all_lt(high), - "Uniform::sample_single called with low >= high"); - let mut scale = high - low; - - loop { - // Generate a value in the range [1, 2) - let value1_2 = (rng.gen::<$uty>() >> $bits_to_discard) - .into_float_with_exponent(0); - - // Get a value in the range [0, 1) in order to avoid - // overflowing into infinity when multiplying with scale - let value0_1 = value1_2 - 1.0; - - // Doing multiply before addition allows some architectures - // to use a single instruction. - let res = value0_1 * scale + low; - - debug_assert!(low.all_le(res) || !scale.all_finite()); - if res.all_lt(high) { - return res; - } - - // This handles a number of edge cases. - // * `low` or `high` is NaN. In this case `scale` and - // `res` are going to end up as NaN. - // * `low` is negative infinity and `high` is finite. - // `scale` is going to be infinite and `res` will be - // NaN. - // * `high` is positive infinity and `low` is finite. - // `scale` is going to be infinite and `res` will - // be infinite or NaN (if value0_1 is 0). - // * `low` is negative infinity and `high` is positive - // infinity. `scale` will be infinite and `res` will - // be NaN. - // * `low` and `high` are finite, but `high - low` - // overflows to infinite. `scale` will be infinite - // and `res` will be infinite or NaN (if value0_1 is 0). - // So if `high` or `low` are non-finite, we are guaranteed - // to fail the `res < high` check above and end up here. - // - // While we technically should check for non-finite `low` - // and `high` before entering the loop, by doing the checks - // here instead, we allow the common case to avoid these - // checks. But we are still guaranteed that if `low` or - // `high` are non-finite we'll end up here and can do the - // appropriate checks. - // - // Likewise `high - low` overflowing to infinity is also - // rare, so handle it here after the common case. - let mask = !scale.finite_mask(); - if mask.any() { - assert!(low.all_finite() && high.all_finite(), - "Uniform::sample_single called with non-finite boundaries"); - scale = scale.decrease_masked(mask); - } - } - } - } - } -} - -uniform_float_impl! { f32, u32, f32, u32, 32 - 23 } -uniform_float_impl! { f64, u64, f64, u64, 64 - 52 } - -#[cfg(feature="simd_support")] -uniform_float_impl! { f32x2, u32x2, f32, u32, 32 - 23 } -#[cfg(feature="simd_support")] -uniform_float_impl! { f32x4, u32x4, f32, u32, 32 - 23 } -#[cfg(feature="simd_support")] -uniform_float_impl! { f32x8, u32x8, f32, u32, 32 - 23 } -#[cfg(feature="simd_support")] -uniform_float_impl! { f32x16, u32x16, f32, u32, 32 - 23 } - -#[cfg(feature="simd_support")] -uniform_float_impl! { f64x2, u64x2, f64, u64, 64 - 52 } -#[cfg(feature="simd_support")] -uniform_float_impl! { f64x4, u64x4, f64, u64, 64 - 52 } -#[cfg(feature="simd_support")] -uniform_float_impl! { f64x8, u64x8, f64, u64, 64 - 52 } - - - -/// The back-end implementing [`UniformSampler`] for `Duration`. -/// -/// Unless you are implementing [`UniformSampler`] for your own types, this type -/// should not be used directly, use [`Uniform`] instead. -/// -/// [`UniformSampler`]: trait.UniformSampler.html -/// [`Uniform`]: struct.Uniform.html -#[cfg(any(feature = "std", rustc_1_25))] -#[derive(Clone, Copy, Debug)] -pub struct UniformDuration { - mode: UniformDurationMode, - offset: u32, -} - -#[cfg(any(feature = "std", rustc_1_25))] -#[derive(Debug, Copy, Clone)] -enum UniformDurationMode { - Small { - secs: u64, - nanos: Uniform<u32>, - }, - Medium { - nanos: Uniform<u64>, - }, - Large { - max_secs: u64, - max_nanos: u32, - secs: Uniform<u64>, - } -} - -#[cfg(any(feature = "std", rustc_1_25))] -impl SampleUniform for Duration { - type Sampler = UniformDuration; -} - -#[cfg(any(feature = "std", rustc_1_25))] -impl UniformSampler for UniformDuration { - type X = Duration; - - #[inline] - fn new<B1, B2>(low_b: B1, high_b: B2) -> Self - where B1: SampleBorrow<Self::X> + Sized, - B2: SampleBorrow<Self::X> + Sized - { - let low = *low_b.borrow(); - let high = *high_b.borrow(); - assert!(low < high, "Uniform::new called with `low >= high`"); - UniformDuration::new_inclusive(low, high - Duration::new(0, 1)) - } - - #[inline] - fn new_inclusive<B1, B2>(low_b: B1, high_b: B2) -> Self - where B1: SampleBorrow<Self::X> + Sized, - B2: SampleBorrow<Self::X> + Sized - { - let low = *low_b.borrow(); - let high = *high_b.borrow(); - assert!(low <= high, "Uniform::new_inclusive called with `low > high`"); - - let low_s = low.as_secs(); - let low_n = low.subsec_nanos(); - let mut high_s = high.as_secs(); - let mut high_n = high.subsec_nanos(); - - if high_n < low_n { - high_s = high_s - 1; - high_n = high_n + 1_000_000_000; - } - - let mode = if low_s == high_s { - UniformDurationMode::Small { - secs: low_s, - nanos: Uniform::new_inclusive(low_n, high_n), - } - } else { - let max = high_s - .checked_mul(1_000_000_000) - .and_then(|n| n.checked_add(high_n as u64)); - - if let Some(higher_bound) = max { - let lower_bound = low_s * 1_000_000_000 + low_n as u64; - UniformDurationMode::Medium { - nanos: Uniform::new_inclusive(lower_bound, higher_bound), - } - } else { - // An offset is applied to simplify generation of nanoseconds - let max_nanos = high_n - low_n; - UniformDurationMode::Large { - max_secs: high_s, - max_nanos, - secs: Uniform::new_inclusive(low_s, high_s), - } - } - }; - UniformDuration { - mode, - offset: low_n, - } - } - - #[inline] - fn sample<R: Rng + ?Sized>(&self, rng: &mut R) -> Duration { - match self.mode { - UniformDurationMode::Small { secs, nanos } => { - let n = nanos.sample(rng); - Duration::new(secs, n) - } - UniformDurationMode::Medium { nanos } => { - let nanos = nanos.sample(rng); - Duration::new(nanos / 1_000_000_000, (nanos % 1_000_000_000) as u32) - } - UniformDurationMode::Large { max_secs, max_nanos, secs } => { - // constant folding means this is at least as fast as `gen_range` - let nano_range = Uniform::new(0, 1_000_000_000); - loop { - let s = secs.sample(rng); - let n = nano_range.sample(rng); - if !(s == max_secs && n > max_nanos) { - let sum = n + self.offset; - break Duration::new(s, sum); - } - } - } - } - } -} - -#[cfg(test)] -mod tests { - use Rng; - use rngs::mock::StepRng; - use distributions::uniform::Uniform; - use distributions::utils::FloatAsSIMD; - #[cfg(feature="simd_support")] use packed_simd::*; - - #[should_panic] - #[test] - fn test_uniform_bad_limits_equal_int() { - Uniform::new(10, 10); - } - - #[test] - fn test_uniform_good_limits_equal_int() { - let mut rng = ::test::rng(804); - let dist = Uniform::new_inclusive(10, 10); - for _ in 0..20 { - assert_eq!(rng.sample(dist), 10); - } - } - - #[should_panic] - #[test] - fn test_uniform_bad_limits_flipped_int() { - Uniform::new(10, 5); - } - - #[test] - fn test_integers() { - use core::{i8, i16, i32, i64, isize}; - use core::{u8, u16, u32, u64, usize}; - #[cfg(all(rustc_1_26, not(target_os = "emscripten")))] - use core::{i128, u128}; - - let mut rng = ::test::rng(251); - macro_rules! t { - ($ty:ident, $v:expr, $le:expr, $lt:expr) => {{ - for &(low, high) in $v.iter() { - let my_uniform = Uniform::new(low, high); - for _ in 0..1000 { - let v: $ty = rng.sample(my_uniform); - assert!($le(low, v) && $lt(v, high)); - } - - let my_uniform = Uniform::new_inclusive(low, high); - for _ in 0..1000 { - let v: $ty = rng.sample(my_uniform); - assert!($le(low, v) && $le(v, high)); - } - - let my_uniform = Uniform::new(&low, high); - for _ in 0..1000 { - let v: $ty = rng.sample(my_uniform); - assert!($le(low, v) && $lt(v, high)); - } - - let my_uniform = Uniform::new_inclusive(&low, &high); - for _ in 0..1000 { - let v: $ty = rng.sample(my_uniform); - assert!($le(low, v) && $le(v, high)); - } - - for _ in 0..1000 { - let v: $ty = rng.gen_range(low, high); - assert!($le(low, v) && $lt(v, high)); - } - } - }}; - - // scalar bulk - ($($ty:ident),*) => {{ - $(t!( - $ty, - [(0, 10), (10, 127), ($ty::MIN, $ty::MAX)], - |x, y| x <= y, - |x, y| x < y - );)* - }}; - - // simd bulk - ($($ty:ident),* => $scalar:ident) => {{ - $(t!( - $ty, - [ - ($ty::splat(0), $ty::splat(10)), - ($ty::splat(10), $ty::splat(127)), - ($ty::splat($scalar::MIN), $ty::splat($scalar::MAX)), - ], - |x: $ty, y| x.le(y).all(), - |x: $ty, y| x.lt(y).all() - );)* - }}; - } - t!(i8, i16, i32, i64, isize, - u8, u16, u32, u64, usize); - #[cfg(all(rustc_1_26, not(target_os = "emscripten")))] - t!(i128, u128); - - #[cfg(all(feature = "simd_support", feature = "nightly"))] - { - t!(u8x2, u8x4, u8x8, u8x16, u8x32, u8x64 => u8); - t!(i8x2, i8x4, i8x8, i8x16, i8x32, i8x64 => i8); - t!(u16x2, u16x4, u16x8, u16x16, u16x32 => u16); - t!(i16x2, i16x4, i16x8, i16x16, i16x32 => i16); - t!(u32x2, u32x4, u32x8, u32x16 => u32); - t!(i32x2, i32x4, i32x8, i32x16 => i32); - t!(u64x2, u64x4, u64x8 => u64); - t!(i64x2, i64x4, i64x8 => i64); - } - } - - #[test] - fn test_floats() { - let mut rng = ::test::rng(252); - let mut zero_rng = StepRng::new(0, 0); - let mut max_rng = StepRng::new(0xffff_ffff_ffff_ffff, 0); - macro_rules! t { - ($ty:ty, $f_scalar:ident, $bits_shifted:expr) => {{ - let v: &[($f_scalar, $f_scalar)]= - &[(0.0, 100.0), - (-1e35, -1e25), - (1e-35, 1e-25), - (-1e35, 1e35), - (<$f_scalar>::from_bits(0), <$f_scalar>::from_bits(3)), - (-<$f_scalar>::from_bits(10), -<$f_scalar>::from_bits(1)), - (-<$f_scalar>::from_bits(5), 0.0), - (-<$f_scalar>::from_bits(7), -0.0), - (10.0, ::core::$f_scalar::MAX), - (-100.0, ::core::$f_scalar::MAX), - (-::core::$f_scalar::MAX / 5.0, ::core::$f_scalar::MAX), - (-::core::$f_scalar::MAX, ::core::$f_scalar::MAX / 5.0), - (-::core::$f_scalar::MAX * 0.8, ::core::$f_scalar::MAX * 0.7), - (-::core::$f_scalar::MAX, ::core::$f_scalar::MAX), - ]; - for &(low_scalar, high_scalar) in v.iter() { - for lane in 0..<$ty>::lanes() { - let low = <$ty>::splat(0.0 as $f_scalar).replace(lane, low_scalar); - let high = <$ty>::splat(1.0 as $f_scalar).replace(lane, high_scalar); - let my_uniform = Uniform::new(low, high); - let my_incl_uniform = Uniform::new_inclusive(low, high); - for _ in 0..100 { - let v = rng.sample(my_uniform).extract(lane); - assert!(low_scalar <= v && v < high_scalar); - let v = rng.sample(my_incl_uniform).extract(lane); - assert!(low_scalar <= v && v <= high_scalar); - let v = rng.gen_range(low, high).extract(lane); - assert!(low_scalar <= v && v < high_scalar); - } - - assert_eq!(rng.sample(Uniform::new_inclusive(low, low)).extract(lane), low_scalar); - - assert_eq!(zero_rng.sample(my_uniform).extract(lane), low_scalar); - assert_eq!(zero_rng.sample(my_incl_uniform).extract(lane), low_scalar); - assert_eq!(zero_rng.gen_range(low, high).extract(lane), low_scalar); - assert!(max_rng.sample(my_uniform).extract(lane) < high_scalar); - assert!(max_rng.sample(my_incl_uniform).extract(lane) <= high_scalar); - - // Don't run this test for really tiny differences between high and low - // since for those rounding might result in selecting high for a very - // long time. - if (high_scalar - low_scalar) > 0.0001 { - let mut lowering_max_rng = - StepRng::new(0xffff_ffff_ffff_ffff, - (-1i64 << $bits_shifted) as u64); - assert!(lowering_max_rng.gen_range(low, high).extract(lane) < high_scalar); - } - } - } - - assert_eq!(rng.sample(Uniform::new_inclusive(::core::$f_scalar::MAX, - ::core::$f_scalar::MAX)), - ::core::$f_scalar::MAX); - assert_eq!(rng.sample(Uniform::new_inclusive(-::core::$f_scalar::MAX, - -::core::$f_scalar::MAX)), - -::core::$f_scalar::MAX); - }} - } - - t!(f32, f32, 32 - 23); - t!(f64, f64, 64 - 52); - #[cfg(feature="simd_support")] - { - t!(f32x2, f32, 32 - 23); - t!(f32x4, f32, 32 - 23); - t!(f32x8, f32, 32 - 23); - t!(f32x16, f32, 32 - 23); - t!(f64x2, f64, 64 - 52); - t!(f64x4, f64, 64 - 52); - t!(f64x8, f64, 64 - 52); - } - } - - #[test] - #[cfg(all(feature="std", - not(target_arch = "wasm32"), - not(target_arch = "asmjs")))] - fn test_float_assertions() { - use std::panic::catch_unwind; - use super::SampleUniform; - fn range<T: SampleUniform>(low: T, high: T) { - let mut rng = ::test::rng(253); - rng.gen_range(low, high); - } - - macro_rules! t { - ($ty:ident, $f_scalar:ident) => {{ - let v: &[($f_scalar, $f_scalar)] = - &[(::std::$f_scalar::NAN, 0.0), - (1.0, ::std::$f_scalar::NAN), - (::std::$f_scalar::NAN, ::std::$f_scalar::NAN), - (1.0, 0.5), - (::std::$f_scalar::MAX, -::std::$f_scalar::MAX), - (::std::$f_scalar::INFINITY, ::std::$f_scalar::INFINITY), - (::std::$f_scalar::NEG_INFINITY, ::std::$f_scalar::NEG_INFINITY), - (::std::$f_scalar::NEG_INFINITY, 5.0), - (5.0, ::std::$f_scalar::INFINITY), - (::std::$f_scalar::NAN, ::std::$f_scalar::INFINITY), - (::std::$f_scalar::NEG_INFINITY, ::std::$f_scalar::NAN), - (::std::$f_scalar::NEG_INFINITY, ::std::$f_scalar::INFINITY), - ]; - for &(low_scalar, high_scalar) in v.iter() { - for lane in 0..<$ty>::lanes() { - let low = <$ty>::splat(0.0 as $f_scalar).replace(lane, low_scalar); - let high = <$ty>::splat(1.0 as $f_scalar).replace(lane, high_scalar); - assert!(catch_unwind(|| range(low, high)).is_err()); - assert!(catch_unwind(|| Uniform::new(low, high)).is_err()); - assert!(catch_unwind(|| Uniform::new_inclusive(low, high)).is_err()); - assert!(catch_unwind(|| range(low, low)).is_err()); - assert!(catch_unwind(|| Uniform::new(low, low)).is_err()); - } - } - }} - } - - t!(f32, f32); - t!(f64, f64); - #[cfg(feature="simd_support")] - { - t!(f32x2, f32); - t!(f32x4, f32); - t!(f32x8, f32); - t!(f32x16, f32); - t!(f64x2, f64); - t!(f64x4, f64); - t!(f64x8, f64); - } - } - - - #[test] - #[cfg(any(feature = "std", rustc_1_25))] - fn test_durations() { - #[cfg(feature = "std")] - use std::time::Duration; - #[cfg(all(not(feature = "std"), rustc_1_25))] - use core::time::Duration; - - let mut rng = ::test::rng(253); - - let v = &[(Duration::new(10, 50000), Duration::new(100, 1234)), - (Duration::new(0, 100), Duration::new(1, 50)), - (Duration::new(0, 0), Duration::new(u64::max_value(), 999_999_999))]; - for &(low, high) in v.iter() { - let my_uniform = Uniform::new(low, high); - for _ in 0..1000 { - let v = rng.sample(my_uniform); - assert!(low <= v && v < high); - } - } - } - - #[test] - fn test_custom_uniform() { - use distributions::uniform::{UniformSampler, UniformFloat, SampleUniform, SampleBorrow}; - #[derive(Clone, Copy, PartialEq, PartialOrd)] - struct MyF32 { - x: f32, - } - #[derive(Clone, Copy, Debug)] - struct UniformMyF32 { - inner: UniformFloat<f32>, - } - impl UniformSampler for UniformMyF32 { - type X = MyF32; - fn new<B1, B2>(low: B1, high: B2) -> Self - where B1: SampleBorrow<Self::X> + Sized, - B2: SampleBorrow<Self::X> + Sized - { - UniformMyF32 { - inner: UniformFloat::<f32>::new(low.borrow().x, high.borrow().x), - } - } - fn new_inclusive<B1, B2>(low: B1, high: B2) -> Self - where B1: SampleBorrow<Self::X> + Sized, - B2: SampleBorrow<Self::X> + Sized - { - UniformSampler::new(low, high) - } - fn sample<R: Rng + ?Sized>(&self, rng: &mut R) -> Self::X { - MyF32 { x: self.inner.sample(rng) } - } - } - impl SampleUniform for MyF32 { - type Sampler = UniformMyF32; - } - - let (low, high) = (MyF32{ x: 17.0f32 }, MyF32{ x: 22.0f32 }); - let uniform = Uniform::new(low, high); - let mut rng = ::test::rng(804); - for _ in 0..100 { - let x: MyF32 = rng.sample(uniform); - assert!(low <= x && x < high); - } - } - - #[test] - fn test_uniform_from_std_range() { - let r = Uniform::from(2u32..7); - assert_eq!(r.inner.low, 2); - assert_eq!(r.inner.range, 5); - let r = Uniform::from(2.0f64..7.0); - assert_eq!(r.inner.low, 2.0); - assert_eq!(r.inner.scale, 5.0); - } - - #[cfg(rustc_1_27)] - #[test] - fn test_uniform_from_std_range_inclusive() { - let r = Uniform::from(2u32..=6); - assert_eq!(r.inner.low, 2); - assert_eq!(r.inner.range, 5); - let r = Uniform::from(2.0f64..=7.0); - assert_eq!(r.inner.low, 2.0); - assert!(r.inner.scale > 5.0); - assert!(r.inner.scale < 5.0 + 1e-14); - } -} diff --git a/rand/src/distributions/unit_circle.rs b/rand/src/distributions/unit_circle.rs deleted file mode 100644 index 01ab76a..0000000 --- a/rand/src/distributions/unit_circle.rs +++ /dev/null @@ -1,101 +0,0 @@ -// Copyright 2018 Developers of the Rand project. -// -// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or -// https://www.apache.org/licenses/LICENSE-2.0> or the MIT license -// <LICENSE-MIT or https://opensource.org/licenses/MIT>, at your -// option. This file may not be copied, modified, or distributed -// except according to those terms. - -use Rng; -use distributions::{Distribution, Uniform}; - -/// Samples uniformly from the edge of the unit circle in two dimensions. -/// -/// Implemented via a method by von Neumann[^1]. -/// -/// -/// # Example -/// -/// ``` -/// use rand::distributions::{UnitCircle, Distribution}; -/// -/// let circle = UnitCircle::new(); -/// let v = circle.sample(&mut rand::thread_rng()); -/// println!("{:?} is from the unit circle.", v) -/// ``` -/// -/// [^1]: von Neumann, J. (1951) [*Various Techniques Used in Connection with -/// Random Digits.*](https://mcnp.lanl.gov/pdf_files/nbs_vonneumann.pdf) -/// NBS Appl. Math. Ser., No. 12. Washington, DC: U.S. Government Printing -/// Office, pp. 36-38. -#[derive(Clone, Copy, Debug)] -pub struct UnitCircle; - -impl UnitCircle { - /// Construct a new `UnitCircle` distribution. - #[inline] - pub fn new() -> UnitCircle { - UnitCircle - } -} - -impl Distribution<[f64; 2]> for UnitCircle { - #[inline] - fn sample<R: Rng + ?Sized>(&self, rng: &mut R) -> [f64; 2] { - let uniform = Uniform::new(-1., 1.); - let mut x1; - let mut x2; - let mut sum; - loop { - x1 = uniform.sample(rng); - x2 = uniform.sample(rng); - sum = x1*x1 + x2*x2; - if sum < 1. { - break; - } - } - let diff = x1*x1 - x2*x2; - [diff / sum, 2.*x1*x2 / sum] - } -} - -#[cfg(test)] -mod tests { - use distributions::Distribution; - use super::UnitCircle; - - /// Assert that two numbers are almost equal to each other. - /// - /// On panic, this macro will print the values of the expressions with their - /// debug representations. - macro_rules! assert_almost_eq { - ($a:expr, $b:expr, $prec:expr) => ( - let diff = ($a - $b).abs(); - if diff > $prec { - panic!(format!( - "assertion failed: `abs(left - right) = {:.1e} < {:e}`, \ - (left: `{}`, right: `{}`)", - diff, $prec, $a, $b)); - } - ); - } - - #[test] - fn norm() { - let mut rng = ::test::rng(1); - let dist = UnitCircle::new(); - for _ in 0..1000 { - let x = dist.sample(&mut rng); - assert_almost_eq!(x[0]*x[0] + x[1]*x[1], 1., 1e-15); - } - } - - #[test] - fn value_stability() { - let mut rng = ::test::rng(2); - let dist = UnitCircle::new(); - assert_eq!(dist.sample(&mut rng), [-0.8032118336637037, 0.5956935036263119]); - assert_eq!(dist.sample(&mut rng), [-0.4742919588505423, -0.880367615130018]); - assert_eq!(dist.sample(&mut rng), [0.9297328981467168, 0.368234623716601]); - } -} diff --git a/rand/src/distributions/unit_sphere.rs b/rand/src/distributions/unit_sphere.rs deleted file mode 100644 index 37de88b..0000000 --- a/rand/src/distributions/unit_sphere.rs +++ /dev/null @@ -1,99 +0,0 @@ -// Copyright 2018 Developers of the Rand project. -// -// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or -// https://www.apache.org/licenses/LICENSE-2.0> or the MIT license -// <LICENSE-MIT or https://opensource.org/licenses/MIT>, at your -// option. This file may not be copied, modified, or distributed -// except according to those terms. - -use Rng; -use distributions::{Distribution, Uniform}; - -/// Samples uniformly from the surface of the unit sphere in three dimensions. -/// -/// Implemented via a method by Marsaglia[^1]. -/// -/// -/// # Example -/// -/// ``` -/// use rand::distributions::{UnitSphereSurface, Distribution}; -/// -/// let sphere = UnitSphereSurface::new(); -/// let v = sphere.sample(&mut rand::thread_rng()); -/// println!("{:?} is from the unit sphere surface.", v) -/// ``` -/// -/// [^1]: Marsaglia, George (1972). [*Choosing a Point from the Surface of a -/// Sphere.*](https://doi.org/10.1214/aoms/1177692644) -/// Ann. Math. Statist. 43, no. 2, 645--646. -#[derive(Clone, Copy, Debug)] -pub struct UnitSphereSurface; - -impl UnitSphereSurface { - /// Construct a new `UnitSphereSurface` distribution. - #[inline] - pub fn new() -> UnitSphereSurface { - UnitSphereSurface - } -} - -impl Distribution<[f64; 3]> for UnitSphereSurface { - #[inline] - fn sample<R: Rng + ?Sized>(&self, rng: &mut R) -> [f64; 3] { - let uniform = Uniform::new(-1., 1.); - loop { - let (x1, x2) = (uniform.sample(rng), uniform.sample(rng)); - let sum = x1*x1 + x2*x2; - if sum >= 1. { - continue; - } - let factor = 2. * (1.0_f64 - sum).sqrt(); - return [x1 * factor, x2 * factor, 1. - 2.*sum]; - } - } -} - -#[cfg(test)] -mod tests { - use distributions::Distribution; - use super::UnitSphereSurface; - - /// Assert that two numbers are almost equal to each other. - /// - /// On panic, this macro will print the values of the expressions with their - /// debug representations. - macro_rules! assert_almost_eq { - ($a:expr, $b:expr, $prec:expr) => ( - let diff = ($a - $b).abs(); - if diff > $prec { - panic!(format!( - "assertion failed: `abs(left - right) = {:.1e} < {:e}`, \ - (left: `{}`, right: `{}`)", - diff, $prec, $a, $b)); - } - ); - } - - #[test] - fn norm() { - let mut rng = ::test::rng(1); - let dist = UnitSphereSurface::new(); - for _ in 0..1000 { - let x = dist.sample(&mut rng); - assert_almost_eq!(x[0]*x[0] + x[1]*x[1] + x[2]*x[2], 1., 1e-15); - } - } - - #[test] - fn value_stability() { - let mut rng = ::test::rng(2); - let dist = UnitSphereSurface::new(); - assert_eq!(dist.sample(&mut rng), - [-0.24950027180862533, -0.7552572587896719, 0.6060825747478084]); - assert_eq!(dist.sample(&mut rng), - [0.47604534507233487, -0.797200864987207, -0.3712837328763685]); - assert_eq!(dist.sample(&mut rng), - [0.9795722330927367, 0.18692349236651176, 0.07414747571708524]); - } -} diff --git a/rand/src/distributions/utils.rs b/rand/src/distributions/utils.rs deleted file mode 100644 index d4d3642..0000000 --- a/rand/src/distributions/utils.rs +++ /dev/null @@ -1,504 +0,0 @@ -// Copyright 2018 Developers of the Rand project. -// -// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or -// https://www.apache.org/licenses/LICENSE-2.0> or the MIT license -// <LICENSE-MIT or https://opensource.org/licenses/MIT>, at your -// option. This file may not be copied, modified, or distributed -// except according to those terms. - -//! Math helper functions - -#[cfg(feature="simd_support")] -use packed_simd::*; -#[cfg(feature="std")] -use distributions::ziggurat_tables; -#[cfg(feature="std")] -use Rng; - - -pub trait WideningMultiply<RHS = Self> { - type Output; - - fn wmul(self, x: RHS) -> Self::Output; -} - -macro_rules! wmul_impl { - ($ty:ty, $wide:ty, $shift:expr) => { - impl WideningMultiply for $ty { - type Output = ($ty, $ty); - - #[inline(always)] - fn wmul(self, x: $ty) -> Self::Output { - let tmp = (self as $wide) * (x as $wide); - ((tmp >> $shift) as $ty, tmp as $ty) - } - } - }; - - // simd bulk implementation - ($(($ty:ident, $wide:ident),)+, $shift:expr) => { - $( - impl WideningMultiply for $ty { - type Output = ($ty, $ty); - - #[inline(always)] - fn wmul(self, x: $ty) -> Self::Output { - // For supported vectors, this should compile to a couple - // supported multiply & swizzle instructions (no actual - // casting). - // TODO: optimize - let y: $wide = self.cast(); - let x: $wide = x.cast(); - let tmp = y * x; - let hi: $ty = (tmp >> $shift).cast(); - let lo: $ty = tmp.cast(); - (hi, lo) - } - } - )+ - }; -} -wmul_impl! { u8, u16, 8 } -wmul_impl! { u16, u32, 16 } -wmul_impl! { u32, u64, 32 } -#[cfg(all(rustc_1_26, not(target_os = "emscripten")))] -wmul_impl! { u64, u128, 64 } - -// This code is a translation of the __mulddi3 function in LLVM's -// compiler-rt. It is an optimised variant of the common method -// `(a + b) * (c + d) = ac + ad + bc + bd`. -// -// For some reason LLVM can optimise the C version very well, but -// keeps shuffling registers in this Rust translation. -macro_rules! wmul_impl_large { - ($ty:ty, $half:expr) => { - impl WideningMultiply for $ty { - type Output = ($ty, $ty); - - #[inline(always)] - fn wmul(self, b: $ty) -> Self::Output { - const LOWER_MASK: $ty = !0 >> $half; - let mut low = (self & LOWER_MASK).wrapping_mul(b & LOWER_MASK); - let mut t = low >> $half; - low &= LOWER_MASK; - t += (self >> $half).wrapping_mul(b & LOWER_MASK); - low += (t & LOWER_MASK) << $half; - let mut high = t >> $half; - t = low >> $half; - low &= LOWER_MASK; - t += (b >> $half).wrapping_mul(self & LOWER_MASK); - low += (t & LOWER_MASK) << $half; - high += t >> $half; - high += (self >> $half).wrapping_mul(b >> $half); - - (high, low) - } - } - }; - - // simd bulk implementation - (($($ty:ty,)+) $scalar:ty, $half:expr) => { - $( - impl WideningMultiply for $ty { - type Output = ($ty, $ty); - - #[inline(always)] - fn wmul(self, b: $ty) -> Self::Output { - // needs wrapping multiplication - const LOWER_MASK: $scalar = !0 >> $half; - let mut low = (self & LOWER_MASK) * (b & LOWER_MASK); - let mut t = low >> $half; - low &= LOWER_MASK; - t += (self >> $half) * (b & LOWER_MASK); - low += (t & LOWER_MASK) << $half; - let mut high = t >> $half; - t = low >> $half; - low &= LOWER_MASK; - t += (b >> $half) * (self & LOWER_MASK); - low += (t & LOWER_MASK) << $half; - high += t >> $half; - high += (self >> $half) * (b >> $half); - - (high, low) - } - } - )+ - }; -} -#[cfg(not(all(rustc_1_26, not(target_os = "emscripten"))))] -wmul_impl_large! { u64, 32 } -#[cfg(all(rustc_1_26, not(target_os = "emscripten")))] -wmul_impl_large! { u128, 64 } - -macro_rules! wmul_impl_usize { - ($ty:ty) => { - impl WideningMultiply for usize { - type Output = (usize, usize); - - #[inline(always)] - fn wmul(self, x: usize) -> Self::Output { - let (high, low) = (self as $ty).wmul(x as $ty); - (high as usize, low as usize) - } - } - } -} -#[cfg(target_pointer_width = "32")] -wmul_impl_usize! { u32 } -#[cfg(target_pointer_width = "64")] -wmul_impl_usize! { u64 } - -#[cfg(all(feature = "simd_support", feature = "nightly"))] -mod simd_wmul { - #[cfg(target_arch = "x86")] - use core::arch::x86::*; - #[cfg(target_arch = "x86_64")] - use core::arch::x86_64::*; - use super::*; - - wmul_impl! { - (u8x2, u16x2), - (u8x4, u16x4), - (u8x8, u16x8), - (u8x16, u16x16), - (u8x32, u16x32),, - 8 - } - - wmul_impl! { (u16x2, u32x2),, 16 } - #[cfg(not(target_feature = "sse2"))] - wmul_impl! { (u16x4, u32x4),, 16 } - #[cfg(not(target_feature = "sse4.2"))] - wmul_impl! { (u16x8, u32x8),, 16 } - #[cfg(not(target_feature = "avx2"))] - wmul_impl! { (u16x16, u32x16),, 16 } - - // 16-bit lane widths allow use of the x86 `mulhi` instructions, which - // means `wmul` can be implemented with only two instructions. - #[allow(unused_macros)] - macro_rules! wmul_impl_16 { - ($ty:ident, $intrinsic:ident, $mulhi:ident, $mullo:ident) => { - impl WideningMultiply for $ty { - type Output = ($ty, $ty); - - #[inline(always)] - fn wmul(self, x: $ty) -> Self::Output { - let b = $intrinsic::from_bits(x); - let a = $intrinsic::from_bits(self); - let hi = $ty::from_bits(unsafe { $mulhi(a, b) }); - let lo = $ty::from_bits(unsafe { $mullo(a, b) }); - (hi, lo) - } - } - }; - } - - #[cfg(target_feature = "sse2")] - wmul_impl_16! { u16x4, __m64, _mm_mulhi_pu16, _mm_mullo_pi16 } - #[cfg(target_feature = "sse4.2")] - wmul_impl_16! { u16x8, __m128i, _mm_mulhi_epu16, _mm_mullo_epi16 } - #[cfg(target_feature = "avx2")] - wmul_impl_16! { u16x16, __m256i, _mm256_mulhi_epu16, _mm256_mullo_epi16 } - // FIXME: there are no `__m512i` types in stdsimd yet, so `wmul::<u16x32>` - // cannot use the same implementation. - - wmul_impl! { - (u32x2, u64x2), - (u32x4, u64x4), - (u32x8, u64x8),, - 32 - } - - // TODO: optimize, this seems to seriously slow things down - wmul_impl_large! { (u8x64,) u8, 4 } - wmul_impl_large! { (u16x32,) u16, 8 } - wmul_impl_large! { (u32x16,) u32, 16 } - wmul_impl_large! { (u64x2, u64x4, u64x8,) u64, 32 } -} -#[cfg(all(feature = "simd_support", feature = "nightly"))] -pub use self::simd_wmul::*; - - -/// Helper trait when dealing with scalar and SIMD floating point types. -pub(crate) trait FloatSIMDUtils { - // `PartialOrd` for vectors compares lexicographically. We want to compare all - // the individual SIMD lanes instead, and get the combined result over all - // lanes. This is possible using something like `a.lt(b).all()`, but we - // implement it as a trait so we can write the same code for `f32` and `f64`. - // Only the comparison functions we need are implemented. - fn all_lt(self, other: Self) -> bool; - fn all_le(self, other: Self) -> bool; - fn all_finite(self) -> bool; - - type Mask; - fn finite_mask(self) -> Self::Mask; - fn gt_mask(self, other: Self) -> Self::Mask; - fn ge_mask(self, other: Self) -> Self::Mask; - - // Decrease all lanes where the mask is `true` to the next lower value - // representable by the floating-point type. At least one of the lanes - // must be set. - fn decrease_masked(self, mask: Self::Mask) -> Self; - - // Convert from int value. Conversion is done while retaining the numerical - // value, not by retaining the binary representation. - type UInt; - fn cast_from_int(i: Self::UInt) -> Self; -} - -/// Implement functions available in std builds but missing from core primitives -#[cfg(not(std))] -pub(crate) trait Float : Sized { - type Bits; - - fn is_nan(self) -> bool; - fn is_infinite(self) -> bool; - fn is_finite(self) -> bool; - fn to_bits(self) -> Self::Bits; - fn from_bits(v: Self::Bits) -> Self; -} - -/// Implement functions on f32/f64 to give them APIs similar to SIMD types -pub(crate) trait FloatAsSIMD : Sized { - #[inline(always)] - fn lanes() -> usize { 1 } - #[inline(always)] - fn splat(scalar: Self) -> Self { scalar } - #[inline(always)] - fn extract(self, index: usize) -> Self { debug_assert_eq!(index, 0); self } - #[inline(always)] - fn replace(self, index: usize, new_value: Self) -> Self { debug_assert_eq!(index, 0); new_value } -} - -pub(crate) trait BoolAsSIMD : Sized { - fn any(self) -> bool; - fn all(self) -> bool; - fn none(self) -> bool; -} - -impl BoolAsSIMD for bool { - #[inline(always)] - fn any(self) -> bool { self } - #[inline(always)] - fn all(self) -> bool { self } - #[inline(always)] - fn none(self) -> bool { !self } -} - -macro_rules! scalar_float_impl { - ($ty:ident, $uty:ident) => { - #[cfg(not(std))] - impl Float for $ty { - type Bits = $uty; - - #[inline] - fn is_nan(self) -> bool { - self != self - } - - #[inline] - fn is_infinite(self) -> bool { - self == ::core::$ty::INFINITY || self == ::core::$ty::NEG_INFINITY - } - - #[inline] - fn is_finite(self) -> bool { - !(self.is_nan() || self.is_infinite()) - } - - #[inline] - fn to_bits(self) -> Self::Bits { - unsafe { ::core::mem::transmute(self) } - } - - #[inline] - fn from_bits(v: Self::Bits) -> Self { - // It turns out the safety issues with sNaN were overblown! Hooray! - unsafe { ::core::mem::transmute(v) } - } - } - - impl FloatSIMDUtils for $ty { - type Mask = bool; - #[inline(always)] - fn all_lt(self, other: Self) -> bool { self < other } - #[inline(always)] - fn all_le(self, other: Self) -> bool { self <= other } - #[inline(always)] - fn all_finite(self) -> bool { self.is_finite() } - #[inline(always)] - fn finite_mask(self) -> Self::Mask { self.is_finite() } - #[inline(always)] - fn gt_mask(self, other: Self) -> Self::Mask { self > other } - #[inline(always)] - fn ge_mask(self, other: Self) -> Self::Mask { self >= other } - #[inline(always)] - fn decrease_masked(self, mask: Self::Mask) -> Self { - debug_assert!(mask, "At least one lane must be set"); - <$ty>::from_bits(self.to_bits() - 1) - } - type UInt = $uty; - fn cast_from_int(i: Self::UInt) -> Self { i as $ty } - } - - impl FloatAsSIMD for $ty {} - } -} - -scalar_float_impl!(f32, u32); -scalar_float_impl!(f64, u64); - - -#[cfg(feature="simd_support")] -macro_rules! simd_impl { - ($ty:ident, $f_scalar:ident, $mty:ident, $uty:ident) => { - impl FloatSIMDUtils for $ty { - type Mask = $mty; - #[inline(always)] - fn all_lt(self, other: Self) -> bool { self.lt(other).all() } - #[inline(always)] - fn all_le(self, other: Self) -> bool { self.le(other).all() } - #[inline(always)] - fn all_finite(self) -> bool { self.finite_mask().all() } - #[inline(always)] - fn finite_mask(self) -> Self::Mask { - // This can possibly be done faster by checking bit patterns - let neg_inf = $ty::splat(::core::$f_scalar::NEG_INFINITY); - let pos_inf = $ty::splat(::core::$f_scalar::INFINITY); - self.gt(neg_inf) & self.lt(pos_inf) - } - #[inline(always)] - fn gt_mask(self, other: Self) -> Self::Mask { self.gt(other) } - #[inline(always)] - fn ge_mask(self, other: Self) -> Self::Mask { self.ge(other) } - #[inline(always)] - fn decrease_masked(self, mask: Self::Mask) -> Self { - // Casting a mask into ints will produce all bits set for - // true, and 0 for false. Adding that to the binary - // representation of a float means subtracting one from - // the binary representation, resulting in the next lower - // value representable by $ty. This works even when the - // current value is infinity. - debug_assert!(mask.any(), "At least one lane must be set"); - <$ty>::from_bits(<$uty>::from_bits(self) + <$uty>::from_bits(mask)) - } - type UInt = $uty; - fn cast_from_int(i: Self::UInt) -> Self { i.cast() } - } - } -} - -#[cfg(feature="simd_support")] simd_impl! { f32x2, f32, m32x2, u32x2 } -#[cfg(feature="simd_support")] simd_impl! { f32x4, f32, m32x4, u32x4 } -#[cfg(feature="simd_support")] simd_impl! { f32x8, f32, m32x8, u32x8 } -#[cfg(feature="simd_support")] simd_impl! { f32x16, f32, m32x16, u32x16 } -#[cfg(feature="simd_support")] simd_impl! { f64x2, f64, m64x2, u64x2 } -#[cfg(feature="simd_support")] simd_impl! { f64x4, f64, m64x4, u64x4 } -#[cfg(feature="simd_support")] simd_impl! { f64x8, f64, m64x8, u64x8 } - -/// Calculates ln(gamma(x)) (natural logarithm of the gamma -/// function) using the Lanczos approximation. -/// -/// The approximation expresses the gamma function as: -/// `gamma(z+1) = sqrt(2*pi)*(z+g+0.5)^(z+0.5)*exp(-z-g-0.5)*Ag(z)` -/// `g` is an arbitrary constant; we use the approximation with `g=5`. -/// -/// Noting that `gamma(z+1) = z*gamma(z)` and applying `ln` to both sides: -/// `ln(gamma(z)) = (z+0.5)*ln(z+g+0.5)-(z+g+0.5) + ln(sqrt(2*pi)*Ag(z)/z)` -/// -/// `Ag(z)` is an infinite series with coefficients that can be calculated -/// ahead of time - we use just the first 6 terms, which is good enough -/// for most purposes. -#[cfg(feature="std")] -pub fn log_gamma(x: f64) -> f64 { - // precalculated 6 coefficients for the first 6 terms of the series - let coefficients: [f64; 6] = [ - 76.18009172947146, - -86.50532032941677, - 24.01409824083091, - -1.231739572450155, - 0.1208650973866179e-2, - -0.5395239384953e-5, - ]; - - // (x+0.5)*ln(x+g+0.5)-(x+g+0.5) - let tmp = x + 5.5; - let log = (x + 0.5) * tmp.ln() - tmp; - - // the first few terms of the series for Ag(x) - let mut a = 1.000000000190015; - let mut denom = x; - for coeff in &coefficients { - denom += 1.0; - a += coeff / denom; - } - - // get everything together - // a is Ag(x) - // 2.5066... is sqrt(2pi) - log + (2.5066282746310005 * a / x).ln() -} - -/// Sample a random number using the Ziggurat method (specifically the -/// ZIGNOR variant from Doornik 2005). Most of the arguments are -/// directly from the paper: -/// -/// * `rng`: source of randomness -/// * `symmetric`: whether this is a symmetric distribution, or one-sided with P(x < 0) = 0. -/// * `X`: the $x_i$ abscissae. -/// * `F`: precomputed values of the PDF at the $x_i$, (i.e. $f(x_i)$) -/// * `F_DIFF`: precomputed values of $f(x_i) - f(x_{i+1})$ -/// * `pdf`: the probability density function -/// * `zero_case`: manual sampling from the tail when we chose the -/// bottom box (i.e. i == 0) - -// the perf improvement (25-50%) is definitely worth the extra code -// size from force-inlining. -#[cfg(feature="std")] -#[inline(always)] -pub fn ziggurat<R: Rng + ?Sized, P, Z>( - rng: &mut R, - symmetric: bool, - x_tab: ziggurat_tables::ZigTable, - f_tab: ziggurat_tables::ZigTable, - mut pdf: P, - mut zero_case: Z) - -> f64 where P: FnMut(f64) -> f64, Z: FnMut(&mut R, f64) -> f64 { - use distributions::float::IntoFloat; - loop { - // As an optimisation we re-implement the conversion to a f64. - // From the remaining 12 most significant bits we use 8 to construct `i`. - // This saves us generating a whole extra random number, while the added - // precision of using 64 bits for f64 does not buy us much. - let bits = rng.next_u64(); - let i = bits as usize & 0xff; - - let u = if symmetric { - // Convert to a value in the range [2,4) and substract to get [-1,1) - // We can't convert to an open range directly, that would require - // substracting `3.0 - EPSILON`, which is not representable. - // It is possible with an extra step, but an open range does not - // seem neccesary for the ziggurat algorithm anyway. - (bits >> 12).into_float_with_exponent(1) - 3.0 - } else { - // Convert to a value in the range [1,2) and substract to get (0,1) - (bits >> 12).into_float_with_exponent(0) - - (1.0 - ::core::f64::EPSILON / 2.0) - }; - let x = u * x_tab[i]; - - let test_x = if symmetric { x.abs() } else {x}; - - // algebraically equivalent to |u| < x_tab[i+1]/x_tab[i] (or u < x_tab[i+1]/x_tab[i]) - if test_x < x_tab[i + 1] { - return x; - } - if i == 0 { - return zero_case(rng, u); - } - // algebraically equivalent to f1 + DRanU()*(f0 - f1) < 1 - if f_tab[i + 1] + (f_tab[i] - f_tab[i + 1]) * rng.gen::<f64>() < pdf(x) { - return x; - } - } -} diff --git a/rand/src/distributions/weibull.rs b/rand/src/distributions/weibull.rs deleted file mode 100644 index 5fbe10a..0000000 --- a/rand/src/distributions/weibull.rs +++ /dev/null @@ -1,71 +0,0 @@ -// Copyright 2018 Developers of the Rand project. -// -// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or -// https://www.apache.org/licenses/LICENSE-2.0> or the MIT license -// <LICENSE-MIT or https://opensource.org/licenses/MIT>, at your -// option. This file may not be copied, modified, or distributed -// except according to those terms. - -//! The Weibull distribution. - -use Rng; -use distributions::{Distribution, OpenClosed01}; - -/// Samples floating-point numbers according to the Weibull distribution -/// -/// # Example -/// ``` -/// use rand::prelude::*; -/// use rand::distributions::Weibull; -/// -/// let val: f64 = SmallRng::from_entropy().sample(Weibull::new(1., 10.)); -/// println!("{}", val); -/// ``` -#[derive(Clone, Copy, Debug)] -pub struct Weibull { - inv_shape: f64, - scale: f64, -} - -impl Weibull { - /// Construct a new `Weibull` distribution with given `scale` and `shape`. - /// - /// # Panics - /// - /// `scale` and `shape` have to be non-zero and positive. - pub fn new(scale: f64, shape: f64) -> Weibull { - assert!((scale > 0.) & (shape > 0.)); - Weibull { inv_shape: 1./shape, scale } - } -} - -impl Distribution<f64> for Weibull { - fn sample<R: Rng + ?Sized>(&self, rng: &mut R) -> f64 { - let x: f64 = rng.sample(OpenClosed01); - self.scale * (-x.ln()).powf(self.inv_shape) - } -} - -#[cfg(test)] -mod tests { - use distributions::Distribution; - use super::Weibull; - - #[test] - #[should_panic] - fn invalid() { - Weibull::new(0., 0.); - } - - #[test] - fn sample() { - let scale = 1.0; - let shape = 2.0; - let d = Weibull::new(scale, shape); - let mut rng = ::test::rng(1); - for _ in 0..1000 { - let r = d.sample(&mut rng); - assert!(r >= 0.); - } - } -} diff --git a/rand/src/distributions/weighted.rs b/rand/src/distributions/weighted.rs deleted file mode 100644 index 01c8fe6..0000000 --- a/rand/src/distributions/weighted.rs +++ /dev/null @@ -1,232 +0,0 @@ -// Copyright 2018 Developers of the Rand project. -// -// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or -// https://www.apache.org/licenses/LICENSE-2.0> or the MIT license -// <LICENSE-MIT or https://opensource.org/licenses/MIT>, at your -// option. This file may not be copied, modified, or distributed -// except according to those terms. - -use Rng; -use distributions::Distribution; -use distributions::uniform::{UniformSampler, SampleUniform, SampleBorrow}; -use ::core::cmp::PartialOrd; -use core::fmt; - -// Note that this whole module is only imported if feature="alloc" is enabled. -#[cfg(not(feature="std"))] use alloc::vec::Vec; - -/// A distribution using weighted sampling to pick a discretely selected -/// item. -/// -/// Sampling a `WeightedIndex` distribution returns the index of a randomly -/// selected element from the iterator used when the `WeightedIndex` was -/// created. The chance of a given element being picked is proportional to the -/// value of the element. The weights can use any type `X` for which an -/// implementation of [`Uniform<X>`] exists. -/// -/// # Performance -/// -/// A `WeightedIndex<X>` contains a `Vec<X>` and a [`Uniform<X>`] and so its -/// size is the sum of the size of those objects, possibly plus some alignment. -/// -/// Creating a `WeightedIndex<X>` will allocate enough space to hold `N - 1` -/// weights of type `X`, where `N` is the number of weights. However, since -/// `Vec` doesn't guarantee a particular growth strategy, additional memory -/// might be allocated but not used. Since the `WeightedIndex` object also -/// contains, this might cause additional allocations, though for primitive -/// types, ['Uniform<X>`] doesn't allocate any memory. -/// -/// Time complexity of sampling from `WeightedIndex` is `O(log N)` where -/// `N` is the number of weights. -/// -/// Sampling from `WeightedIndex` will result in a single call to -/// [`Uniform<X>::sample`], which typically will request a single value from -/// the underlying [`RngCore`], though the exact number depends on the -/// implementaiton of [`Uniform<X>::sample`]. -/// -/// # Example -/// -/// ``` -/// use rand::prelude::*; -/// use rand::distributions::WeightedIndex; -/// -/// let choices = ['a', 'b', 'c']; -/// let weights = [2, 1, 1]; -/// let dist = WeightedIndex::new(&weights).unwrap(); -/// let mut rng = thread_rng(); -/// for _ in 0..100 { -/// // 50% chance to print 'a', 25% chance to print 'b', 25% chance to print 'c' -/// println!("{}", choices[dist.sample(&mut rng)]); -/// } -/// -/// let items = [('a', 0), ('b', 3), ('c', 7)]; -/// let dist2 = WeightedIndex::new(items.iter().map(|item| item.1)).unwrap(); -/// for _ in 0..100 { -/// // 0% chance to print 'a', 30% chance to print 'b', 70% chance to print 'c' -/// println!("{}", items[dist2.sample(&mut rng)].0); -/// } -/// ``` -/// -/// [`Uniform<X>`]: struct.Uniform.html -/// [`Uniform<X>::sample`]: struct.Uniform.html#method.sample -/// [`RngCore`]: ../trait.RngCore.html -#[derive(Debug, Clone)] -pub struct WeightedIndex<X: SampleUniform + PartialOrd> { - cumulative_weights: Vec<X>, - weight_distribution: X::Sampler, -} - -impl<X: SampleUniform + PartialOrd> WeightedIndex<X> { - /// Creates a new a `WeightedIndex` [`Distribution`] using the values - /// in `weights`. The weights can use any type `X` for which an - /// implementation of [`Uniform<X>`] exists. - /// - /// Returns an error if the iterator is empty, if any weight is `< 0`, or - /// if its total value is 0. - /// - /// [`Distribution`]: trait.Distribution.html - /// [`Uniform<X>`]: struct.Uniform.html - pub fn new<I>(weights: I) -> Result<WeightedIndex<X>, WeightedError> - where I: IntoIterator, - I::Item: SampleBorrow<X>, - X: for<'a> ::core::ops::AddAssign<&'a X> + - Clone + - Default { - let mut iter = weights.into_iter(); - let mut total_weight: X = iter.next() - .ok_or(WeightedError::NoItem)? - .borrow() - .clone(); - - let zero = <X as Default>::default(); - if total_weight < zero { - return Err(WeightedError::NegativeWeight); - } - - let mut weights = Vec::<X>::with_capacity(iter.size_hint().0); - for w in iter { - if *w.borrow() < zero { - return Err(WeightedError::NegativeWeight); - } - weights.push(total_weight.clone()); - total_weight += w.borrow(); - } - - if total_weight == zero { - return Err(WeightedError::AllWeightsZero); - } - let distr = X::Sampler::new(zero, total_weight); - - Ok(WeightedIndex { cumulative_weights: weights, weight_distribution: distr }) - } -} - -impl<X> Distribution<usize> for WeightedIndex<X> where - X: SampleUniform + PartialOrd { - fn sample<R: Rng + ?Sized>(&self, rng: &mut R) -> usize { - use ::core::cmp::Ordering; - let chosen_weight = self.weight_distribution.sample(rng); - // Find the first item which has a weight *higher* than the chosen weight. - self.cumulative_weights.binary_search_by( - |w| if *w <= chosen_weight { Ordering::Less } else { Ordering::Greater }).unwrap_err() - } -} - -#[cfg(test)] -mod test { - use super::*; - - #[test] - fn test_weightedindex() { - let mut r = ::test::rng(700); - const N_REPS: u32 = 5000; - let weights = [1u32, 2, 3, 0, 5, 6, 7, 1, 2, 3, 4, 5, 6, 7]; - let total_weight = weights.iter().sum::<u32>() as f32; - - let verify = |result: [i32; 14]| { - for (i, count) in result.iter().enumerate() { - let exp = (weights[i] * N_REPS) as f32 / total_weight; - let mut err = (*count as f32 - exp).abs(); - if err != 0.0 { - err /= exp; - } - assert!(err <= 0.25); - } - }; - - // WeightedIndex from vec - let mut chosen = [0i32; 14]; - let distr = WeightedIndex::new(weights.to_vec()).unwrap(); - for _ in 0..N_REPS { - chosen[distr.sample(&mut r)] += 1; - } - verify(chosen); - - // WeightedIndex from slice - chosen = [0i32; 14]; - let distr = WeightedIndex::new(&weights[..]).unwrap(); - for _ in 0..N_REPS { - chosen[distr.sample(&mut r)] += 1; - } - verify(chosen); - - // WeightedIndex from iterator - chosen = [0i32; 14]; - let distr = WeightedIndex::new(weights.iter()).unwrap(); - for _ in 0..N_REPS { - chosen[distr.sample(&mut r)] += 1; - } - verify(chosen); - - for _ in 0..5 { - assert_eq!(WeightedIndex::new(&[0, 1]).unwrap().sample(&mut r), 1); - assert_eq!(WeightedIndex::new(&[1, 0]).unwrap().sample(&mut r), 0); - assert_eq!(WeightedIndex::new(&[0, 0, 0, 0, 10, 0]).unwrap().sample(&mut r), 4); - } - - assert_eq!(WeightedIndex::new(&[10][0..0]).unwrap_err(), WeightedError::NoItem); - assert_eq!(WeightedIndex::new(&[0]).unwrap_err(), WeightedError::AllWeightsZero); - assert_eq!(WeightedIndex::new(&[10, 20, -1, 30]).unwrap_err(), WeightedError::NegativeWeight); - assert_eq!(WeightedIndex::new(&[-10, 20, 1, 30]).unwrap_err(), WeightedError::NegativeWeight); - assert_eq!(WeightedIndex::new(&[-10]).unwrap_err(), WeightedError::NegativeWeight); - } -} - -/// Error type returned from `WeightedIndex::new`. -#[derive(Debug, Clone, Copy, PartialEq, Eq)] -pub enum WeightedError { - /// The provided iterator contained no items. - NoItem, - - /// A weight lower than zero was used. - NegativeWeight, - - /// All items in the provided iterator had a weight of zero. - AllWeightsZero, -} - -impl WeightedError { - fn msg(&self) -> &str { - match *self { - WeightedError::NoItem => "No items found", - WeightedError::NegativeWeight => "Item has negative weight", - WeightedError::AllWeightsZero => "All items had weight zero", - } - } -} - -#[cfg(feature="std")] -impl ::std::error::Error for WeightedError { - fn description(&self) -> &str { - self.msg() - } - fn cause(&self) -> Option<&::std::error::Error> { - None - } -} - -impl fmt::Display for WeightedError { - fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { - write!(f, "{}", self.msg()) - } -} diff --git a/rand/src/distributions/ziggurat_tables.rs b/rand/src/distributions/ziggurat_tables.rs deleted file mode 100644 index ca1ce30..0000000 --- a/rand/src/distributions/ziggurat_tables.rs +++ /dev/null @@ -1,279 +0,0 @@ -// Copyright 2018 Developers of the Rand project. -// Copyright 2013 The Rust Project Developers. -// -// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or -// https://www.apache.org/licenses/LICENSE-2.0> or the MIT license -// <LICENSE-MIT or https://opensource.org/licenses/MIT>, at your -// option. This file may not be copied, modified, or distributed -// except according to those terms. - -// Tables for distributions which are sampled using the ziggurat -// algorithm. Autogenerated by `ziggurat_tables.py`. - -pub type ZigTable = &'static [f64; 257]; -pub const ZIG_NORM_R: f64 = 3.654152885361008796; -pub static ZIG_NORM_X: [f64; 257] = - [3.910757959537090045, 3.654152885361008796, 3.449278298560964462, 3.320244733839166074, - 3.224575052047029100, 3.147889289517149969, 3.083526132001233044, 3.027837791768635434, - 2.978603279880844834, 2.934366867207854224, 2.894121053612348060, 2.857138730872132548, - 2.822877396825325125, 2.790921174000785765, 2.760944005278822555, 2.732685359042827056, - 2.705933656121858100, 2.680514643284522158, 2.656283037575502437, 2.633116393630324570, - 2.610910518487548515, 2.589575986706995181, 2.569035452680536569, 2.549221550323460761, - 2.530075232158516929, 2.511544441625342294, 2.493583041269680667, 2.476149939669143318, - 2.459208374333311298, 2.442725318198956774, 2.426670984935725972, 2.411018413899685520, - 2.395743119780480601, 2.380822795170626005, 2.366237056715818632, 2.351967227377659952, - 2.337996148795031370, 2.324308018869623016, 2.310888250599850036, 2.297723348901329565, - 2.284800802722946056, 2.272108990226823888, 2.259637095172217780, 2.247375032945807760, - 2.235313384928327984, 2.223443340090905718, 2.211756642882544366, 2.200245546609647995, - 2.188902771624720689, 2.177721467738641614, 2.166695180352645966, 2.155817819875063268, - 2.145083634046203613, 2.134487182844320152, 2.124023315687815661, 2.113687150684933957, - 2.103474055713146829, 2.093379631137050279, 2.083399693996551783, 2.073530263516978778, - 2.063767547809956415, 2.054107931648864849, 2.044547965215732788, 2.035084353727808715, - 2.025713947862032960, 2.016433734904371722, 2.007240830558684852, 1.998132471356564244, - 1.989106007615571325, 1.980158896898598364, 1.971288697931769640, 1.962493064942461896, - 1.953769742382734043, 1.945116560006753925, 1.936531428273758904, 1.928012334050718257, - 1.919557336591228847, 1.911164563769282232, 1.902832208548446369, 1.894558525668710081, - 1.886341828534776388, 1.878180486290977669, 1.870072921069236838, 1.862017605397632281, - 1.854013059758148119, 1.846057850283119750, 1.838150586580728607, 1.830289919680666566, - 1.822474540091783224, 1.814703175964167636, 1.806974591348693426, 1.799287584547580199, - 1.791640986550010028, 1.784033659547276329, 1.776464495522344977, 1.768932414909077933, - 1.761436365316706665, 1.753975320315455111, 1.746548278279492994, 1.739154261283669012, - 1.731792314050707216, 1.724461502945775715, 1.717160915015540690, 1.709889657069006086, - 1.702646854797613907, 1.695431651932238548, 1.688243209434858727, 1.681080704722823338, - 1.673943330923760353, 1.666830296159286684, 1.659740822855789499, 1.652674147080648526, - 1.645629517902360339, 1.638606196773111146, 1.631603456932422036, 1.624620582830568427, - 1.617656869570534228, 1.610711622367333673, 1.603784156023583041, 1.596873794420261339, - 1.589979870021648534, 1.583101723393471438, 1.576238702733332886, 1.569390163412534456, - 1.562555467528439657, 1.555733983466554893, 1.548925085471535512, 1.542128153226347553, - 1.535342571438843118, 1.528567729435024614, 1.521803020758293101, 1.515047842773992404, - 1.508301596278571965, 1.501563685112706548, 1.494833515777718391, 1.488110497054654369, - 1.481394039625375747, 1.474683555695025516, 1.467978458615230908, 1.461278162507407830, - 1.454582081885523293, 1.447889631277669675, 1.441200224845798017, 1.434513276002946425, - 1.427828197027290358, 1.421144398672323117, 1.414461289772464658, 1.407778276843371534, - 1.401094763676202559, 1.394410150925071257, 1.387723835686884621, 1.381035211072741964, - 1.374343665770030531, 1.367648583594317957, 1.360949343030101844, 1.354245316759430606, - 1.347535871177359290, 1.340820365893152122, 1.334098153216083604, 1.327368577624624679, - 1.320630975217730096, 1.313884673146868964, 1.307128989027353860, 1.300363230327433728, - 1.293586693733517645, 1.286798664489786415, 1.279998415710333237, 1.273185207661843732, - 1.266358287014688333, 1.259516886060144225, 1.252660221891297887, 1.245787495544997903, - 1.238897891102027415, 1.231990574742445110, 1.225064693752808020, 1.218119375481726552, - 1.211153726239911244, 1.204166830140560140, 1.197157747875585931, 1.190125515422801650, - 1.183069142678760732, 1.175987612011489825, 1.168879876726833800, 1.161744859441574240, - 1.154581450355851802, 1.147388505416733873, 1.140164844363995789, 1.132909248648336975, - 1.125620459211294389, 1.118297174115062909, 1.110938046009249502, 1.103541679420268151, - 1.096106627847603487, 1.088631390649514197, 1.081114409698889389, 1.073554065787871714, - 1.065948674757506653, 1.058296483326006454, 1.050595664586207123, 1.042844313139370538, - 1.035040439828605274, 1.027181966030751292, 1.019266717460529215, 1.011292417434978441, - 1.003256679539591412, 0.995156999629943084, 0.986990747093846266, 0.978755155288937750, - 0.970447311058864615, 0.962064143217605250, 0.953602409875572654, 0.945058684462571130, - 0.936429340280896860, 0.927710533396234771, 0.918898183643734989, 0.909987953490768997, - 0.900975224455174528, 0.891855070726792376, 0.882622229578910122, 0.873271068082494550, - 0.863795545546826915, 0.854189171001560554, 0.844444954902423661, 0.834555354079518752, - 0.824512208745288633, 0.814306670128064347, 0.803929116982664893, 0.793369058833152785, - 0.782615023299588763, 0.771654424216739354, 0.760473406422083165, 0.749056662009581653, - 0.737387211425838629, 0.725446140901303549, 0.713212285182022732, 0.700661841097584448, - 0.687767892786257717, 0.674499822827436479, 0.660822574234205984, 0.646695714884388928, - 0.632072236375024632, 0.616896989996235545, 0.601104617743940417, 0.584616766093722262, - 0.567338257040473026, 0.549151702313026790, 0.529909720646495108, 0.509423329585933393, - 0.487443966121754335, 0.463634336771763245, 0.437518402186662658, 0.408389134588000746, - 0.375121332850465727, 0.335737519180459465, 0.286174591747260509, 0.215241895913273806, - 0.000000000000000000]; -pub static ZIG_NORM_F: [f64; 257] = - [0.000477467764586655, 0.001260285930498598, 0.002609072746106363, 0.004037972593371872, - 0.005522403299264754, 0.007050875471392110, 0.008616582769422917, 0.010214971439731100, - 0.011842757857943104, 0.013497450601780807, 0.015177088307982072, 0.016880083152595839, - 0.018605121275783350, 0.020351096230109354, 0.022117062707379922, 0.023902203305873237, - 0.025705804008632656, 0.027527235669693315, 0.029365939758230111, 0.031221417192023690, - 0.033093219458688698, 0.034980941461833073, 0.036884215688691151, 0.038802707404656918, - 0.040736110656078753, 0.042684144916619378, 0.044646552251446536, 0.046623094902089664, - 0.048613553216035145, 0.050617723861121788, 0.052635418276973649, 0.054666461325077916, - 0.056710690106399467, 0.058767952921137984, 0.060838108349751806, 0.062921024437977854, - 0.065016577971470438, 0.067124653828023989, 0.069245144397250269, 0.071377949059141965, - 0.073522973714240991, 0.075680130359194964, 0.077849336702372207, 0.080030515814947509, - 0.082223595813495684, 0.084428509570654661, 0.086645194450867782, 0.088873592068594229, - 0.091113648066700734, 0.093365311913026619, 0.095628536713353335, 0.097903279039215627, - 0.100189498769172020, 0.102487158942306270, 0.104796225622867056, 0.107116667775072880, - 0.109448457147210021, 0.111791568164245583, 0.114145977828255210, 0.116511665626037014, - 0.118888613443345698, 0.121276805485235437, 0.123676228202051403, 0.126086870220650349, - 0.128508722280473636, 0.130941777174128166, 0.133386029692162844, 0.135841476571757352, - 0.138308116449064322, 0.140785949814968309, 0.143274978974047118, 0.145775208006537926, - 0.148286642733128721, 0.150809290682410169, 0.153343161060837674, 0.155888264725064563, - 0.158444614156520225, 0.161012223438117663, 0.163591108232982951, 0.166181285765110071, - 0.168782774801850333, 0.171395595638155623, 0.174019770082499359, 0.176655321444406654, - 0.179302274523530397, 0.181960655600216487, 0.184630492427504539, 0.187311814224516926, - 0.190004651671193070, 0.192709036904328807, 0.195425003514885592, 0.198152586546538112, - 0.200891822495431333, 0.203642749311121501, 0.206405406398679298, 0.209179834621935651, - 0.211966076307852941, 0.214764175252008499, 0.217574176725178370, 0.220396127481011589, - 0.223230075764789593, 0.226076071323264877, 0.228934165415577484, 0.231804410825248525, - 0.234686861873252689, 0.237581574432173676, 0.240488605941449107, 0.243408015423711988, - 0.246339863502238771, 0.249284212419516704, 0.252241126056943765, 0.255210669955677150, - 0.258192911338648023, 0.261187919133763713, 0.264195763998317568, 0.267216518344631837, - 0.270250256366959984, 0.273297054069675804, 0.276356989296781264, 0.279430141762765316, - 0.282516593084849388, 0.285616426816658109, 0.288729728483353931, 0.291856585618280984, - 0.294997087801162572, 0.298151326697901342, 0.301319396102034120, 0.304501391977896274, - 0.307697412505553769, 0.310907558127563710, 0.314131931597630143, 0.317370638031222396, - 0.320623784958230129, 0.323891482377732021, 0.327173842814958593, 0.330470981380537099, - 0.333783015832108509, 0.337110066638412809, 0.340452257045945450, 0.343809713148291340, - 0.347182563958251478, 0.350570941482881204, 0.353974980801569250, 0.357394820147290515, - 0.360830600991175754, 0.364282468130549597, 0.367750569780596226, 0.371235057669821344, - 0.374736087139491414, 0.378253817247238111, 0.381788410875031348, 0.385340034841733958, - 0.388908860020464597, 0.392495061461010764, 0.396098818517547080, 0.399720314981931668, - 0.403359739222868885, 0.407017284331247953, 0.410693148271983222, 0.414387534042706784, - 0.418100649839684591, 0.421832709231353298, 0.425583931339900579, 0.429354541031341519, - 0.433144769114574058, 0.436954852549929273, 0.440785034667769915, 0.444635565397727750, - 0.448506701509214067, 0.452398706863882505, 0.456311852680773566, 0.460246417814923481, - 0.464202689050278838, 0.468180961407822172, 0.472181538469883255, 0.476204732721683788, - 0.480250865911249714, 0.484320269428911598, 0.488413284707712059, 0.492530263646148658, - 0.496671569054796314, 0.500837575128482149, 0.505028667945828791, 0.509245245998136142, - 0.513487720749743026, 0.517756517232200619, 0.522052074674794864, 0.526374847174186700, - 0.530725304406193921, 0.535103932383019565, 0.539511234259544614, 0.543947731192649941, - 0.548413963257921133, 0.552910490428519918, 0.557437893621486324, 0.561996775817277916, - 0.566587763258951771, 0.571211506738074970, 0.575868682975210544, 0.580559996103683473, - 0.585286179266300333, 0.590047996335791969, 0.594846243770991268, 0.599681752622167719, - 0.604555390700549533, 0.609468064928895381, 0.614420723892076803, 0.619414360609039205, - 0.624450015550274240, 0.629528779928128279, 0.634651799290960050, 0.639820277456438991, - 0.645035480824251883, 0.650298743114294586, 0.655611470583224665, 0.660975147780241357, - 0.666391343912380640, 0.671861719900766374, 0.677388036222513090, 0.682972161648791376, - 0.688616083008527058, 0.694321916130032579, 0.700091918140490099, 0.705928501336797409, - 0.711834248882358467, 0.717811932634901395, 0.723864533472881599, 0.729995264565802437, - 0.736207598131266683, 0.742505296344636245, 0.748892447223726720, 0.755373506511754500, - 0.761953346841546475, 0.768637315803334831, 0.775431304986138326, 0.782341832659861902, - 0.789376143571198563, 0.796542330428254619, 0.803849483176389490, 0.811307874318219935, - 0.818929191609414797, 0.826726833952094231, 0.834716292992930375, 0.842915653118441077, - 0.851346258465123684, 0.860033621203008636, 0.869008688043793165, 0.878309655816146839, - 0.887984660763399880, 0.898095921906304051, 0.908726440060562912, 0.919991505048360247, - 0.932060075968990209, 0.945198953453078028, 0.959879091812415930, 0.977101701282731328, - 1.000000000000000000]; -pub const ZIG_EXP_R: f64 = 7.697117470131050077; -pub static ZIG_EXP_X: [f64; 257] = - [8.697117470131052741, 7.697117470131050077, 6.941033629377212577, 6.478378493832569696, - 6.144164665772472667, 5.882144315795399869, 5.666410167454033697, 5.482890627526062488, - 5.323090505754398016, 5.181487281301500047, 5.054288489981304089, 4.938777085901250530, - 4.832939741025112035, 4.735242996601741083, 4.644491885420085175, 4.559737061707351380, - 4.480211746528421912, 4.405287693473573185, 4.334443680317273007, 4.267242480277365857, - 4.203313713735184365, 4.142340865664051464, 4.084051310408297830, 4.028208544647936762, - 3.974606066673788796, 3.923062500135489739, 3.873417670399509127, 3.825529418522336744, - 3.779270992411667862, 3.734528894039797375, 3.691201090237418825, 3.649195515760853770, - 3.608428813128909507, 3.568825265648337020, 3.530315889129343354, 3.492837654774059608, - 3.456332821132760191, 3.420748357251119920, 3.386035442460300970, 3.352149030900109405, - 3.319047470970748037, 3.286692171599068679, 3.255047308570449882, 3.224079565286264160, - 3.193757903212240290, 3.164053358025972873, 3.134938858084440394, 3.106389062339824481, - 3.078380215254090224, 3.050890016615455114, 3.023897504455676621, 2.997382949516130601, - 2.971327759921089662, 2.945714394895045718, 2.920526286512740821, 2.895747768600141825, - 2.871364012015536371, 2.847360965635188812, 2.823725302450035279, 2.800444370250737780, - 2.777506146439756574, 2.754899196562344610, 2.732612636194700073, 2.710636095867928752, - 2.688959688741803689, 2.667573980773266573, 2.646469963151809157, 2.625639026797788489, - 2.605072938740835564, 2.584763820214140750, 2.564704126316905253, 2.544886627111869970, - 2.525304390037828028, 2.505950763528594027, 2.486819361740209455, 2.467904050297364815, - 2.449198932978249754, 2.430698339264419694, 2.412396812688870629, 2.394289099921457886, - 2.376370140536140596, 2.358635057409337321, 2.341079147703034380, 2.323697874390196372, - 2.306486858283579799, 2.289441870532269441, 2.272558825553154804, 2.255833774367219213, - 2.239262898312909034, 2.222842503111036816, 2.206569013257663858, 2.190438966723220027, - 2.174449009937774679, 2.158595893043885994, 2.142876465399842001, 2.127287671317368289, - 2.111826546019042183, 2.096490211801715020, 2.081275874393225145, 2.066180819490575526, - 2.051202409468584786, 2.036338080248769611, 2.021585338318926173, 2.006941757894518563, - 1.992404978213576650, 1.977972700957360441, 1.963642687789548313, 1.949412758007184943, - 1.935280786297051359, 1.921244700591528076, 1.907302480018387536, 1.893452152939308242, - 1.879691795072211180, 1.866019527692827973, 1.852433515911175554, 1.838931967018879954, - 1.825513128903519799, 1.812175288526390649, 1.798916770460290859, 1.785735935484126014, - 1.772631179231305643, 1.759600930889074766, 1.746643651946074405, 1.733757834985571566, - 1.720942002521935299, 1.708194705878057773, 1.695514524101537912, 1.682900062917553896, - 1.670349953716452118, 1.657862852574172763, 1.645437439303723659, 1.633072416535991334, - 1.620766508828257901, 1.608518461798858379, 1.596327041286483395, 1.584191032532688892, - 1.572109239386229707, 1.560080483527888084, 1.548103603714513499, 1.536177455041032092, - 1.524300908219226258, 1.512472848872117082, 1.500692176842816750, 1.488957805516746058, - 1.477268661156133867, 1.465623682245745352, 1.454021818848793446, 1.442462031972012504, - 1.430943292938879674, 1.419464582769983219, 1.408024891569535697, 1.396623217917042137, - 1.385258568263121992, 1.373929956328490576, 1.362636402505086775, 1.351376933258335189, - 1.340150580529504643, 1.328956381137116560, 1.317793376176324749, 1.306660610415174117, - 1.295557131686601027, 1.284481990275012642, 1.273434238296241139, 1.262412929069615330, - 1.251417116480852521, 1.240445854334406572, 1.229498195693849105, 1.218573192208790124, - 1.207669893426761121, 1.196787346088403092, 1.185924593404202199, 1.175080674310911677, - 1.164254622705678921, 1.153445466655774743, 1.142652227581672841, 1.131873919411078511, - 1.121109547701330200, 1.110358108727411031, 1.099618588532597308, 1.088889961938546813, - 1.078171191511372307, 1.067461226479967662, 1.056759001602551429, 1.046063435977044209, - 1.035373431790528542, 1.024687873002617211, 1.014005623957096480, 1.003325527915696735, - 0.992646405507275897, 0.981967053085062602, 0.971286240983903260, 0.960602711668666509, - 0.949915177764075969, 0.939222319955262286, 0.928522784747210395, 0.917815182070044311, - 0.907098082715690257, 0.896370015589889935, 0.885629464761751528, 0.874874866291025066, - 0.864104604811004484, 0.853317009842373353, 0.842510351810368485, 0.831682837734273206, - 0.820832606554411814, 0.809957724057418282, 0.799056177355487174, 0.788125868869492430, - 0.777164609759129710, 0.766170112735434672, 0.755139984181982249, 0.744071715500508102, - 0.732962673584365398, 0.721810090308756203, 0.710611050909655040, 0.699362481103231959, - 0.688061132773747808, 0.676703568029522584, 0.665286141392677943, 0.653804979847664947, - 0.642255960424536365, 0.630634684933490286, 0.618936451394876075, 0.607156221620300030, - 0.595288584291502887, 0.583327712748769489, 0.571267316532588332, 0.559100585511540626, - 0.546820125163310577, 0.534417881237165604, 0.521885051592135052, 0.509211982443654398, - 0.496388045518671162, 0.483401491653461857, 0.470239275082169006, 0.456886840931420235, - 0.443327866073552401, 0.429543940225410703, 0.415514169600356364, 0.401214678896277765, - 0.386617977941119573, 0.371692145329917234, 0.356399760258393816, 0.340696481064849122, - 0.324529117016909452, 0.307832954674932158, 0.290527955491230394, 0.272513185478464703, - 0.253658363385912022, 0.233790483059674731, 0.212671510630966620, 0.189958689622431842, - 0.165127622564187282, 0.137304980940012589, 0.104838507565818778, 0.063852163815001570, - 0.000000000000000000]; -pub static ZIG_EXP_F: [f64; 257] = - [0.000167066692307963, 0.000454134353841497, 0.000967269282327174, 0.001536299780301573, - 0.002145967743718907, 0.002788798793574076, 0.003460264777836904, 0.004157295120833797, - 0.004877655983542396, 0.005619642207205489, 0.006381905937319183, 0.007163353183634991, - 0.007963077438017043, 0.008780314985808977, 0.009614413642502212, 0.010464810181029981, - 0.011331013597834600, 0.012212592426255378, 0.013109164931254991, 0.014020391403181943, - 0.014945968011691148, 0.015885621839973156, 0.016839106826039941, 0.017806200410911355, - 0.018786700744696024, 0.019780424338009740, 0.020787204072578114, 0.021806887504283581, - 0.022839335406385240, 0.023884420511558174, 0.024942026419731787, 0.026012046645134221, - 0.027094383780955803, 0.028188948763978646, 0.029295660224637411, 0.030414443910466622, - 0.031545232172893622, 0.032687963508959555, 0.033842582150874358, 0.035009037697397431, - 0.036187284781931443, 0.037377282772959382, 0.038578995503074871, 0.039792391023374139, - 0.041017441380414840, 0.042254122413316254, 0.043502413568888197, 0.044762297732943289, - 0.046033761076175184, 0.047316792913181561, 0.048611385573379504, 0.049917534282706379, - 0.051235237055126281, 0.052564494593071685, 0.053905310196046080, 0.055257689676697030, - 0.056621641283742870, 0.057997175631200659, 0.059384305633420280, 0.060783046445479660, - 0.062193415408541036, 0.063615431999807376, 0.065049117786753805, 0.066494496385339816, - 0.067951593421936643, 0.069420436498728783, 0.070901055162371843, 0.072393480875708752, - 0.073897746992364746, 0.075413888734058410, 0.076941943170480517, 0.078481949201606435, - 0.080033947542319905, 0.081597980709237419, 0.083174093009632397, 0.084762330532368146, - 0.086362741140756927, 0.087975374467270231, 0.089600281910032886, 0.091237516631040197, - 0.092887133556043569, 0.094549189376055873, 0.096223742550432825, 0.097910853311492213, - 0.099610583670637132, 0.101322997425953631, 0.103048160171257702, 0.104786139306570145, - 0.106537004050001632, 0.108300825451033755, 0.110077676405185357, 0.111867631670056283, - 0.113670767882744286, 0.115487163578633506, 0.117316899211555525, 0.119160057175327641, - 0.121016721826674792, 0.122886979509545108, 0.124770918580830933, 0.126668629437510671, - 0.128580204545228199, 0.130505738468330773, 0.132445327901387494, 0.134399071702213602, - 0.136367070926428829, 0.138349428863580176, 0.140346251074862399, 0.142357645432472146, - 0.144383722160634720, 0.146424593878344889, 0.148480375643866735, 0.150551185001039839, - 0.152637142027442801, 0.154738369384468027, 0.156854992369365148, 0.158987138969314129, - 0.161134939917591952, 0.163298528751901734, 0.165478041874935922, 0.167673618617250081, - 0.169885401302527550, 0.172113535315319977, 0.174358169171353411, 0.176619454590494829, - 0.178897546572478278, 0.181192603475496261, 0.183504787097767436, 0.185834262762197083, - 0.188181199404254262, 0.190545769663195363, 0.192928149976771296, 0.195328520679563189, - 0.197747066105098818, 0.200183974691911210, 0.202639439093708962, 0.205113656293837654, - 0.207606827724221982, 0.210119159388988230, 0.212650861992978224, 0.215202151075378628, - 0.217773247148700472, 0.220364375843359439, 0.222975768058120111, 0.225607660116683956, - 0.228260293930716618, 0.230933917169627356, 0.233628783437433291, 0.236345152457059560, - 0.239083290262449094, 0.241843469398877131, 0.244625969131892024, 0.247431075665327543, - 0.250259082368862240, 0.253110290015629402, 0.255985007030415324, 0.258883549749016173, - 0.261806242689362922, 0.264753418835062149, 0.267725419932044739, 0.270722596799059967, - 0.273745309652802915, 0.276793928448517301, 0.279868833236972869, 0.282970414538780746, - 0.286099073737076826, 0.289255223489677693, 0.292439288161892630, 0.295651704281261252, - 0.298892921015581847, 0.302163400675693528, 0.305463619244590256, 0.308794066934560185, - 0.312155248774179606, 0.315547685227128949, 0.318971912844957239, 0.322428484956089223, - 0.325917972393556354, 0.329440964264136438, 0.332998068761809096, 0.336589914028677717, - 0.340217149066780189, 0.343880444704502575, 0.347580494621637148, 0.351318016437483449, - 0.355093752866787626, 0.358908472948750001, 0.362762973354817997, 0.366658079781514379, - 0.370594648435146223, 0.374573567615902381, 0.378595759409581067, 0.382662181496010056, - 0.386773829084137932, 0.390931736984797384, 0.395136981833290435, 0.399390684475231350, - 0.403694012530530555, 0.408048183152032673, 0.412454465997161457, 0.416914186433003209, - 0.421428728997616908, 0.425999541143034677, 0.430628137288459167, 0.435316103215636907, - 0.440065100842354173, 0.444876873414548846, 0.449753251162755330, 0.454696157474615836, - 0.459707615642138023, 0.464789756250426511, 0.469944825283960310, 0.475175193037377708, - 0.480483363930454543, 0.485871987341885248, 0.491343869594032867, 0.496901987241549881, - 0.502549501841348056, 0.508289776410643213, 0.514126393814748894, 0.520063177368233931, - 0.526104213983620062, 0.532253880263043655, 0.538516872002862246, 0.544898237672440056, - 0.551403416540641733, 0.558038282262587892, 0.564809192912400615, 0.571723048664826150, - 0.578787358602845359, 0.586010318477268366, 0.593400901691733762, 0.600968966365232560, - 0.608725382079622346, 0.616682180915207878, 0.624852738703666200, 0.633251994214366398, - 0.641896716427266423, 0.650805833414571433, 0.660000841079000145, 0.669506316731925177, - 0.679350572264765806, 0.689566496117078431, 0.700192655082788606, 0.711274760805076456, - 0.722867659593572465, 0.735038092431424039, 0.747868621985195658, 0.761463388849896838, - 0.775956852040116218, 0.791527636972496285, 0.808421651523009044, 0.826993296643051101, - 0.847785500623990496, 0.871704332381204705, 0.900469929925747703, 0.938143680862176477, - 1.000000000000000000]; diff --git a/rand/src/lib.rs b/rand/src/lib.rs deleted file mode 100644 index ca231b5..0000000 --- a/rand/src/lib.rs +++ /dev/null @@ -1,852 +0,0 @@ -// Copyright 2018 Developers of the Rand project. -// Copyright 2013-2017 The Rust Project Developers. -// -// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or -// https://www.apache.org/licenses/LICENSE-2.0> or the MIT license -// <LICENSE-MIT or https://opensource.org/licenses/MIT>, at your -// option. This file may not be copied, modified, or distributed -// except according to those terms. - -//! Utilities for random number generation -//! -//! Rand provides utilities to generate random numbers, to convert them to -//! useful types and distributions, and some randomness-related algorithms. -//! -//! # Quick Start -//! -//! To get you started quickly, the easiest and highest-level way to get -//! a random value is to use [`random()`]; alternatively you can use -//! [`thread_rng()`]. The [`Rng`] trait provides a useful API on all RNGs, while -//! the [`distributions` module] and [`seq` module] provide further -//! functionality on top of RNGs. -//! -//! ``` -//! use rand::prelude::*; -//! -//! if rand::random() { // generates a boolean -//! // Try printing a random unicode code point (probably a bad idea)! -//! println!("char: {}", rand::random::<char>()); -//! } -//! -//! let mut rng = rand::thread_rng(); -//! let y: f64 = rng.gen(); // generates a float between 0 and 1 -//! -//! let mut nums: Vec<i32> = (1..100).collect(); -//! nums.shuffle(&mut rng); -//! ``` -//! -//! # The Book -//! -//! For the user guide and futher documentation, please read -//! [The Rust Rand Book](https://rust-random.github.io/book). -//! -//! [`distributions` module]: distributions/index.html -//! [`random()`]: fn.random.html -//! [`Rng`]: trait.Rng.html -//! [`seq` module]: seq/index.html -//! [`thread_rng()`]: fn.thread_rng.html - - -#![doc(html_logo_url = "https://www.rust-lang.org/logos/rust-logo-128x128-blk.png", - html_favicon_url = "https://www.rust-lang.org/favicon.ico", - html_root_url = "https://rust-random.github.io/rand/")] - -#![deny(missing_docs)] -#![deny(missing_debug_implementations)] -#![doc(test(attr(allow(unused_variables), deny(warnings))))] - -#![cfg_attr(not(feature="std"), no_std)] -#![cfg_attr(all(feature="alloc", not(feature="std")), feature(alloc))] -#![cfg_attr(all(feature="simd_support", feature="nightly"), feature(stdsimd))] - -#[cfg(feature = "std")] extern crate core; -#[cfg(all(feature = "alloc", not(feature="std")))] #[macro_use] extern crate alloc; - -#[cfg(feature="simd_support")] extern crate packed_simd; - -#[cfg(feature = "rand_os")] -extern crate rand_os; - -extern crate rand_core; -extern crate rand_isaac; // only for deprecations -extern crate rand_chacha; // only for deprecations -extern crate rand_hc; -extern crate rand_pcg; -extern crate rand_xorshift; - -#[cfg(feature = "log")] #[macro_use] extern crate log; -#[allow(unused)] -#[cfg(not(feature = "log"))] macro_rules! trace { ($($x:tt)*) => () } -#[allow(unused)] -#[cfg(not(feature = "log"))] macro_rules! debug { ($($x:tt)*) => () } -#[allow(unused)] -#[cfg(not(feature = "log"))] macro_rules! info { ($($x:tt)*) => () } -#[allow(unused)] -#[cfg(not(feature = "log"))] macro_rules! warn { ($($x:tt)*) => () } -#[allow(unused)] -#[cfg(not(feature = "log"))] macro_rules! error { ($($x:tt)*) => () } - - -// Re-exports from rand_core -pub use rand_core::{RngCore, CryptoRng, SeedableRng}; -pub use rand_core::{ErrorKind, Error}; - -// Public exports -#[cfg(feature="std")] pub use rngs::thread::thread_rng; - -// Public modules -pub mod distributions; -pub mod prelude; -#[deprecated(since="0.6.0")] -pub mod prng; -pub mod rngs; -pub mod seq; - -//////////////////////////////////////////////////////////////////////////////// -// Compatibility re-exports. Documentation is hidden; will be removed eventually. - -#[doc(hidden)] mod deprecated; - -#[allow(deprecated)] -#[doc(hidden)] pub use deprecated::ReseedingRng; - -#[allow(deprecated)] -#[cfg(feature="std")] #[doc(hidden)] pub use deprecated::EntropyRng; - -#[allow(deprecated)] -#[cfg(feature="rand_os")] -#[doc(hidden)] -pub use deprecated::OsRng; - -#[allow(deprecated)] -#[doc(hidden)] pub use deprecated::{ChaChaRng, IsaacRng, Isaac64Rng, XorShiftRng}; -#[allow(deprecated)] -#[doc(hidden)] pub use deprecated::StdRng; - - -#[allow(deprecated)] -#[doc(hidden)] -pub mod jitter { - pub use deprecated::JitterRng; - pub use rngs::TimerError; -} -#[allow(deprecated)] -#[cfg(feature="rand_os")] -#[doc(hidden)] -pub mod os { - pub use deprecated::OsRng; -} -#[allow(deprecated)] -#[doc(hidden)] -pub mod chacha { - pub use deprecated::ChaChaRng; -} -#[allow(deprecated)] -#[doc(hidden)] -pub mod isaac { - pub use deprecated::{IsaacRng, Isaac64Rng}; -} -#[allow(deprecated)] -#[cfg(feature="std")] -#[doc(hidden)] -pub mod read { - pub use deprecated::ReadRng; -} - -#[allow(deprecated)] -#[cfg(feature="std")] #[doc(hidden)] pub use deprecated::ThreadRng; - -//////////////////////////////////////////////////////////////////////////////// - - -use core::{mem, slice}; -use distributions::{Distribution, Standard}; -use distributions::uniform::{SampleUniform, UniformSampler, SampleBorrow}; - -/// An automatically-implemented extension trait on [`RngCore`] providing high-level -/// generic methods for sampling values and other convenience methods. -/// -/// This is the primary trait to use when generating random values. -/// -/// # Generic usage -/// -/// The basic pattern is `fn foo<R: Rng + ?Sized>(rng: &mut R)`. Some -/// things are worth noting here: -/// -/// - Since `Rng: RngCore` and every `RngCore` implements `Rng`, it makes no -/// difference whether we use `R: Rng` or `R: RngCore`. -/// - The `+ ?Sized` un-bounding allows functions to be called directly on -/// type-erased references; i.e. `foo(r)` where `r: &mut RngCore`. Without -/// this it would be necessary to write `foo(&mut r)`. -/// -/// An alternative pattern is possible: `fn foo<R: Rng>(rng: R)`. This has some -/// trade-offs. It allows the argument to be consumed directly without a `&mut` -/// (which is how `from_rng(thread_rng())` works); also it still works directly -/// on references (including type-erased references). Unfortunately within the -/// function `foo` it is not known whether `rng` is a reference type or not, -/// hence many uses of `rng` require an extra reference, either explicitly -/// (`distr.sample(&mut rng)`) or implicitly (`rng.gen()`); one may hope the -/// optimiser can remove redundant references later. -/// -/// Example: -/// -/// ``` -/// # use rand::thread_rng; -/// use rand::Rng; -/// -/// fn foo<R: Rng + ?Sized>(rng: &mut R) -> f32 { -/// rng.gen() -/// } -/// -/// # let v = foo(&mut thread_rng()); -/// ``` -/// -/// [`RngCore`]: trait.RngCore.html -pub trait Rng: RngCore { - /// Return a random value supporting the [`Standard`] distribution. - /// - /// [`Standard`]: distributions/struct.Standard.html - /// - /// # Example - /// - /// ``` - /// use rand::{thread_rng, Rng}; - /// - /// let mut rng = thread_rng(); - /// let x: u32 = rng.gen(); - /// println!("{}", x); - /// println!("{:?}", rng.gen::<(f64, bool)>()); - /// ``` - #[inline] - fn gen<T>(&mut self) -> T where Standard: Distribution<T> { - Standard.sample(self) - } - - /// Generate a random value in the range [`low`, `high`), i.e. inclusive of - /// `low` and exclusive of `high`. - /// - /// This function is optimised for the case that only a single sample is - /// made from the given range. See also the [`Uniform`] distribution - /// type which may be faster if sampling from the same range repeatedly. - /// - /// # Panics - /// - /// Panics if `low >= high`. - /// - /// # Example - /// - /// ``` - /// use rand::{thread_rng, Rng}; - /// - /// let mut rng = thread_rng(); - /// let n: u32 = rng.gen_range(0, 10); - /// println!("{}", n); - /// let m: f64 = rng.gen_range(-40.0f64, 1.3e5f64); - /// println!("{}", m); - /// ``` - /// - /// [`Uniform`]: distributions/uniform/struct.Uniform.html - fn gen_range<T: SampleUniform, B1, B2>(&mut self, low: B1, high: B2) -> T - where B1: SampleBorrow<T> + Sized, - B2: SampleBorrow<T> + Sized { - T::Sampler::sample_single(low, high, self) - } - - /// Sample a new value, using the given distribution. - /// - /// ### Example - /// - /// ``` - /// use rand::{thread_rng, Rng}; - /// use rand::distributions::Uniform; - /// - /// let mut rng = thread_rng(); - /// let x = rng.sample(Uniform::new(10u32, 15)); - /// // Type annotation requires two types, the type and distribution; the - /// // distribution can be inferred. - /// let y = rng.sample::<u16, _>(Uniform::new(10, 15)); - /// ``` - fn sample<T, D: Distribution<T>>(&mut self, distr: D) -> T { - distr.sample(self) - } - - /// Create an iterator that generates values using the given distribution. - /// - /// # Example - /// - /// ``` - /// use rand::{thread_rng, Rng}; - /// use rand::distributions::{Alphanumeric, Uniform, Standard}; - /// - /// let mut rng = thread_rng(); - /// - /// // Vec of 16 x f32: - /// let v: Vec<f32> = thread_rng().sample_iter(&Standard).take(16).collect(); - /// - /// // String: - /// let s: String = rng.sample_iter(&Alphanumeric).take(7).collect(); - /// - /// // Combined values - /// println!("{:?}", thread_rng().sample_iter(&Standard).take(5) - /// .collect::<Vec<(f64, bool)>>()); - /// - /// // Dice-rolling: - /// let die_range = Uniform::new_inclusive(1, 6); - /// let mut roll_die = rng.sample_iter(&die_range); - /// while roll_die.next().unwrap() != 6 { - /// println!("Not a 6; rolling again!"); - /// } - /// ``` - fn sample_iter<'a, T, D: Distribution<T>>(&'a mut self, distr: &'a D) - -> distributions::DistIter<'a, D, Self, T> where Self: Sized - { - distr.sample_iter(self) - } - - /// Fill `dest` entirely with random bytes (uniform value distribution), - /// where `dest` is any type supporting [`AsByteSliceMut`], namely slices - /// and arrays over primitive integer types (`i8`, `i16`, `u32`, etc.). - /// - /// On big-endian platforms this performs byte-swapping to ensure - /// portability of results from reproducible generators. - /// - /// This uses [`fill_bytes`] internally which may handle some RNG errors - /// implicitly (e.g. waiting if the OS generator is not ready), but panics - /// on other errors. See also [`try_fill`] which returns errors. - /// - /// # Example - /// - /// ``` - /// use rand::{thread_rng, Rng}; - /// - /// let mut arr = [0i8; 20]; - /// thread_rng().fill(&mut arr[..]); - /// ``` - /// - /// [`fill_bytes`]: trait.RngCore.html#method.fill_bytes - /// [`try_fill`]: trait.Rng.html#method.try_fill - /// [`AsByteSliceMut`]: trait.AsByteSliceMut.html - fn fill<T: AsByteSliceMut + ?Sized>(&mut self, dest: &mut T) { - self.fill_bytes(dest.as_byte_slice_mut()); - dest.to_le(); - } - - /// Fill `dest` entirely with random bytes (uniform value distribution), - /// where `dest` is any type supporting [`AsByteSliceMut`], namely slices - /// and arrays over primitive integer types (`i8`, `i16`, `u32`, etc.). - /// - /// On big-endian platforms this performs byte-swapping to ensure - /// portability of results from reproducible generators. - /// - /// This uses [`try_fill_bytes`] internally and forwards all RNG errors. In - /// some cases errors may be resolvable; see [`ErrorKind`] and - /// documentation for the RNG in use. If you do not plan to handle these - /// errors you may prefer to use [`fill`]. - /// - /// # Example - /// - /// ``` - /// # use rand::Error; - /// use rand::{thread_rng, Rng}; - /// - /// # fn try_inner() -> Result<(), Error> { - /// let mut arr = [0u64; 4]; - /// thread_rng().try_fill(&mut arr[..])?; - /// # Ok(()) - /// # } - /// - /// # try_inner().unwrap() - /// ``` - /// - /// [`ErrorKind`]: enum.ErrorKind.html - /// [`try_fill_bytes`]: trait.RngCore.html#method.try_fill_bytes - /// [`fill`]: trait.Rng.html#method.fill - /// [`AsByteSliceMut`]: trait.AsByteSliceMut.html - fn try_fill<T: AsByteSliceMut + ?Sized>(&mut self, dest: &mut T) -> Result<(), Error> { - self.try_fill_bytes(dest.as_byte_slice_mut())?; - dest.to_le(); - Ok(()) - } - - /// Return a bool with a probability `p` of being true. - /// - /// See also the [`Bernoulli`] distribution, which may be faster if - /// sampling from the same probability repeatedly. - /// - /// # Example - /// - /// ``` - /// use rand::{thread_rng, Rng}; - /// - /// let mut rng = thread_rng(); - /// println!("{}", rng.gen_bool(1.0 / 3.0)); - /// ``` - /// - /// # Panics - /// - /// If `p < 0` or `p > 1`. - /// - /// [`Bernoulli`]: distributions/bernoulli/struct.Bernoulli.html - #[inline] - fn gen_bool(&mut self, p: f64) -> bool { - let d = distributions::Bernoulli::new(p); - self.sample(d) - } - - /// Return a bool with a probability of `numerator/denominator` of being - /// true. I.e. `gen_ratio(2, 3)` has chance of 2 in 3, or about 67%, of - /// returning true. If `numerator == denominator`, then the returned value - /// is guaranteed to be `true`. If `numerator == 0`, then the returned - /// value is guaranteed to be `false`. - /// - /// See also the [`Bernoulli`] distribution, which may be faster if - /// sampling from the same `numerator` and `denominator` repeatedly. - /// - /// # Panics - /// - /// If `denominator == 0` or `numerator > denominator`. - /// - /// # Example - /// - /// ``` - /// use rand::{thread_rng, Rng}; - /// - /// let mut rng = thread_rng(); - /// println!("{}", rng.gen_ratio(2, 3)); - /// ``` - /// - /// [`Bernoulli`]: distributions/bernoulli/struct.Bernoulli.html - #[inline] - fn gen_ratio(&mut self, numerator: u32, denominator: u32) -> bool { - let d = distributions::Bernoulli::from_ratio(numerator, denominator); - self.sample(d) - } - - /// Return a random element from `values`. - /// - /// Deprecated: use [`SliceRandom::choose`] instead. - /// - /// [`SliceRandom::choose`]: seq/trait.SliceRandom.html#method.choose - #[deprecated(since="0.6.0", note="use SliceRandom::choose instead")] - fn choose<'a, T>(&mut self, values: &'a [T]) -> Option<&'a T> { - use seq::SliceRandom; - values.choose(self) - } - - /// Return a mutable pointer to a random element from `values`. - /// - /// Deprecated: use [`SliceRandom::choose_mut`] instead. - /// - /// [`SliceRandom::choose_mut`]: seq/trait.SliceRandom.html#method.choose_mut - #[deprecated(since="0.6.0", note="use SliceRandom::choose_mut instead")] - fn choose_mut<'a, T>(&mut self, values: &'a mut [T]) -> Option<&'a mut T> { - use seq::SliceRandom; - values.choose_mut(self) - } - - /// Shuffle a mutable slice in place. - /// - /// Deprecated: use [`SliceRandom::shuffle`] instead. - /// - /// [`SliceRandom::shuffle`]: seq/trait.SliceRandom.html#method.shuffle - #[deprecated(since="0.6.0", note="use SliceRandom::shuffle instead")] - fn shuffle<T>(&mut self, values: &mut [T]) { - use seq::SliceRandom; - values.shuffle(self) - } -} - -impl<R: RngCore + ?Sized> Rng for R {} - -/// Trait for casting types to byte slices -/// -/// This is used by the [`fill`] and [`try_fill`] methods. -/// -/// [`fill`]: trait.Rng.html#method.fill -/// [`try_fill`]: trait.Rng.html#method.try_fill -pub trait AsByteSliceMut { - /// Return a mutable reference to self as a byte slice - fn as_byte_slice_mut(&mut self) -> &mut [u8]; - - /// Call `to_le` on each element (i.e. byte-swap on Big Endian platforms). - fn to_le(&mut self); -} - -impl AsByteSliceMut for [u8] { - fn as_byte_slice_mut(&mut self) -> &mut [u8] { - self - } - - fn to_le(&mut self) {} -} - -macro_rules! impl_as_byte_slice { - ($t:ty) => { - impl AsByteSliceMut for [$t] { - fn as_byte_slice_mut(&mut self) -> &mut [u8] { - if self.len() == 0 { - unsafe { - // must not use null pointer - slice::from_raw_parts_mut(0x1 as *mut u8, 0) - } - } else { - unsafe { - slice::from_raw_parts_mut(&mut self[0] - as *mut $t - as *mut u8, - self.len() * mem::size_of::<$t>() - ) - } - } - } - - fn to_le(&mut self) { - for x in self { - *x = x.to_le(); - } - } - } - } -} - -impl_as_byte_slice!(u16); -impl_as_byte_slice!(u32); -impl_as_byte_slice!(u64); -#[cfg(all(rustc_1_26, not(target_os = "emscripten")))] impl_as_byte_slice!(u128); -impl_as_byte_slice!(usize); -impl_as_byte_slice!(i8); -impl_as_byte_slice!(i16); -impl_as_byte_slice!(i32); -impl_as_byte_slice!(i64); -#[cfg(all(rustc_1_26, not(target_os = "emscripten")))] impl_as_byte_slice!(i128); -impl_as_byte_slice!(isize); - -macro_rules! impl_as_byte_slice_arrays { - ($n:expr,) => {}; - ($n:expr, $N:ident, $($NN:ident,)*) => { - impl_as_byte_slice_arrays!($n - 1, $($NN,)*); - - impl<T> AsByteSliceMut for [T; $n] where [T]: AsByteSliceMut { - fn as_byte_slice_mut(&mut self) -> &mut [u8] { - self[..].as_byte_slice_mut() - } - - fn to_le(&mut self) { - self[..].to_le() - } - } - }; - (!div $n:expr,) => {}; - (!div $n:expr, $N:ident, $($NN:ident,)*) => { - impl_as_byte_slice_arrays!(!div $n / 2, $($NN,)*); - - impl<T> AsByteSliceMut for [T; $n] where [T]: AsByteSliceMut { - fn as_byte_slice_mut(&mut self) -> &mut [u8] { - self[..].as_byte_slice_mut() - } - - fn to_le(&mut self) { - self[..].to_le() - } - } - }; -} -impl_as_byte_slice_arrays!(32, N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,); -impl_as_byte_slice_arrays!(!div 4096, N,N,N,N,N,N,N,); - - -/// A convenience extension to [`SeedableRng`] allowing construction from fresh -/// entropy. This trait is automatically implemented for any PRNG implementing -/// [`SeedableRng`] and is not intended to be implemented by users. -/// -/// This is equivalent to using `SeedableRng::from_rng(EntropyRng::new())` then -/// unwrapping the result. -/// -/// Since this is convenient and secure, it is the recommended way to create -/// PRNGs, though two alternatives may be considered: -/// -/// * Deterministic creation using [`SeedableRng::from_seed`] with a fixed seed -/// * Seeding from `thread_rng`: `SeedableRng::from_rng(thread_rng())?`; -/// this will usually be faster and should also be secure, but requires -/// trusting one extra component. -/// -/// ## Example -/// -/// ``` -/// use rand::{Rng, FromEntropy}; -/// use rand::rngs::StdRng; -/// -/// let mut rng = StdRng::from_entropy(); -/// println!("Random die roll: {}", rng.gen_range(1, 7)); -/// ``` -/// -/// [`EntropyRng`]: rngs/struct.EntropyRng.html -/// [`SeedableRng`]: trait.SeedableRng.html -/// [`SeedableRng::from_seed`]: trait.SeedableRng.html#tymethod.from_seed -#[cfg(feature="std")] -pub trait FromEntropy: SeedableRng { - /// Creates a new instance, automatically seeded with fresh entropy. - /// - /// Normally this will use `OsRng`, but if that fails `JitterRng` will be - /// used instead. Both should be suitable for cryptography. It is possible - /// that both entropy sources will fail though unlikely; failures would - /// almost certainly be platform limitations or build issues, i.e. most - /// applications targetting PC/mobile platforms should not need to worry - /// about this failing. - /// - /// # Panics - /// - /// If all entropy sources fail this will panic. If you need to handle - /// errors, use the following code, equivalent aside from error handling: - /// - /// ``` - /// # use rand::Error; - /// use rand::prelude::*; - /// use rand::rngs::EntropyRng; - /// - /// # fn try_inner() -> Result<(), Error> { - /// // This uses StdRng, but is valid for any R: SeedableRng - /// let mut rng = StdRng::from_rng(EntropyRng::new())?; - /// - /// println!("random number: {}", rng.gen_range(1, 10)); - /// # Ok(()) - /// # } - /// - /// # try_inner().unwrap() - /// ``` - fn from_entropy() -> Self; -} - -#[cfg(feature="std")] -impl<R: SeedableRng> FromEntropy for R { - fn from_entropy() -> R { - R::from_rng(rngs::EntropyRng::new()).unwrap_or_else(|err| - panic!("FromEntropy::from_entropy() failed: {}", err)) - } -} - - -/// Generates a random value using the thread-local random number generator. -/// -/// This is simply a shortcut for `thread_rng().gen()`. See [`thread_rng`] for -/// documentation of the entropy source and [`Standard`] for documentation of -/// distributions and type-specific generation. -/// -/// # Examples -/// -/// ``` -/// let x = rand::random::<u8>(); -/// println!("{}", x); -/// -/// let y = rand::random::<f64>(); -/// println!("{}", y); -/// -/// if rand::random() { // generates a boolean -/// println!("Better lucky than good!"); -/// } -/// ``` -/// -/// If you're calling `random()` in a loop, caching the generator as in the -/// following example can increase performance. -/// -/// ``` -/// use rand::Rng; -/// -/// let mut v = vec![1, 2, 3]; -/// -/// for x in v.iter_mut() { -/// *x = rand::random() -/// } -/// -/// // can be made faster by caching thread_rng -/// -/// let mut rng = rand::thread_rng(); -/// -/// for x in v.iter_mut() { -/// *x = rng.gen(); -/// } -/// ``` -/// -/// [`thread_rng`]: fn.thread_rng.html -/// [`Standard`]: distributions/struct.Standard.html -#[cfg(feature="std")] -#[inline] -pub fn random<T>() -> T where Standard: Distribution<T> { - thread_rng().gen() -} - -#[cfg(test)] -mod test { - use rngs::mock::StepRng; - use rngs::StdRng; - use super::*; - #[cfg(all(not(feature="std"), feature="alloc"))] use alloc::boxed::Box; - - pub struct TestRng<R> { inner: R } - - impl<R: RngCore> RngCore for TestRng<R> { - fn next_u32(&mut self) -> u32 { - self.inner.next_u32() - } - fn next_u64(&mut self) -> u64 { - self.inner.next_u64() - } - fn fill_bytes(&mut self, dest: &mut [u8]) { - self.inner.fill_bytes(dest) - } - fn try_fill_bytes(&mut self, dest: &mut [u8]) -> Result<(), Error> { - self.inner.try_fill_bytes(dest) - } - } - - pub fn rng(seed: u64) -> TestRng<StdRng> { - TestRng { inner: StdRng::seed_from_u64(seed) } - } - - #[test] - fn test_fill_bytes_default() { - let mut r = StepRng::new(0x11_22_33_44_55_66_77_88, 0); - - // check every remainder mod 8, both in small and big vectors. - let lengths = [0, 1, 2, 3, 4, 5, 6, 7, - 80, 81, 82, 83, 84, 85, 86, 87]; - for &n in lengths.iter() { - let mut buffer = [0u8; 87]; - let v = &mut buffer[0..n]; - r.fill_bytes(v); - - // use this to get nicer error messages. - for (i, &byte) in v.iter().enumerate() { - if byte == 0 { - panic!("byte {} of {} is zero", i, n) - } - } - } - } - - #[test] - fn test_fill() { - let x = 9041086907909331047; // a random u64 - let mut rng = StepRng::new(x, 0); - - // Convert to byte sequence and back to u64; byte-swap twice if BE. - let mut array = [0u64; 2]; - rng.fill(&mut array[..]); - assert_eq!(array, [x, x]); - assert_eq!(rng.next_u64(), x); - - // Convert to bytes then u32 in LE order - let mut array = [0u32; 2]; - rng.fill(&mut array[..]); - assert_eq!(array, [x as u32, (x >> 32) as u32]); - assert_eq!(rng.next_u32(), x as u32); - } - - #[test] - fn test_fill_empty() { - let mut array = [0u32; 0]; - let mut rng = StepRng::new(0, 1); - rng.fill(&mut array); - rng.fill(&mut array[..]); - } - - #[test] - fn test_gen_range() { - let mut r = rng(101); - for _ in 0..1000 { - let a = r.gen_range(-4711, 17); - assert!(a >= -4711 && a < 17); - let a = r.gen_range(-3i8, 42); - assert!(a >= -3i8 && a < 42i8); - let a = r.gen_range(&10u16, 99); - assert!(a >= 10u16 && a < 99u16); - let a = r.gen_range(-100i32, &2000); - assert!(a >= -100i32 && a < 2000i32); - let a = r.gen_range(&12u32, &24u32); - assert!(a >= 12u32 && a < 24u32); - - assert_eq!(r.gen_range(0u32, 1), 0u32); - assert_eq!(r.gen_range(-12i64, -11), -12i64); - assert_eq!(r.gen_range(3_000_000, 3_000_001), 3_000_000); - } - } - - #[test] - #[should_panic] - fn test_gen_range_panic_int() { - let mut r = rng(102); - r.gen_range(5, -2); - } - - #[test] - #[should_panic] - fn test_gen_range_panic_usize() { - let mut r = rng(103); - r.gen_range(5, 2); - } - - #[test] - fn test_gen_bool() { - let mut r = rng(105); - for _ in 0..5 { - assert_eq!(r.gen_bool(0.0), false); - assert_eq!(r.gen_bool(1.0), true); - } - } - - #[test] - fn test_rng_trait_object() { - use distributions::{Distribution, Standard}; - let mut rng = rng(109); - let mut r = &mut rng as &mut RngCore; - r.next_u32(); - r.gen::<i32>(); - assert_eq!(r.gen_range(0, 1), 0); - let _c: u8 = Standard.sample(&mut r); - } - - #[test] - #[cfg(feature="alloc")] - fn test_rng_boxed_trait() { - use distributions::{Distribution, Standard}; - let rng = rng(110); - let mut r = Box::new(rng) as Box<RngCore>; - r.next_u32(); - r.gen::<i32>(); - assert_eq!(r.gen_range(0, 1), 0); - let _c: u8 = Standard.sample(&mut r); - } - - #[test] - #[cfg(feature="std")] - fn test_random() { - // not sure how to test this aside from just getting some values - let _n : usize = random(); - let _f : f32 = random(); - let _o : Option<Option<i8>> = random(); - let _many : ((), - (usize, - isize, - Option<(u32, (bool,))>), - (u8, i8, u16, i16, u32, i32, u64, i64), - (f32, (f64, (f64,)))) = random(); - } - - #[test] - fn test_gen_ratio_average() { - const NUM: u32 = 3; - const DENOM: u32 = 10; - const N: u32 = 100_000; - - let mut sum: u32 = 0; - let mut rng = rng(111); - for _ in 0..N { - if rng.gen_ratio(NUM, DENOM) { - sum += 1; - } - } - // Have Binomial(N, NUM/DENOM) distribution - let expected = (NUM * N) / DENOM; // exact integer - assert!(((sum - expected) as i32).abs() < 500); - } -} diff --git a/rand/src/prelude.rs b/rand/src/prelude.rs deleted file mode 100644 index 5d8a0e9..0000000 --- a/rand/src/prelude.rs +++ /dev/null @@ -1,27 +0,0 @@ -// Copyright 2018 Developers of the Rand project. -// -// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or -// https://www.apache.org/licenses/LICENSE-2.0> or the MIT license -// <LICENSE-MIT or https://opensource.org/licenses/MIT>, at your -// option. This file may not be copied, modified, or distributed -// except according to those terms. - -//! Convenience re-export of common members -//! -//! Like the standard library's prelude, this module simplifies importing of -//! common items. Unlike the standard prelude, the contents of this module must -//! be imported manually: -//! -//! ``` -//! use rand::prelude::*; -//! # let _ = StdRng::from_entropy(); -//! # let mut r = SmallRng::from_rng(thread_rng()).unwrap(); -//! # let _: f32 = r.gen(); -//! ``` - -#[doc(no_inline)] pub use distributions::Distribution; -#[doc(no_inline)] pub use rngs::{SmallRng, StdRng}; -#[doc(no_inline)] #[cfg(feature="std")] pub use rngs::ThreadRng; -#[doc(no_inline)] pub use {Rng, RngCore, CryptoRng, SeedableRng}; -#[doc(no_inline)] #[cfg(feature="std")] pub use {FromEntropy, random, thread_rng}; -#[doc(no_inline)] pub use seq::{SliceRandom, IteratorRandom}; diff --git a/rand/src/prng/mod.rs b/rand/src/prng/mod.rs deleted file mode 100644 index 3c0d27b..0000000 --- a/rand/src/prng/mod.rs +++ /dev/null @@ -1,37 +0,0 @@ -// Copyright 2018 Developers of the Rand project. -// -// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or -// https://www.apache.org/licenses/LICENSE-2.0> or the MIT license -// <LICENSE-MIT or https://opensource.org/licenses/MIT>, at your -// option. This file may not be copied, modified, or distributed -// except according to those terms. - -//! Pseudo-random number generators. -//! -//! This module is deprecated: -//! -//! - documentation has moved to -//! [The Book](https://rust-random.github.io/book/guide-rngs.html), -//! - PRNGs have moved to other `rand_*` crates. - -// Deprecations (to be removed in 0.7) -#[doc(hidden)] #[allow(deprecated)] -pub use deprecated::XorShiftRng; -#[doc(hidden)] pub mod isaac { - // Note: we miss `IsaacCore` here but probably unimportant. - #[allow(deprecated)] pub use deprecated::IsaacRng; -} -#[doc(hidden)] pub mod isaac64 { - #[allow(deprecated)] pub use deprecated::Isaac64Rng; -} -#[doc(hidden)] #[allow(deprecated)] pub use deprecated::{IsaacRng, Isaac64Rng}; -#[doc(hidden)] pub mod chacha { - // Note: we miss `ChaChaCore` here but probably unimportant. - #[allow(deprecated)] pub use deprecated::ChaChaRng; -} -#[doc(hidden)] #[allow(deprecated)] pub use deprecated::ChaChaRng; -#[doc(hidden)] pub mod hc128 { - // Note: we miss `Hc128Core` here but probably unimportant. - #[allow(deprecated)] pub use deprecated::Hc128Rng; -} -#[doc(hidden)] #[allow(deprecated)] pub use deprecated::Hc128Rng; diff --git a/rand/src/rngs/adapter/mod.rs b/rand/src/rngs/adapter/mod.rs deleted file mode 100644 index 60b832e..0000000 --- a/rand/src/rngs/adapter/mod.rs +++ /dev/null @@ -1,15 +0,0 @@ -// Copyright 2018 Developers of the Rand project. -// -// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or -// https://www.apache.org/licenses/LICENSE-2.0> or the MIT license -// <LICENSE-MIT or https://opensource.org/licenses/MIT>, at your -// option. This file may not be copied, modified, or distributed -// except according to those terms. - -//! Wrappers / adapters forming RNGs - -#[cfg(feature="std")] #[doc(hidden)] pub mod read; -mod reseeding; - -#[cfg(feature="std")] pub use self::read::ReadRng; -pub use self::reseeding::ReseedingRng; diff --git a/rand/src/rngs/adapter/read.rs b/rand/src/rngs/adapter/read.rs deleted file mode 100644 index 30b6de6..0000000 --- a/rand/src/rngs/adapter/read.rs +++ /dev/null @@ -1,137 +0,0 @@ -// Copyright 2018 Developers of the Rand project. -// Copyright 2013 The Rust Project Developers. -// -// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or -// https://www.apache.org/licenses/LICENSE-2.0> or the MIT license -// <LICENSE-MIT or https://opensource.org/licenses/MIT>, at your -// option. This file may not be copied, modified, or distributed -// except according to those terms. - -//! A wrapper around any Read to treat it as an RNG. - -use std::io::Read; - -use rand_core::{RngCore, Error, ErrorKind, impls}; - - -/// An RNG that reads random bytes straight from any type supporting -/// `std::io::Read`, for example files. -/// -/// This will work best with an infinite reader, but that is not required. -/// -/// This can be used with `/dev/urandom` on Unix but it is recommended to use -/// [`OsRng`] instead. -/// -/// # Panics -/// -/// `ReadRng` uses `std::io::read_exact`, which retries on interrupts. All other -/// errors from the underlying reader, including when it does not have enough -/// data, will only be reported through [`try_fill_bytes`]. The other -/// [`RngCore`] methods will panic in case of an error. -/// -/// # Example -/// -/// ``` -/// use rand::Rng; -/// use rand::rngs::adapter::ReadRng; -/// -/// let data = vec![1, 2, 3, 4, 5, 6, 7, 8]; -/// let mut rng = ReadRng::new(&data[..]); -/// println!("{:x}", rng.gen::<u32>()); -/// ``` -/// -/// [`OsRng`]: ../struct.OsRng.html -/// [`RngCore`]: ../../trait.RngCore.html -/// [`try_fill_bytes`]: ../../trait.RngCore.html#method.tymethod.try_fill_bytes -#[derive(Debug)] -pub struct ReadRng<R> { - reader: R -} - -impl<R: Read> ReadRng<R> { - /// Create a new `ReadRng` from a `Read`. - pub fn new(r: R) -> ReadRng<R> { - ReadRng { - reader: r - } - } -} - -impl<R: Read> RngCore for ReadRng<R> { - fn next_u32(&mut self) -> u32 { - impls::next_u32_via_fill(self) - } - - fn next_u64(&mut self) -> u64 { - impls::next_u64_via_fill(self) - } - - fn fill_bytes(&mut self, dest: &mut [u8]) { - self.try_fill_bytes(dest).unwrap_or_else(|err| - panic!("reading random bytes from Read implementation failed; error: {}", err)); - } - - fn try_fill_bytes(&mut self, dest: &mut [u8]) -> Result<(), Error> { - if dest.len() == 0 { return Ok(()); } - // Use `std::io::read_exact`, which retries on `ErrorKind::Interrupted`. - self.reader.read_exact(dest).map_err(|err| { - match err.kind() { - ::std::io::ErrorKind::UnexpectedEof => Error::with_cause( - ErrorKind::Unavailable, - "not enough bytes available, reached end of source", err), - _ => Error::with_cause(ErrorKind::Unavailable, - "error reading from Read source", err) - } - }) - } -} - -#[cfg(test)] -mod test { - use super::ReadRng; - use {RngCore, ErrorKind}; - - #[test] - fn test_reader_rng_u64() { - // transmute from the target to avoid endianness concerns. - let v = vec![0u8, 0, 0, 0, 0, 0, 0, 1, - 0 , 0, 0, 0, 0, 0, 0, 2, - 0, 0, 0, 0, 0, 0, 0, 3]; - let mut rng = ReadRng::new(&v[..]); - - assert_eq!(rng.next_u64(), 1_u64.to_be()); - assert_eq!(rng.next_u64(), 2_u64.to_be()); - assert_eq!(rng.next_u64(), 3_u64.to_be()); - } - - #[test] - fn test_reader_rng_u32() { - let v = vec![0u8, 0, 0, 1, 0, 0, 0, 2, 0, 0, 0, 3]; - let mut rng = ReadRng::new(&v[..]); - - assert_eq!(rng.next_u32(), 1_u32.to_be()); - assert_eq!(rng.next_u32(), 2_u32.to_be()); - assert_eq!(rng.next_u32(), 3_u32.to_be()); - } - - #[test] - fn test_reader_rng_fill_bytes() { - let v = [1u8, 2, 3, 4, 5, 6, 7, 8]; - let mut w = [0u8; 8]; - - let mut rng = ReadRng::new(&v[..]); - rng.fill_bytes(&mut w); - - assert!(v == w); - } - - #[test] - fn test_reader_rng_insufficient_bytes() { - let v = [1u8, 2, 3, 4, 5, 6, 7, 8]; - let mut w = [0u8; 9]; - - let mut rng = ReadRng::new(&v[..]); - - assert!(rng.try_fill_bytes(&mut w).err().unwrap().kind == ErrorKind::Unavailable); - } -} diff --git a/rand/src/rngs/adapter/reseeding.rs b/rand/src/rngs/adapter/reseeding.rs deleted file mode 100644 index 016afab..0000000 --- a/rand/src/rngs/adapter/reseeding.rs +++ /dev/null @@ -1,370 +0,0 @@ -// Copyright 2018 Developers of the Rand project. -// Copyright 2013 The Rust Project Developers. -// -// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or -// https://www.apache.org/licenses/LICENSE-2.0> or the MIT license -// <LICENSE-MIT or https://opensource.org/licenses/MIT>, at your -// option. This file may not be copied, modified, or distributed -// except according to those terms. - -//! A wrapper around another PRNG that reseeds it after it -//! generates a certain number of random bytes. - -use core::mem::size_of; - -use rand_core::{RngCore, CryptoRng, SeedableRng, Error, ErrorKind}; -use rand_core::block::{BlockRngCore, BlockRng}; - -/// A wrapper around any PRNG that implements [`BlockRngCore`], that adds the -/// ability to reseed it. -/// -/// `ReseedingRng` reseeds the underlying PRNG in the following cases: -/// -/// - On a manual call to [`reseed()`]. -/// - After `clone()`, the clone will be reseeded on first use. -/// - After a process is forked, the RNG in the child process is reseeded within -/// the next few generated values, depending on the block size of the -/// underlying PRNG. For [`ChaChaCore`] and [`Hc128Core`] this is a maximum of -/// 15 `u32` values before reseeding. -/// - After the PRNG has generated a configurable number of random bytes. -/// -/// # When should reseeding after a fixed number of generated bytes be used? -/// -/// Reseeding after a fixed number of generated bytes is never strictly -/// *necessary*. Cryptographic PRNGs don't have a limited number of bytes they -/// can output, or at least not a limit reachable in any practical way. There is -/// no such thing as 'running out of entropy'. -/// -/// Occasionally reseeding can be seen as some form of 'security in depth'. Even -/// if in the future a cryptographic weakness is found in the CSPRNG being used, -/// or a flaw in the implementation, occasionally reseeding should make -/// exploiting it much more difficult or even impossible. -/// -/// Use [`ReseedingRng::new`] with a `threshold` of `0` to disable reseeding -/// after a fixed number of generated bytes. -/// -/// # Error handling -/// -/// Although unlikely, reseeding the wrapped PRNG can fail. `ReseedingRng` will -/// never panic but try to handle the error intelligently through some -/// combination of retrying and delaying reseeding until later. -/// If handling the source error fails `ReseedingRng` will continue generating -/// data from the wrapped PRNG without reseeding. -/// -/// Manually calling [`reseed()`] will not have this retry or delay logic, but -/// reports the error. -/// -/// # Example -/// -/// ``` -/// # extern crate rand; -/// # extern crate rand_chacha; -/// # fn main() { -/// use rand::prelude::*; -/// use rand_chacha::ChaChaCore; // Internal part of ChaChaRng that -/// // implements BlockRngCore -/// use rand::rngs::OsRng; -/// use rand::rngs::adapter::ReseedingRng; -/// -/// let prng = ChaChaCore::from_entropy(); -// FIXME: it is better to use EntropyRng as reseeder, but that doesn't implement -// clone yet. -/// let reseeder = OsRng::new().unwrap(); -/// let mut reseeding_rng = ReseedingRng::new(prng, 0, reseeder); -/// -/// println!("{}", reseeding_rng.gen::<u64>()); -/// -/// let mut cloned_rng = reseeding_rng.clone(); -/// assert!(reseeding_rng.gen::<u64>() != cloned_rng.gen::<u64>()); -/// # } -/// ``` -/// -/// [`ChaChaCore`]: ../../../rand_chacha/struct.ChaChaCore.html -/// [`Hc128Core`]: ../../../rand_hc/struct.Hc128Core.html -/// [`BlockRngCore`]: ../../../rand_core/block/trait.BlockRngCore.html -/// [`ReseedingRng::new`]: struct.ReseedingRng.html#method.new -/// [`reseed()`]: struct.ReseedingRng.html#method.reseed -#[derive(Debug)] -pub struct ReseedingRng<R, Rsdr>(BlockRng<ReseedingCore<R, Rsdr>>) -where R: BlockRngCore + SeedableRng, - Rsdr: RngCore; - -impl<R, Rsdr> ReseedingRng<R, Rsdr> -where R: BlockRngCore + SeedableRng, - Rsdr: RngCore -{ - /// Create a new `ReseedingRng` from an existing PRNG, combined with a RNG - /// to use as reseeder. - /// - /// `threshold` sets the number of generated bytes after which to reseed the - /// PRNG. Set it to zero to never reseed based on the number of generated - /// values. - pub fn new(rng: R, threshold: u64, reseeder: Rsdr) -> Self { - ReseedingRng(BlockRng::new(ReseedingCore::new(rng, threshold, reseeder))) - } - - /// Reseed the internal PRNG. - pub fn reseed(&mut self) -> Result<(), Error> { - self.0.core.reseed() - } -} - -// TODO: this should be implemented for any type where the inner type -// implements RngCore, but we can't specify that because ReseedingCore is private -impl<R, Rsdr: RngCore> RngCore for ReseedingRng<R, Rsdr> -where R: BlockRngCore<Item = u32> + SeedableRng, - <R as BlockRngCore>::Results: AsRef<[u32]> + AsMut<[u32]> -{ - #[inline(always)] - fn next_u32(&mut self) -> u32 { - self.0.next_u32() - } - - #[inline(always)] - fn next_u64(&mut self) -> u64 { - self.0.next_u64() - } - - fn fill_bytes(&mut self, dest: &mut [u8]) { - self.0.fill_bytes(dest) - } - - fn try_fill_bytes(&mut self, dest: &mut [u8]) -> Result<(), Error> { - self.0.try_fill_bytes(dest) - } -} - -impl<R, Rsdr> Clone for ReseedingRng<R, Rsdr> -where R: BlockRngCore + SeedableRng + Clone, - Rsdr: RngCore + Clone -{ - fn clone(&self) -> ReseedingRng<R, Rsdr> { - // Recreating `BlockRng` seems easier than cloning it and resetting - // the index. - ReseedingRng(BlockRng::new(self.0.core.clone())) - } -} - -impl<R, Rsdr> CryptoRng for ReseedingRng<R, Rsdr> -where R: BlockRngCore + SeedableRng + CryptoRng, - Rsdr: RngCore + CryptoRng {} - -#[derive(Debug)] -struct ReseedingCore<R, Rsdr> { - inner: R, - reseeder: Rsdr, - threshold: i64, - bytes_until_reseed: i64, - fork_counter: usize, -} - -impl<R, Rsdr> BlockRngCore for ReseedingCore<R, Rsdr> -where R: BlockRngCore + SeedableRng, - Rsdr: RngCore -{ - type Item = <R as BlockRngCore>::Item; - type Results = <R as BlockRngCore>::Results; - - fn generate(&mut self, results: &mut Self::Results) { - let global_fork_counter = fork::get_fork_counter(); - if self.bytes_until_reseed <= 0 || - self.is_forked(global_fork_counter) { - // We get better performance by not calling only `reseed` here - // and continuing with the rest of the function, but by directly - // returning from a non-inlined function. - return self.reseed_and_generate(results, global_fork_counter); - } - let num_bytes = results.as_ref().len() * size_of::<Self::Item>(); - self.bytes_until_reseed -= num_bytes as i64; - self.inner.generate(results); - } -} - -impl<R, Rsdr> ReseedingCore<R, Rsdr> -where R: BlockRngCore + SeedableRng, - Rsdr: RngCore -{ - /// Create a new `ReseedingCore`. - fn new(rng: R, threshold: u64, reseeder: Rsdr) -> Self { - use ::core::i64::MAX; - fork::register_fork_handler(); - - // Because generating more values than `i64::MAX` takes centuries on - // current hardware, we just clamp to that value. - // Also we set a threshold of 0, which indicates no limit, to that - // value. - let threshold = - if threshold == 0 { MAX } - else if threshold <= MAX as u64 { threshold as i64 } - else { MAX }; - - ReseedingCore { - inner: rng, - reseeder, - threshold: threshold as i64, - bytes_until_reseed: threshold as i64, - fork_counter: 0, - } - } - - /// Reseed the internal PRNG. - fn reseed(&mut self) -> Result<(), Error> { - R::from_rng(&mut self.reseeder).map(|result| { - self.bytes_until_reseed = self.threshold; - self.inner = result - }) - } - - fn is_forked(&self, global_fork_counter: usize) -> bool { - // In theory, on 32-bit platforms, it is possible for - // `global_fork_counter` to wrap around after ~4e9 forks. - // - // This check will detect a fork in the normal case where - // `fork_counter < global_fork_counter`, and also when the difference - // between both is greater than `isize::MAX` (wrapped around). - // - // It will still fail to detect a fork if there have been more than - // `isize::MAX` forks, without any reseed in between. Seems unlikely - // enough. - (self.fork_counter.wrapping_sub(global_fork_counter) as isize) < 0 - } - - #[inline(never)] - fn reseed_and_generate(&mut self, - results: &mut <Self as BlockRngCore>::Results, - global_fork_counter: usize) - { - if self.is_forked(global_fork_counter) { - info!("Fork detected, reseeding RNG"); - } else { - trace!("Reseeding RNG (periodic reseed)"); - } - - let num_bytes = - results.as_ref().len() * size_of::<<R as BlockRngCore>::Item>(); - - let threshold = if let Err(e) = self.reseed() { - let delay = match e.kind { - ErrorKind::Transient => num_bytes as i64, - kind @ _ if kind.should_retry() => self.threshold >> 8, - _ => self.threshold, - }; - warn!("Reseeding RNG delayed reseeding by {} bytes due to \ - error from source: {}", delay, e); - delay - } else { - self.fork_counter = global_fork_counter; - self.threshold - }; - - self.bytes_until_reseed = threshold - num_bytes as i64; - self.inner.generate(results); - } -} - -impl<R, Rsdr> Clone for ReseedingCore<R, Rsdr> -where R: BlockRngCore + SeedableRng + Clone, - Rsdr: RngCore + Clone -{ - fn clone(&self) -> ReseedingCore<R, Rsdr> { - ReseedingCore { - inner: self.inner.clone(), - reseeder: self.reseeder.clone(), - threshold: self.threshold, - bytes_until_reseed: 0, // reseed clone on first use - fork_counter: self.fork_counter, - } - } -} - -impl<R, Rsdr> CryptoRng for ReseedingCore<R, Rsdr> -where R: BlockRngCore + SeedableRng + CryptoRng, - Rsdr: RngCore + CryptoRng {} - - -#[cfg(all(feature="std", unix, not(target_os="emscripten")))] -mod fork { - extern crate libc; - - use std::sync::atomic::{AtomicUsize, ATOMIC_USIZE_INIT, Ordering}; - use std::sync::atomic::{AtomicBool, ATOMIC_BOOL_INIT}; - - // Fork protection - // - // We implement fork protection on Unix using `pthread_atfork`. - // When the process is forked, we increment `RESEEDING_RNG_FORK_COUNTER`. - // Every `ReseedingRng` stores the last known value of the static in - // `fork_counter`. If the cached `fork_counter` is less than - // `RESEEDING_RNG_FORK_COUNTER`, it is time to reseed this RNG. - // - // If reseeding fails, we don't deal with this by setting a delay, but just - // don't update `fork_counter`, so a reseed is attempted as soon as - // possible. - - static RESEEDING_RNG_FORK_COUNTER: AtomicUsize = ATOMIC_USIZE_INIT; - - pub fn get_fork_counter() -> usize { - RESEEDING_RNG_FORK_COUNTER.load(Ordering::Relaxed) - } - - static FORK_HANDLER_REGISTERED: AtomicBool = ATOMIC_BOOL_INIT; - - extern fn fork_handler() { - // Note: fetch_add is defined to wrap on overflow - // (which is what we want). - RESEEDING_RNG_FORK_COUNTER.fetch_add(1, Ordering::Relaxed); - } - - pub fn register_fork_handler() { - if FORK_HANDLER_REGISTERED.load(Ordering::Relaxed) == false { - unsafe { libc::pthread_atfork(None, None, Some(fork_handler)) }; - FORK_HANDLER_REGISTERED.store(true, Ordering::Relaxed); - } - } -} - -#[cfg(not(all(feature="std", unix, not(target_os="emscripten"))))] -mod fork { - pub fn get_fork_counter() -> usize { 0 } - pub fn register_fork_handler() {} -} - - -#[cfg(test)] -mod test { - use {Rng, SeedableRng}; - use rand_chacha::ChaChaCore; - use rngs::mock::StepRng; - use super::ReseedingRng; - - #[test] - fn test_reseeding() { - let mut zero = StepRng::new(0, 0); - let rng = ChaChaCore::from_rng(&mut zero).unwrap(); - let mut reseeding = ReseedingRng::new(rng, 32*4, zero); - - // Currently we only support for arrays up to length 32. - // TODO: cannot generate seq via Rng::gen because it uses different alg - let mut buf = [0u32; 32]; // Needs to be a multiple of the RNGs result - // size to test exactly. - reseeding.fill(&mut buf); - let seq = buf; - for _ in 0..10 { - reseeding.fill(&mut buf); - assert_eq!(buf, seq); - } - } - - #[test] - fn test_clone_reseeding() { - let mut zero = StepRng::new(0, 0); - let rng = ChaChaCore::from_rng(&mut zero).unwrap(); - let mut rng1 = ReseedingRng::new(rng, 32*4, zero); - - let first: u32 = rng1.gen(); - for _ in 0..10 { let _ = rng1.gen::<u32>(); } - - let mut rng2 = rng1.clone(); - assert_eq!(first, rng2.gen::<u32>()); - } -} diff --git a/rand/src/rngs/entropy.rs b/rand/src/rngs/entropy.rs deleted file mode 100644 index 372b4d7..0000000 --- a/rand/src/rngs/entropy.rs +++ /dev/null @@ -1,249 +0,0 @@ -// Copyright 2018 Developers of the Rand project. -// -// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or -// https://www.apache.org/licenses/LICENSE-2.0> or the MIT license -// <LICENSE-MIT or https://opensource.org/licenses/MIT>, at your -// option. This file may not be copied, modified, or distributed -// except according to those terms. - -//! Entropy generator, or wrapper around external generators - -use rand_core::{RngCore, CryptoRng, Error, ErrorKind, impls}; -#[allow(unused)] -use rngs; - -/// An interface returning random data from external source(s), provided -/// specifically for securely seeding algorithmic generators (PRNGs). -/// -/// Where possible, `EntropyRng` retrieves random data from the operating -/// system's interface for random numbers ([`OsRng`]); if that fails it will -/// fall back to the [`JitterRng`] entropy collector. In the latter case it will -/// still try to use [`OsRng`] on the next usage. -/// -/// If no secure source of entropy is available `EntropyRng` will panic on use; -/// i.e. it should never output predictable data. -/// -/// This is either a little slow ([`OsRng`] requires a system call) or extremely -/// slow ([`JitterRng`] must use significant CPU time to generate sufficient -/// jitter); for better performance it is common to seed a local PRNG from -/// external entropy then primarily use the local PRNG ([`thread_rng`] is -/// provided as a convenient, local, automatically-seeded CSPRNG). -/// -/// # Panics -/// -/// On most systems, like Windows, Linux, macOS and *BSD on common hardware, it -/// is highly unlikely for both [`OsRng`] and [`JitterRng`] to fail. But on -/// combinations like webassembly without Emscripten or stdweb both sources are -/// unavailable. If both sources fail, only [`try_fill_bytes`] is able to -/// report the error, and only the one from `OsRng`. The other [`RngCore`] -/// methods will panic in case of an error. -/// -/// [`OsRng`]: struct.OsRng.html -/// [`JitterRng`]: jitter/struct.JitterRng.html -/// [`thread_rng`]: ../fn.thread_rng.html -/// [`RngCore`]: ../trait.RngCore.html -/// [`try_fill_bytes`]: ../trait.RngCore.html#method.tymethod.try_fill_bytes -#[derive(Debug)] -pub struct EntropyRng { - source: Source, -} - -#[derive(Debug)] -enum Source { - Os(Os), - Custom(Custom), - Jitter(Jitter), - None, -} - -impl EntropyRng { - /// Create a new `EntropyRng`. - /// - /// This method will do no system calls or other initialization routines, - /// those are done on first use. This is done to make `new` infallible, - /// and `try_fill_bytes` the only place to report errors. - pub fn new() -> Self { - EntropyRng { source: Source::None } - } -} - -impl Default for EntropyRng { - fn default() -> Self { - EntropyRng::new() - } -} - -impl RngCore for EntropyRng { - fn next_u32(&mut self) -> u32 { - impls::next_u32_via_fill(self) - } - - fn next_u64(&mut self) -> u64 { - impls::next_u64_via_fill(self) - } - - fn fill_bytes(&mut self, dest: &mut [u8]) { - self.try_fill_bytes(dest).unwrap_or_else(|err| - panic!("all entropy sources failed; first error: {}", err)) - } - - fn try_fill_bytes(&mut self, dest: &mut [u8]) -> Result<(), Error> { - let mut reported_error = None; - - if let Source::Os(ref mut os_rng) = self.source { - match os_rng.fill(dest) { - Ok(()) => return Ok(()), - Err(err) => { - warn!("EntropyRng: OsRng failed \ - [trying other entropy sources]: {}", err); - reported_error = Some(err); - }, - } - } else if Os::is_supported() { - match Os::new_and_fill(dest) { - Ok(os_rng) => { - debug!("EntropyRng: using OsRng"); - self.source = Source::Os(os_rng); - return Ok(()); - }, - Err(err) => { reported_error = reported_error.or(Some(err)) }, - } - } - - if let Source::Custom(ref mut rng) = self.source { - match rng.fill(dest) { - Ok(()) => return Ok(()), - Err(err) => { - warn!("EntropyRng: custom entropy source failed \ - [trying other entropy sources]: {}", err); - reported_error = Some(err); - }, - } - } else if Custom::is_supported() { - match Custom::new_and_fill(dest) { - Ok(custom) => { - debug!("EntropyRng: using custom entropy source"); - self.source = Source::Custom(custom); - return Ok(()); - }, - Err(err) => { reported_error = reported_error.or(Some(err)) }, - } - } - - if let Source::Jitter(ref mut jitter_rng) = self.source { - match jitter_rng.fill(dest) { - Ok(()) => return Ok(()), - Err(err) => { - warn!("EntropyRng: JitterRng failed: {}", err); - reported_error = Some(err); - }, - } - } else if Jitter::is_supported() { - match Jitter::new_and_fill(dest) { - Ok(jitter_rng) => { - debug!("EntropyRng: using JitterRng"); - self.source = Source::Jitter(jitter_rng); - return Ok(()); - }, - Err(err) => { reported_error = reported_error.or(Some(err)) }, - } - } - - if let Some(err) = reported_error { - Err(Error::with_cause(ErrorKind::Unavailable, - "All entropy sources failed", - err)) - } else { - Err(Error::new(ErrorKind::Unavailable, - "No entropy sources available")) - } - } -} - -impl CryptoRng for EntropyRng {} - - - -trait EntropySource { - fn new_and_fill(dest: &mut [u8]) -> Result<Self, Error> - where Self: Sized; - - fn fill(&mut self, dest: &mut [u8]) -> Result<(), Error>; - - fn is_supported() -> bool { true } -} - -#[allow(unused)] -#[derive(Clone, Debug)] -struct NoSource; - -#[allow(unused)] -impl EntropySource for NoSource { - fn new_and_fill(dest: &mut [u8]) -> Result<Self, Error> { - Err(Error::new(ErrorKind::Unavailable, "Source not supported")) - } - - fn fill(&mut self, dest: &mut [u8]) -> Result<(), Error> { - unreachable!() - } - - fn is_supported() -> bool { false } -} - - -#[cfg(feature="rand_os")] -#[derive(Clone, Debug)] -pub struct Os(rngs::OsRng); - -#[cfg(feature="rand_os")] -impl EntropySource for Os { - fn new_and_fill(dest: &mut [u8]) -> Result<Self, Error> { - let mut rng = rngs::OsRng::new()?; - rng.try_fill_bytes(dest)?; - Ok(Os(rng)) - } - - fn fill(&mut self, dest: &mut [u8]) -> Result<(), Error> { - self.0.try_fill_bytes(dest) - } -} - -#[cfg(not(feature="std"))] -type Os = NoSource; - - -type Custom = NoSource; - - -#[cfg(not(target_arch = "wasm32"))] -#[derive(Clone, Debug)] -pub struct Jitter(rngs::JitterRng); - -#[cfg(not(target_arch = "wasm32"))] -impl EntropySource for Jitter { - fn new_and_fill(dest: &mut [u8]) -> Result<Self, Error> { - let mut rng = rngs::JitterRng::new()?; - rng.try_fill_bytes(dest)?; - Ok(Jitter(rng)) - } - - fn fill(&mut self, dest: &mut [u8]) -> Result<(), Error> { - self.0.try_fill_bytes(dest) - } -} - -#[cfg(target_arch = "wasm32")] -type Jitter = NoSource; - - -#[cfg(test)] -mod test { - use super::*; - - #[test] - fn test_entropy() { - let mut rng = EntropyRng::new(); - let n = (rng.next_u32() ^ rng.next_u32()).count_ones(); - assert!(n >= 2); // p(failure) approx 1e-7 - } -} diff --git a/rand/src/rngs/jitter.rs b/rand/src/rngs/jitter.rs deleted file mode 100644 index 3e93477..0000000 --- a/rand/src/rngs/jitter.rs +++ /dev/null @@ -1,885 +0,0 @@ -// Copyright 2018 Developers of the Rand project. -// -// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or -// https://www.apache.org/licenses/LICENSE-2.0> or the MIT license -// <LICENSE-MIT or https://opensource.org/licenses/MIT>, at your -// option. This file may not be copied, modified, or distributed -// except according to those terms. -// -// Based on jitterentropy-library, http://www.chronox.de/jent.html. -// Copyright Stephan Mueller <smueller@chronox.de>, 2014 - 2017. -// -// With permission from Stephan Mueller to relicense the Rust translation under -// the MIT license. - -//! Non-physical true random number generator based on timing jitter. - -// Note: the C implementation of `Jitterentropy` relies on being compiled -// without optimizations. This implementation goes through lengths to make the -// compiler not optimize out code which does influence timing jitter, but is -// technically dead code. - -use rand_core::{RngCore, CryptoRng, Error, ErrorKind, impls}; - -use core::{fmt, mem, ptr}; -#[cfg(all(feature="std", not(target_arch = "wasm32")))] -use std::sync::atomic::{AtomicUsize, ATOMIC_USIZE_INIT, Ordering}; - -const MEMORY_BLOCKS: usize = 64; -const MEMORY_BLOCKSIZE: usize = 32; -const MEMORY_SIZE: usize = MEMORY_BLOCKS * MEMORY_BLOCKSIZE; - -/// A true random number generator based on jitter in the CPU execution time, -/// and jitter in memory access time. -/// -/// This is a true random number generator, as opposed to pseudo-random -/// generators. Random numbers generated by `JitterRng` can be seen as fresh -/// entropy. A consequence is that is orders of magnitude slower than [`OsRng`] -/// and PRNGs (about 10<sup>3</sup>..10<sup>6</sup> slower). -/// -/// There are very few situations where using this RNG is appropriate. Only very -/// few applications require true entropy. A normal PRNG can be statistically -/// indistinguishable, and a cryptographic PRNG should also be as impossible to -/// predict. -/// -/// Use of `JitterRng` is recommended for initializing cryptographic PRNGs when -/// [`OsRng`] is not available. -/// -/// `JitterRng` can be used without the standard library, but not conveniently, -/// you must provide a high-precision timer and carefully have to follow the -/// instructions of [`new_with_timer`]. -/// -/// This implementation is based on -/// [Jitterentropy](http://www.chronox.de/jent.html) version 2.1.0. -/// -/// Note: There is no accurate timer available on Wasm platforms, to help -/// prevent fingerprinting or timing side-channel attacks. Therefore -/// [`JitterRng::new()`] is not available on Wasm. -/// -/// # Quality testing -/// -/// [`JitterRng::new()`] has build-in, but limited, quality testing, however -/// before using `JitterRng` on untested hardware, or after changes that could -/// effect how the code is optimized (such as a new LLVM version), it is -/// recommend to run the much more stringent -/// [NIST SP 800-90B Entropy Estimation Suite]( -/// https://github.com/usnistgov/SP800-90B_EntropyAssessment). -/// -/// Use the following code using [`timer_stats`] to collect the data: -/// -/// ```no_run -/// use rand::rngs::JitterRng; -/// # -/// # use std::error::Error; -/// # use std::fs::File; -/// # use std::io::Write; -/// # -/// # fn try_main() -> Result<(), Box<Error>> { -/// let mut rng = JitterRng::new()?; -/// -/// // 1_000_000 results are required for the -/// // NIST SP 800-90B Entropy Estimation Suite -/// const ROUNDS: usize = 1_000_000; -/// let mut deltas_variable: Vec<u8> = Vec::with_capacity(ROUNDS); -/// let mut deltas_minimal: Vec<u8> = Vec::with_capacity(ROUNDS); -/// -/// for _ in 0..ROUNDS { -/// deltas_variable.push(rng.timer_stats(true) as u8); -/// deltas_minimal.push(rng.timer_stats(false) as u8); -/// } -/// -/// // Write out after the statistics collection loop, to not disturb the -/// // test results. -/// File::create("jitter_rng_var.bin")?.write(&deltas_variable)?; -/// File::create("jitter_rng_min.bin")?.write(&deltas_minimal)?; -/// # -/// # Ok(()) -/// # } -/// # -/// # fn main() { -/// # try_main().unwrap(); -/// # } -/// ``` -/// -/// This will produce two files: `jitter_rng_var.bin` and `jitter_rng_min.bin`. -/// Run the Entropy Estimation Suite in three configurations, as outlined below. -/// Every run has two steps. One step to produce an estimation, another to -/// validate the estimation. -/// -/// 1. Estimate the expected amount of entropy that is at least available with -/// each round of the entropy collector. This number should be greater than -/// the amount estimated with `64 / test_timer()`. -/// ```sh -/// python noniid_main.py -v jitter_rng_var.bin 8 -/// restart.py -v jitter_rng_var.bin 8 <min-entropy> -/// ``` -/// 2. Estimate the expected amount of entropy that is available in the last 4 -/// bits of the timer delta after running noice sources. Note that a value of -/// `3.70` is the minimum estimated entropy for true randomness. -/// ```sh -/// python noniid_main.py -v -u 4 jitter_rng_var.bin 4 -/// restart.py -v -u 4 jitter_rng_var.bin 4 <min-entropy> -/// ``` -/// 3. Estimate the expected amount of entropy that is available to the entropy -/// collector if both noice sources only run their minimal number of times. -/// This measures the absolute worst-case, and gives a lower bound for the -/// available entropy. -/// ```sh -/// python noniid_main.py -v -u 4 jitter_rng_min.bin 4 -/// restart.py -v -u 4 jitter_rng_min.bin 4 <min-entropy> -/// ``` -/// -/// [`OsRng`]: struct.OsRng.html -/// [`JitterRng::new()`]: struct.JitterRng.html#method.new -/// [`new_with_timer`]: struct.JitterRng.html#method.new_with_timer -/// [`timer_stats`]: struct.JitterRng.html#method.timer_stats -pub struct JitterRng { - data: u64, // Actual random number - // Number of rounds to run the entropy collector per 64 bits - rounds: u8, - // Timer used by `measure_jitter` - timer: fn() -> u64, - // Memory for the Memory Access noise source - mem_prev_index: u16, - // Make `next_u32` not waste 32 bits - data_half_used: bool, -} - -// Note: `JitterRng` maintains a small 64-bit entropy pool. With every -// `generate` 64 new bits should be integrated in the pool. If a round of -// `generate` were to collect less than the expected 64 bit, then the returned -// value, and the new state of the entropy pool, would be in some way related to -// the initial state. It is therefore better if the initial state of the entropy -// pool is different on each call to `generate`. This has a few implications: -// - `generate` should be called once before using `JitterRng` to produce the -// first usable value (this is done by default in `new`); -// - We do not zero the entropy pool after generating a result. The reference -// implementation also does not support zeroing, but recommends generating a -// new value without using it if you want to protect a previously generated -// 'secret' value from someone inspecting the memory; -// - Implementing `Clone` seems acceptable, as it would not cause the systematic -// bias a constant might cause. Only instead of one value that could be -// potentially related to the same initial state, there are now two. - -// Entropy collector state. -// These values are not necessary to preserve across runs. -struct EcState { - // Previous time stamp to determine the timer delta - prev_time: u64, - // Deltas used for the stuck test - last_delta: i32, - last_delta2: i32, - // Memory for the Memory Access noise source - mem: [u8; MEMORY_SIZE], -} - -impl EcState { - // Stuck test by checking the: - // - 1st derivation of the jitter measurement (time delta) - // - 2nd derivation of the jitter measurement (delta of time deltas) - // - 3rd derivation of the jitter measurement (delta of delta of time - // deltas) - // - // All values must always be non-zero. - // This test is a heuristic to see whether the last measurement holds - // entropy. - fn stuck(&mut self, current_delta: i32) -> bool { - let delta2 = self.last_delta - current_delta; - let delta3 = delta2 - self.last_delta2; - - self.last_delta = current_delta; - self.last_delta2 = delta2; - - current_delta == 0 || delta2 == 0 || delta3 == 0 - } -} - -// Custom Debug implementation that does not expose the internal state -impl fmt::Debug for JitterRng { - fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { - write!(f, "JitterRng {{}}") - } -} - -impl Clone for JitterRng { - fn clone(&self) -> JitterRng { - JitterRng { - data: self.data, - rounds: self.rounds, - timer: self.timer, - mem_prev_index: self.mem_prev_index, - // The 32 bits that may still be unused from the previous round are - // for the original to use, not for the clone. - data_half_used: false, - } - } -} - -/// An error that can occur when [`JitterRng::test_timer`] fails. -/// -/// [`JitterRng::test_timer`]: struct.JitterRng.html#method.test_timer -#[derive(Debug, Clone, PartialEq, Eq)] -pub enum TimerError { - /// No timer available. - NoTimer, - /// Timer too coarse to use as an entropy source. - CoarseTimer, - /// Timer is not monotonically increasing. - NotMonotonic, - /// Variations of deltas of time too small. - TinyVariantions, - /// Too many stuck results (indicating no added entropy). - TooManyStuck, - #[doc(hidden)] - __Nonexhaustive, -} - -impl TimerError { - fn description(&self) -> &'static str { - match *self { - TimerError::NoTimer => "no timer available", - TimerError::CoarseTimer => "coarse timer", - TimerError::NotMonotonic => "timer not monotonic", - TimerError::TinyVariantions => "time delta variations too small", - TimerError::TooManyStuck => "too many stuck results", - TimerError::__Nonexhaustive => unreachable!(), - } - } -} - -impl fmt::Display for TimerError { - fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { - write!(f, "{}", self.description()) - } -} - -#[cfg(feature="std")] -impl ::std::error::Error for TimerError { - fn description(&self) -> &str { - self.description() - } -} - -impl From<TimerError> for Error { - fn from(err: TimerError) -> Error { - // Timer check is already quite permissive of failures so we don't - // expect false-positive failures, i.e. any error is irrecoverable. - Error::with_cause(ErrorKind::Unavailable, - "timer jitter failed basic quality tests", err) - } -} - -// Initialise to zero; must be positive -#[cfg(all(feature="std", not(target_arch = "wasm32")))] -static JITTER_ROUNDS: AtomicUsize = ATOMIC_USIZE_INIT; - -impl JitterRng { - /// Create a new `JitterRng`. Makes use of `std::time` for a timer, or a - /// platform-specific function with higher accuracy if necessary and - /// available. - /// - /// During initialization CPU execution timing jitter is measured a few - /// hundred times. If this does not pass basic quality tests, an error is - /// returned. The test result is cached to make subsequent calls faster. - #[cfg(all(feature="std", not(target_arch = "wasm32")))] - pub fn new() -> Result<JitterRng, TimerError> { - let mut state = JitterRng::new_with_timer(platform::get_nstime); - let mut rounds = JITTER_ROUNDS.load(Ordering::Relaxed) as u8; - if rounds == 0 { - // No result yet: run test. - // This allows the timer test to run multiple times; we don't care. - rounds = state.test_timer()?; - JITTER_ROUNDS.store(rounds as usize, Ordering::Relaxed); - info!("JitterRng: using {} rounds per u64 output", rounds); - } - state.set_rounds(rounds); - - // Fill `data` with a non-zero value. - state.gen_entropy(); - Ok(state) - } - - /// Create a new `JitterRng`. - /// A custom timer can be supplied, making it possible to use `JitterRng` in - /// `no_std` environments. - /// - /// The timer must have nanosecond precision. - /// - /// This method is more low-level than `new()`. It is the responsibility of - /// the caller to run [`test_timer`] before using any numbers generated with - /// `JitterRng`, and optionally call [`set_rounds`]. Also it is important to - /// consume at least one `u64` before using the first result to initialize - /// the entropy collection pool. - /// - /// # Example - /// - /// ``` - /// # use rand::{Rng, Error}; - /// use rand::rngs::JitterRng; - /// - /// # fn try_inner() -> Result<(), Error> { - /// fn get_nstime() -> u64 { - /// use std::time::{SystemTime, UNIX_EPOCH}; - /// - /// let dur = SystemTime::now().duration_since(UNIX_EPOCH).unwrap(); - /// // The correct way to calculate the current time is - /// // `dur.as_secs() * 1_000_000_000 + dur.subsec_nanos() as u64` - /// // But this is faster, and the difference in terms of entropy is - /// // negligible (log2(10^9) == 29.9). - /// dur.as_secs() << 30 | dur.subsec_nanos() as u64 - /// } - /// - /// let mut rng = JitterRng::new_with_timer(get_nstime); - /// let rounds = rng.test_timer()?; - /// rng.set_rounds(rounds); // optional - /// let _ = rng.gen::<u64>(); - /// - /// // Ready for use - /// let v: u64 = rng.gen(); - /// # Ok(()) - /// # } - /// - /// # let _ = try_inner(); - /// ``` - /// - /// [`test_timer`]: struct.JitterRng.html#method.test_timer - /// [`set_rounds`]: struct.JitterRng.html#method.set_rounds - pub fn new_with_timer(timer: fn() -> u64) -> JitterRng { - JitterRng { - data: 0, - rounds: 64, - timer, - mem_prev_index: 0, - data_half_used: false, - } - } - - /// 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 - /// `rng.set_rounds(rng.test_timer()?);` or cache the value. - /// - /// [`new_with_timer`]: struct.JitterRng.html#method.new_with_timer - pub fn set_rounds(&mut self, rounds: u8) { - assert!(rounds > 0); - self.rounds = rounds; - } - - // Calculate a random loop count used for the next round of an entropy - // collection, based on bits from a fresh value from the timer. - // - // The timer is folded to produce a number that contains at most `n_bits` - // bits. - // - // Note: A constant should be added to the resulting random loop count to - // prevent loops that run 0 times. - #[inline(never)] - fn random_loop_cnt(&mut self, n_bits: u32) -> u32 { - let mut rounds = 0; - - let mut time = (self.timer)(); - // Mix with the current state of the random number balance the random - // loop counter a bit more. - time ^= self.data; - - // We fold the time value as much as possible to ensure that as many - // bits of the time stamp are included as possible. - let folds = (64 + n_bits - 1) / n_bits; - let mask = (1 << n_bits) - 1; - for _ in 0..folds { - rounds ^= time & mask; - time >>= n_bits; - } - - rounds as u32 - } - - // CPU jitter noise source - // Noise source based on the CPU execution time jitter - // - // This function injects the individual bits of the time value into the - // entropy pool using an LFSR. - // - // The code is deliberately inefficient with respect to the bit shifting. - // This function not only acts as folding operation, but this function's - // execution is used to measure the CPU execution time jitter. Any change to - // the loop in this function implies that careful retesting must be done. - #[inline(never)] - fn lfsr_time(&mut self, time: u64, var_rounds: bool) { - fn lfsr(mut data: u64, time: u64) -> u64{ - for i in 1..65 { - let mut tmp = time << (64 - i); - tmp >>= 64 - 1; - - // Fibonacci LSFR with polynomial of - // x^64 + x^61 + x^56 + x^31 + x^28 + x^23 + 1 which is - // primitive according to - // http://poincare.matf.bg.ac.rs/~ezivkovm/publications/primpol1.pdf - // (the shift values are the polynomial values minus one - // due to counting bits from 0 to 63). As the current - // position is always the LSB, the polynomial only needs - // to shift data in from the left without wrap. - data ^= tmp; - data ^= (data >> 63) & 1; - data ^= (data >> 60) & 1; - data ^= (data >> 55) & 1; - data ^= (data >> 30) & 1; - data ^= (data >> 27) & 1; - data ^= (data >> 22) & 1; - data = data.rotate_left(1); - } - data - } - - // Note: in the reference implementation only the last round effects - // `self.data`, all the other results are ignored. To make sure the - // other rounds are not optimised out, we first run all but the last - // round on a throw-away value instead of the real `self.data`. - let mut lfsr_loop_cnt = 0; - if var_rounds { lfsr_loop_cnt = self.random_loop_cnt(4) }; - - let mut throw_away: u64 = 0; - for _ in 0..lfsr_loop_cnt { - throw_away = lfsr(throw_away, time); - } - black_box(throw_away); - - self.data = lfsr(self.data, time); - } - - // Memory Access noise source - // This is a noise source based on variations in memory access times - // - // This function performs memory accesses which will add to the timing - // variations due to an unknown amount of CPU wait states that need to be - // added when accessing memory. The memory size should be larger than the L1 - // caches as outlined in the documentation and the associated testing. - // - // The L1 cache has a very high bandwidth, albeit its access rate is usually - // slower than accessing CPU registers. Therefore, L1 accesses only add - // minimal variations as the CPU has hardly to wait. Starting with L2, - // significant variations are added because L2 typically does not belong to - // the CPU any more and therefore a wider range of CPU wait states is - // necessary for accesses. L3 and real memory accesses have even a wider - // range of wait states. However, to reliably access either L3 or memory, - // the `self.mem` memory must be quite large which is usually not desirable. - #[inline(never)] - fn memaccess(&mut self, mem: &mut [u8; MEMORY_SIZE], var_rounds: bool) { - let mut acc_loop_cnt = 128; - if var_rounds { acc_loop_cnt += self.random_loop_cnt(4) }; - - let mut index = self.mem_prev_index as usize; - for _ in 0..acc_loop_cnt { - // Addition of memblocksize - 1 to index with wrap around logic to - // ensure that every memory location is hit evenly. - // The modulus also allows the compiler to remove the indexing - // bounds check. - index = (index + MEMORY_BLOCKSIZE - 1) % MEMORY_SIZE; - - // memory access: just add 1 to one byte - // memory access implies read from and write to memory location - mem[index] = mem[index].wrapping_add(1); - } - self.mem_prev_index = index as u16; - } - - // This is the heart of the entropy generation: calculate time deltas and - // use the CPU jitter in the time deltas. The jitter is injected into the - // entropy pool. - // - // Ensure that `ec.prev_time` is primed before using the output of this - // function. This can be done by calling this function and not using its - // result. - fn measure_jitter(&mut self, ec: &mut EcState) -> Option<()> { - // Invoke one noise source before time measurement to add variations - self.memaccess(&mut ec.mem, true); - - // Get time stamp and calculate time delta to previous - // invocation to measure the timing variations - let time = (self.timer)(); - // Note: wrapping_sub combined with a cast to `i64` generates a correct - // delta, even in the unlikely case this is a timer that is not strictly - // monotonic. - let current_delta = time.wrapping_sub(ec.prev_time) as i64 as i32; - ec.prev_time = time; - - // Call the next noise source which also injects the data - self.lfsr_time(current_delta as u64, true); - - // Check whether we have a stuck measurement (i.e. does the last - // measurement holds entropy?). - if ec.stuck(current_delta) { return None }; - - // Rotate the data buffer by a prime number (any odd number would - // do) to ensure that every bit position of the input time stamp - // has an even chance of being merged with a bit position in the - // entropy pool. We do not use one here as the adjacent bits in - // successive time deltas may have some form of dependency. The - // chosen value of 7 implies that the low 7 bits of the next - // time delta value is concatenated with the current time delta. - self.data = self.data.rotate_left(7); - - Some(()) - } - - // Shuffle the pool a bit by mixing some value with a bijective function - // (XOR) into the pool. - // - // The function generates a mixer value that depends on the bits set and - // the location of the set bits in the random number generated by the - // entropy source. Therefore, based on the generated random number, this - // mixer value can have 2^64 different values. That mixer value is - // initialized with the first two SHA-1 constants. After obtaining the - // mixer value, it is XORed into the random number. - // - // The mixer value is not assumed to contain any entropy. But due to the - // XOR operation, it can also not destroy any entropy present in the - // entropy pool. - #[inline(never)] - fn stir_pool(&mut self) { - // This constant is derived from the first two 32 bit initialization - // vectors of SHA-1 as defined in FIPS 180-4 section 5.3.1 - // The order does not really matter as we do not rely on the specific - // numbers. We just pick the SHA-1 constants as they have a good mix of - // bit set and unset. - const CONSTANT: u64 = 0x67452301efcdab89; - - // The start value of the mixer variable is derived from the third - // and fourth 32 bit initialization vector of SHA-1 as defined in - // FIPS 180-4 section 5.3.1 - let mut mixer = 0x98badcfe10325476; - - // This is a constant time function to prevent leaking timing - // information about the random number. - // The normal code is: - // ``` - // for i in 0..64 { - // if ((self.data >> i) & 1) == 1 { mixer ^= CONSTANT; } - // } - // ``` - // This is a bit fragile, as LLVM really wants to use branches here, and - // we rely on it to not recognise the opportunity. - for i in 0..64 { - let apply = (self.data >> i) & 1; - let mask = !apply.wrapping_sub(1); - mixer ^= CONSTANT & mask; - mixer = mixer.rotate_left(1); - } - - self.data ^= mixer; - } - - fn gen_entropy(&mut self) -> u64 { - trace!("JitterRng: collecting entropy"); - - // Prime `ec.prev_time`, and run the noice sources to make sure the - // first loop round collects the expected entropy. - let mut ec = EcState { - prev_time: (self.timer)(), - last_delta: 0, - last_delta2: 0, - mem: [0; MEMORY_SIZE], - }; - let _ = self.measure_jitter(&mut ec); - - for _ in 0..self.rounds { - // If a stuck measurement is received, repeat measurement - // Note: we do not guard against an infinite loop, that would mean - // the timer suddenly became broken. - while self.measure_jitter(&mut ec).is_none() {} - } - - // Do a single read from `self.mem` to make sure the Memory Access noise - // source is not optimised out. - black_box(ec.mem[0]); - - self.stir_pool(); - self.data - } - - /// Basic quality tests on the timer, by measuring CPU timing jitter a few - /// hundred times. - /// - /// If succesful, this will return the estimated number of rounds necessary - /// to collect 64 bits of entropy. Otherwise a [`TimerError`] with the cause - /// of the failure will be returned. - /// - /// [`TimerError`]: enum.TimerError.html - pub fn test_timer(&mut self) -> Result<u8, TimerError> { - debug!("JitterRng: testing timer ..."); - // We could add a check for system capabilities such as `clock_getres` - // 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. - - let mut delta_sum = 0; - let mut old_delta = 0; - - let mut time_backwards = 0; - let mut count_mod = 0; - let mut count_stuck = 0; - - let mut ec = EcState { - prev_time: (self.timer)(), - last_delta: 0, - last_delta2: 0, - mem: [0; MEMORY_SIZE], - }; - - // TESTLOOPCOUNT needs some loops to identify edge systems. - // 100 is definitely too little. - const TESTLOOPCOUNT: u64 = 300; - const CLEARCACHE: u64 = 100; - - for i in 0..(CLEARCACHE + TESTLOOPCOUNT) { - // Measure time delta of core entropy collection logic - let time = (self.timer)(); - self.memaccess(&mut ec.mem, true); - self.lfsr_time(time, true); - let time2 = (self.timer)(); - - // Test whether timer works - if time == 0 || time2 == 0 { - return Err(TimerError::NoTimer); - } - let delta = time2.wrapping_sub(time) as i64 as i32; - - // Test whether timer is fine grained enough to provide delta even - // when called shortly after each other -- this implies that we also - // have a high resolution timer - if delta == 0 { - return Err(TimerError::CoarseTimer); - } - - // Up to here we did not modify any variable that will be - // evaluated later, but we already performed some work. Thus we - // already have had an impact on the caches, branch prediction, - // etc. with the goal to clear it to get the worst case - // measurements. - if i < CLEARCACHE { continue; } - - if ec.stuck(delta) { count_stuck += 1; } - - // Test whether we have an increasing timer. - if !(time2 > time) { time_backwards += 1; } - - // Count the number of times the counter increases in steps of 100ns - // or greater. - if (delta % 100) == 0 { count_mod += 1; } - - // Ensure that we have a varying delta timer which is necessary for - // the calculation of entropy -- perform this check only after the - // first loop is executed as we need to prime the old_delta value - delta_sum += (delta - old_delta).abs() as u64; - old_delta = delta; - } - - // Do a single read from `self.mem` to make sure the Memory Access noise - // source is not optimised out. - black_box(ec.mem[0]); - - // We allow the time to run backwards for up to three times. - // This can happen if the clock is being adjusted by NTP operations. - // If such an operation just happens to interfere with our test, it - // should not fail. The value of 3 should cover the NTP case being - // performed during our test run. - if time_backwards > 3 { - return Err(TimerError::NotMonotonic); - } - - // Test that the available amount of entropy per round does not get to - // low. We expect 1 bit of entropy per round as a reasonable minimum - // (although less is possible, it means the collector loop has to run - // much more often). - // `assert!(delta_average >= log2(1))` - // `assert!(delta_sum / TESTLOOPCOUNT >= 1)` - // `assert!(delta_sum >= TESTLOOPCOUNT)` - if delta_sum < TESTLOOPCOUNT { - return Err(TimerError::TinyVariantions); - } - - // Ensure that we have variations in the time stamp below 100 for at - // least 10% of all checks -- on some platforms, the counter increments - // in multiples of 100, but not always - if count_mod > (TESTLOOPCOUNT * 9 / 10) { - return Err(TimerError::CoarseTimer); - } - - // If we have more than 90% stuck results, then this Jitter RNG is - // likely to not work well. - if count_stuck > (TESTLOOPCOUNT * 9 / 10) { - return Err(TimerError::TooManyStuck); - } - - // Estimate the number of `measure_jitter` rounds necessary for 64 bits - // of entropy. - // - // We don't try very hard to come up with a good estimate of the - // available bits of entropy per round here for two reasons: - // 1. Simple estimates of the available bits (like Shannon entropy) are - // too optimistic. - // 2. Unless we want to waste a lot of time during intialization, there - // only a small number of samples are available. - // - // Therefore we use a very simple and conservative estimate: - // `let bits_of_entropy = log2(delta_average) / 2`. - // - // The number of rounds `measure_jitter` should run to collect 64 bits - // of entropy is `64 / bits_of_entropy`. - let delta_average = delta_sum / TESTLOOPCOUNT; - - if delta_average >= 16 { - let log2 = 64 - delta_average.leading_zeros(); - // Do something similar to roundup(64/(log2/2)): - Ok( ((64u32 * 2 + log2 - 1) / log2) as u8) - } else { - // For values < 16 the rounding error becomes too large, use a - // lookup table. - // Values 0 and 1 are invalid, and filtered out by the - // `delta_sum < TESTLOOPCOUNT` test above. - let log2_lookup = [0, 0, 128, 81, 64, 56, 50, 46, - 43, 41, 39, 38, 36, 35, 34, 33]; - Ok(log2_lookup[delta_average as usize]) - } - } - - /// Statistical test: return the timer delta of one normal run of the - /// `JitterRng` entropy collector. - /// - /// Setting `var_rounds` to `true` will execute the memory access and the - /// CPU jitter noice sources a variable amount of times (just like a real - /// `JitterRng` round). - /// - /// Setting `var_rounds` to `false` will execute the noice sources the - /// minimal number of times. This can be used to measure the minimum amount - /// of entropy one round of the entropy collector can collect in the worst - /// case. - /// - /// See [Quality testing](struct.JitterRng.html#quality-testing) on how to - /// use `timer_stats` to test the quality of `JitterRng`. - pub fn timer_stats(&mut self, var_rounds: bool) -> i64 { - let mut mem = [0; MEMORY_SIZE]; - - let time = (self.timer)(); - self.memaccess(&mut mem, var_rounds); - self.lfsr_time(time, var_rounds); - let time2 = (self.timer)(); - time2.wrapping_sub(time) as i64 - } -} - -#[cfg(feature="std")] -mod platform { - #[cfg(not(any(target_os = "macos", target_os = "ios", - target_os = "windows", - target_arch = "wasm32")))] - pub fn get_nstime() -> u64 { - use std::time::{SystemTime, UNIX_EPOCH}; - - let dur = SystemTime::now().duration_since(UNIX_EPOCH).unwrap(); - // The correct way to calculate the current time is - // `dur.as_secs() * 1_000_000_000 + dur.subsec_nanos() as u64` - // But this is faster, and the difference in terms of entropy is - // negligible (log2(10^9) == 29.9). - dur.as_secs() << 30 | dur.subsec_nanos() as u64 - } - - #[cfg(any(target_os = "macos", target_os = "ios"))] - pub 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() } - } - - #[cfg(target_os = "windows")] - pub fn get_nstime() -> u64 { - extern crate winapi; - unsafe { - let mut t = super::mem::zeroed(); - winapi::um::profileapi::QueryPerformanceCounter(&mut t); - *t.QuadPart() as u64 - } - } -} - -// 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 { - unsafe { - let ret = ptr::read_volatile(&dummy); - mem::forget(dummy); - ret - } -} - -impl RngCore for JitterRng { - fn next_u32(&mut self) -> u32 { - // We want to use both parts of the generated entropy - if self.data_half_used { - self.data_half_used = false; - (self.data >> 32) as u32 - } else { - self.data = self.next_u64(); - self.data_half_used = true; - self.data as u32 - } - } - - fn next_u64(&mut self) -> u64 { - self.data_half_used = false; - self.gen_entropy() - } - - fn fill_bytes(&mut self, dest: &mut [u8]) { - // Fill using `next_u32`. This is faster for filling small slices (four - // bytes or less), while the overhead is negligible. - // - // This is done especially for wrappers that implement `next_u32` - // themselves via `fill_bytes`. - impls::fill_bytes_via_next(self, dest) - } - - fn try_fill_bytes(&mut self, dest: &mut [u8]) -> Result<(), Error> { - Ok(self.fill_bytes(dest)) - } -} - -impl CryptoRng for JitterRng {} - -#[cfg(test)] -mod test_jitter_init { - use super::JitterRng; - - #[cfg(all(feature="std", not(target_arch = "wasm32")))] - #[test] - fn test_jitter_init() { - use RngCore; - // Because this is a debug build, measurements here are not representive - // of the final release build. - // Don't fail this test if initializing `JitterRng` fails because of a - // bad timer (the timer from the standard library may not have enough - // accuracy on all platforms). - match JitterRng::new() { - Ok(ref mut rng) => { - // false positives are possible, but extremely unlikely - assert!(rng.next_u32() | rng.next_u32() != 0); - }, - Err(_) => {}, - } - } - - #[test] - fn test_jitter_bad_timer() { - fn bad_timer() -> u64 { 0 } - let mut rng = JitterRng::new_with_timer(bad_timer); - assert!(rng.test_timer().is_err()); - } -} diff --git a/rand/src/rngs/mock.rs b/rand/src/rngs/mock.rs deleted file mode 100644 index 3c9a994..0000000 --- a/rand/src/rngs/mock.rs +++ /dev/null @@ -1,59 +0,0 @@ -// Copyright 2018 Developers of the Rand project. -// -// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or -// https://www.apache.org/licenses/LICENSE-2.0> or the MIT license -// <LICENSE-MIT or https://opensource.org/licenses/MIT>, at your -// option. This file may not be copied, modified, or distributed -// except according to those terms. - -//! Mock random number generator - -use rand_core::{RngCore, Error, impls}; - -/// A simple implementation of `RngCore` for testing purposes. -/// -/// This generates an arithmetic sequence (i.e. adds a constant each step) -/// over a `u64` number, using wrapping arithmetic. If the increment is 0 -/// the generator yields a constant. -/// -/// ``` -/// use rand::Rng; -/// use rand::rngs::mock::StepRng; -/// -/// let mut my_rng = StepRng::new(2, 1); -/// let sample: [u64; 3] = my_rng.gen(); -/// assert_eq!(sample, [2, 3, 4]); -/// ``` -#[derive(Debug, Clone)] -pub struct StepRng { - v: u64, - a: u64, -} - -impl StepRng { - /// Create a `StepRng`, yielding an arithmetic sequence starting with - /// `initial` and incremented by `increment` each time. - pub fn new(initial: u64, increment: u64) -> Self { - StepRng { v: initial, a: increment } - } -} - -impl RngCore for StepRng { - fn next_u32(&mut self) -> u32 { - self.next_u64() as u32 - } - - fn next_u64(&mut self) -> u64 { - let result = self.v; - self.v = self.v.wrapping_add(self.a); - result - } - - fn fill_bytes(&mut self, dest: &mut [u8]) { - impls::fill_bytes_via_next(self, dest); - } - - fn try_fill_bytes(&mut self, dest: &mut [u8]) -> Result<(), Error> { - Ok(self.fill_bytes(dest)) - } -} diff --git a/rand/src/rngs/mod.rs b/rand/src/rngs/mod.rs deleted file mode 100644 index 847fc94..0000000 --- a/rand/src/rngs/mod.rs +++ /dev/null @@ -1,182 +0,0 @@ -// Copyright 2018 Developers of the Rand project. -// -// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or -// https://www.apache.org/licenses/LICENSE-2.0> or the MIT license -// <LICENSE-MIT or https://opensource.org/licenses/MIT>, at your -// option. This file may not be copied, modified, or distributed -// except according to those terms. - -//! Random number generators and adapters for common usage: -//! -//! - [`ThreadRng`], a fast, secure, auto-seeded thread-local generator -//! - [`StdRng`] and [`SmallRng`], algorithms to cover typical usage -//! - [`EntropyRng`], [`OsRng`] and [`JitterRng`] as entropy sources -//! - [`mock::StepRng`] as a simple counter for tests -//! - [`adapter::ReadRng`] to read from a file/stream -//! - [`adapter::ReseedingRng`] to reseed a PRNG on clone / process fork etc. -//! -//! # Background — Random number generators (RNGs) -//! -//! Computers are inherently deterministic, so to get *random* numbers one -//! either has to use a hardware generator or collect bits of *entropy* from -//! various sources (e.g. event timestamps, or jitter). This is a relatively -//! slow and complicated operation. -//! -//! Generally the operating system will collect some entropy, remove bias, and -//! use that to seed its own PRNG; [`OsRng`] provides an interface to this. -//! [`JitterRng`] is an entropy collector included with Rand that measures -//! jitter in the CPU execution time, and jitter in memory access time. -//! [`EntropyRng`] is a wrapper that uses the best entropy source that is -//! available. -//! -//! ## Pseudo-random number generators -//! -//! What is commonly used instead of "true" random number renerators, are -//! *pseudo-random number generators* (PRNGs), deterministic algorithms that -//! produce an infinite stream of pseudo-random numbers from a small random -//! seed. PRNGs are faster, and have better provable properties. The numbers -//! produced can be statistically of very high quality and can be impossible to -//! predict. (They can also have obvious correlations and be trivial to predict; -//! quality varies.) -//! -//! There are two different types of PRNGs: those developed for simulations -//! and statistics, and those developed for use in cryptography; the latter are -//! called Cryptographically Secure PRNGs (CSPRNG or CPRNG). Both types can -//! have good statistical quality but the latter also have to be impossible to -//! predict, even after seeing many previous output values. Rand provides a good -//! default algorithm from each class: -//! -//! - [`SmallRng`] is a PRNG chosen for low memory usage, high performance and -//! good statistical quality. -//! - [`StdRng`] is a CSPRNG chosen for good performance and trust of security -//! (based on reviews, maturity and usage). The current algorithm is HC-128, -//! which is one of the recommendations by ECRYPT's eSTREAM project. -//! -//! The above PRNGs do not cover all use-cases; more algorithms can be found in -//! the [`prng` module], as well as in several other crates. For example, you -//! may wish a CSPRNG with significantly lower memory usage than [`StdRng`] -//! while being less concerned about performance, in which case [`ChaChaRng`] -//! is a good choice. -//! -//! One complexity is that the internal state of a PRNG must change with every -//! generated number. For APIs this generally means a mutable reference to the -//! state of the PRNG has to be passed around. -//! -//! A solution is [`ThreadRng`]. This is a thread-local implementation of -//! [`StdRng`] with automatic seeding on first use. It is the best choice if you -//! "just" want a convenient, secure, fast random number source. Use via the -//! [`thread_rng`] function, which gets a reference to the current thread's -//! local instance. -//! -//! ## Seeding -//! -//! As mentioned above, PRNGs require a random seed in order to produce random -//! output. This is especially important for CSPRNGs, which are still -//! deterministic algorithms, thus can only be secure if their seed value is -//! also secure. To seed a PRNG, use one of: -//! -//! - [`FromEntropy::from_entropy`]; this is the most convenient way to seed -//! with fresh, secure random data. -//! - [`SeedableRng::from_rng`]; this allows seeding from another PRNG or -//! from an entropy source such as [`EntropyRng`]. -//! - [`SeedableRng::from_seed`]; this is mostly useful if you wish to be able -//! to reproduce the output sequence by using a fixed seed. (Don't use -//! [`StdRng`] or [`SmallRng`] in this case since different algorithms may be -//! used by future versions of Rand; use an algorithm from the -//! [`prng` module].) -//! -//! ## Conclusion -//! -//! - [`thread_rng`] is what you often want to use. -//! - If you want more control, flexibility, or better performance, use -//! [`StdRng`], [`SmallRng`] or an algorithm from the [`prng` module]. -//! - Use [`FromEntropy::from_entropy`] to seed new PRNGs. -//! - If you need reproducibility, use [`SeedableRng::from_seed`] combined with -//! a named PRNG. -//! -//! More information and notes on cryptographic security can be found -//! in the [`prng` module]. -//! -//! ## Examples -//! -//! Examples of seeding PRNGs: -//! -//! ``` -//! use rand::prelude::*; -//! # use rand::Error; -//! -//! // StdRng seeded securely by the OS or local entropy collector: -//! let mut rng = StdRng::from_entropy(); -//! # let v: u32 = rng.gen(); -//! -//! // SmallRng seeded from thread_rng: -//! # fn try_inner() -> Result<(), Error> { -//! let mut rng = SmallRng::from_rng(thread_rng())?; -//! # let v: u32 = rng.gen(); -//! # Ok(()) -//! # } -//! # try_inner().unwrap(); -//! -//! // SmallRng seeded by a constant, for deterministic results: -//! let seed = [1,2,3,4, 5,6,7,8, 9,10,11,12, 13,14,15,16]; // byte array -//! let mut rng = SmallRng::from_seed(seed); -//! # let v: u32 = rng.gen(); -//! ``` -//! -//! -//! # Implementing custom RNGs -//! -//! If you want to implement custom RNG, see the [`rand_core`] crate. The RNG -//! will have to implement the [`RngCore`] trait, where the [`Rng`] trait is -//! build on top of. -//! -//! If the RNG needs seeding, also implement the [`SeedableRng`] trait. -//! -//! [`CryptoRng`] is a marker trait cryptographically secure PRNGs can -//! implement. -//! -//! -// This module: -//! [`ThreadRng`]: struct.ThreadRng.html -//! [`StdRng`]: struct.StdRng.html -//! [`SmallRng`]: struct.SmallRng.html -//! [`EntropyRng`]: struct.EntropyRng.html -//! [`OsRng`]: struct.OsRng.html -//! [`JitterRng`]: struct.JitterRng.html -// Other traits and functions: -//! [`rand_core`]: https://crates.io/crates/rand_core -//! [`prng` module]: ../prng/index.html -//! [`CryptoRng`]: ../trait.CryptoRng.html -//! [`FromEntropy`]: ../trait.FromEntropy.html -//! [`FromEntropy::from_entropy`]: ../trait.FromEntropy.html#tymethod.from_entropy -//! [`RngCore`]: ../trait.RngCore.html -//! [`Rng`]: ../trait.Rng.html -//! [`SeedableRng`]: ../trait.SeedableRng.html -//! [`SeedableRng::from_rng`]: ../trait.SeedableRng.html#tymethod.from_rng -//! [`SeedableRng::from_seed`]: ../trait.SeedableRng.html#tymethod.from_seed -//! [`thread_rng`]: ../fn.thread_rng.html -//! [`mock::StepRng`]: mock/struct.StepRng.html -//! [`adapter::ReadRng`]: adapter/struct.ReadRng.html -//! [`adapter::ReseedingRng`]: adapter/struct.ReseedingRng.html -//! [`ChaChaRng`]: ../../rand_chacha/struct.ChaChaRng.html - -pub mod adapter; - -#[cfg(feature="std")] mod entropy; -mod jitter; -pub mod mock; // Public so we don't export `StepRng` directly, making it a bit - // more clear it is intended for testing. -mod small; -mod std; -#[cfg(feature="std")] pub(crate) mod thread; - - -pub use self::jitter::{JitterRng, TimerError}; -#[cfg(feature="std")] pub use self::entropy::EntropyRng; - -pub use self::small::SmallRng; -pub use self::std::StdRng; -#[cfg(feature="std")] pub use self::thread::ThreadRng; - -#[cfg(feature="rand_os")] -pub use rand_os::OsRng; diff --git a/rand/src/rngs/small.rs b/rand/src/rngs/small.rs deleted file mode 100644 index b652c8c..0000000 --- a/rand/src/rngs/small.rs +++ /dev/null @@ -1,105 +0,0 @@ -// Copyright 2018 Developers of the Rand project. -// -// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or -// https://www.apache.org/licenses/LICENSE-2.0> or the MIT license -// <LICENSE-MIT or https://opensource.org/licenses/MIT>, at your -// option. This file may not be copied, modified, or distributed -// except according to those terms. - -//! A small fast RNG - -use {RngCore, SeedableRng, Error}; - -#[cfg(all(all(rustc_1_26, not(target_os = "emscripten")), target_pointer_width = "64"))] -type Rng = ::rand_pcg::Pcg64Mcg; -#[cfg(not(all(all(rustc_1_26, not(target_os = "emscripten")), target_pointer_width = "64")))] -type Rng = ::rand_pcg::Pcg32; - -/// An RNG recommended when small state, cheap initialization and good -/// performance are required. The PRNG algorithm in `SmallRng` is chosen to be -/// efficient on the current platform, **without consideration for cryptography -/// or security**. The size of its state is much smaller than for [`StdRng`]. -/// -/// Reproducibility of output from this generator is however not required, thus -/// future library versions may use a different internal generator with -/// different output. Further, this generator may not be portable and can -/// produce different output depending on the architecture. If you require -/// reproducible output, use a named RNG. Refer to the documentation on the -/// [`prng` module](../prng/index.html). -/// -/// The current algorithm is [`Pcg64Mcg`] on 64-bit platforms with Rust version -/// 1.26 and later, or [`Pcg32`] otherwise. -/// -/// # Examples -/// -/// Initializing `SmallRng` with a random seed can be done using [`FromEntropy`]: -/// -/// ``` -/// # use rand::Rng; -/// use rand::FromEntropy; -/// use rand::rngs::SmallRng; -/// -/// // Create small, cheap to initialize and fast RNG with a random seed. -/// // The randomness is supplied by the operating system. -/// let mut small_rng = SmallRng::from_entropy(); -/// # let v: u32 = small_rng.gen(); -/// ``` -/// -/// When initializing a lot of `SmallRng`'s, using [`thread_rng`] can be more -/// efficient: -/// -/// ``` -/// use std::iter; -/// use rand::{SeedableRng, thread_rng}; -/// use rand::rngs::SmallRng; -/// -/// // Create a big, expensive to initialize and slower, but unpredictable RNG. -/// // This is cached and done only once per thread. -/// let mut thread_rng = thread_rng(); -/// // Create small, cheap to initialize and fast RNGs with random seeds. -/// // One can generally assume this won't fail. -/// let rngs: Vec<SmallRng> = iter::repeat(()) -/// .map(|()| SmallRng::from_rng(&mut thread_rng).unwrap()) -/// .take(10) -/// .collect(); -/// ``` -/// -/// [`FromEntropy`]: ../trait.FromEntropy.html -/// [`StdRng`]: struct.StdRng.html -/// [`thread_rng`]: ../fn.thread_rng.html -/// [`Pcg64Mcg`]: ../../rand_pcg/type.Pcg64Mcg.html -/// [`Pcg32`]: ../../rand_pcg/type.Pcg32.html -#[derive(Clone, Debug)] -pub struct SmallRng(Rng); - -impl RngCore for SmallRng { - #[inline(always)] - fn next_u32(&mut self) -> u32 { - self.0.next_u32() - } - - #[inline(always)] - fn next_u64(&mut self) -> u64 { - self.0.next_u64() - } - - fn fill_bytes(&mut self, dest: &mut [u8]) { - self.0.fill_bytes(dest); - } - - fn try_fill_bytes(&mut self, dest: &mut [u8]) -> Result<(), Error> { - self.0.try_fill_bytes(dest) - } -} - -impl SeedableRng for SmallRng { - type Seed = <Rng as SeedableRng>::Seed; - - fn from_seed(seed: Self::Seed) -> Self { - SmallRng(Rng::from_seed(seed)) - } - - fn from_rng<R: RngCore>(rng: R) -> Result<Self, Error> { - Rng::from_rng(rng).map(SmallRng) - } -} diff --git a/rand/src/rngs/std.rs b/rand/src/rngs/std.rs deleted file mode 100644 index ce1658b..0000000 --- a/rand/src/rngs/std.rs +++ /dev/null @@ -1,81 +0,0 @@ -// Copyright 2018 Developers of the Rand project. -// -// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or -// https://www.apache.org/licenses/LICENSE-2.0> or the MIT license -// <LICENSE-MIT or https://opensource.org/licenses/MIT>, at your -// option. This file may not be copied, modified, or distributed -// except according to those terms. - -//! The standard RNG - -use {RngCore, CryptoRng, Error, SeedableRng}; -use rand_hc::Hc128Rng; - -/// The standard RNG. The PRNG algorithm in `StdRng` is chosen to be efficient -/// on the current platform, to be statistically strong and unpredictable -/// (meaning a cryptographically secure PRNG). -/// -/// The current algorithm used on all platforms is [HC-128]. -/// -/// Reproducibility of output from this generator is however not required, thus -/// future library versions may use a different internal generator with -/// different output. Further, this generator may not be portable and can -/// produce different output depending on the architecture. If you require -/// reproducible output, use a named RNG, for example [`ChaChaRng`]. -/// -/// [HC-128]: ../../rand_hc/struct.Hc128Rng.html -/// [`ChaChaRng`]: ../../rand_chacha/struct.ChaChaRng.html -#[derive(Clone, Debug)] -pub struct StdRng(Hc128Rng); - -impl RngCore for StdRng { - #[inline(always)] - fn next_u32(&mut self) -> u32 { - self.0.next_u32() - } - - #[inline(always)] - fn next_u64(&mut self) -> u64 { - self.0.next_u64() - } - - fn fill_bytes(&mut self, dest: &mut [u8]) { - self.0.fill_bytes(dest); - } - - fn try_fill_bytes(&mut self, dest: &mut [u8]) -> Result<(), Error> { - self.0.try_fill_bytes(dest) - } -} - -impl SeedableRng for StdRng { - type Seed = <Hc128Rng as SeedableRng>::Seed; - - fn from_seed(seed: Self::Seed) -> Self { - StdRng(Hc128Rng::from_seed(seed)) - } - - fn from_rng<R: RngCore>(rng: R) -> Result<Self, Error> { - Hc128Rng::from_rng(rng).map(StdRng) - } -} - -impl CryptoRng for StdRng {} - - -#[cfg(test)] -mod test { - use {RngCore, SeedableRng}; - use rngs::StdRng; - - #[test] - fn test_stdrng_construction() { - let seed = [1,0,0,0, 23,0,0,0, 200,1,0,0, 210,30,0,0, - 0,0,0,0, 0,0,0,0, 0,0,0,0, 0,0,0,0]; - let mut rng1 = StdRng::from_seed(seed); - assert_eq!(rng1.next_u64(), 15759097995037006553); - - let mut rng2 = StdRng::from_rng(rng1).unwrap(); - assert_eq!(rng2.next_u64(), 6766915756997287454); - } -} diff --git a/rand/src/rngs/thread.rs b/rand/src/rngs/thread.rs deleted file mode 100644 index 7977d85..0000000 --- a/rand/src/rngs/thread.rs +++ /dev/null @@ -1,141 +0,0 @@ -// Copyright 2018 Developers of the Rand project. -// -// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or -// https://www.apache.org/licenses/LICENSE-2.0> or the MIT license -// <LICENSE-MIT or https://opensource.org/licenses/MIT>, at your -// option. This file may not be copied, modified, or distributed -// except according to those terms. - -//! Thread-local random number generator - -use std::cell::UnsafeCell; - -use {RngCore, CryptoRng, SeedableRng, Error}; -use rngs::adapter::ReseedingRng; -use rngs::EntropyRng; -use rand_hc::Hc128Core; - -// Rationale for using `UnsafeCell` in `ThreadRng`: -// -// Previously we used a `RefCell`, with an overhead of ~15%. There will only -// ever be one mutable reference to the interior of the `UnsafeCell`, because -// we only have such a reference inside `next_u32`, `next_u64`, etc. Within a -// single thread (which is the definition of `ThreadRng`), there will only ever -// be one of these methods active at a time. -// -// A possible scenario where there could be multiple mutable references is if -// `ThreadRng` is used inside `next_u32` and co. But the implementation is -// completely under our control. We just have to ensure none of them use -// `ThreadRng` internally, which is nonsensical anyway. We should also never run -// `ThreadRng` in destructors of its implementation, which is also nonsensical. -// -// The additional `Rc` is not strictly neccesary, and could be removed. For now -// it ensures `ThreadRng` stays `!Send` and `!Sync`, and implements `Clone`. - - -// Number of generated bytes after which to reseed `TreadRng`. -// -// The time it takes to reseed HC-128 is roughly equivalent to generating 7 KiB. -// We pick a treshold here that is large enough to not reduce the average -// performance too much, but also small enough to not make reseeding something -// that basically never happens. -const THREAD_RNG_RESEED_THRESHOLD: u64 = 32*1024*1024; // 32 MiB - -/// The type returned by [`thread_rng`], essentially just a reference to the -/// PRNG in thread-local memory. -/// -/// `ThreadRng` uses [`ReseedingRng`] wrapping the same PRNG as [`StdRng`], -/// which is reseeded after generating 32 MiB of random data. A single instance -/// is cached per thread and the returned `ThreadRng` is a reference to this -/// instance — hence `ThreadRng` is neither `Send` nor `Sync` but is safe to use -/// within a single thread. This RNG is seeded and reseeded via [`EntropyRng`] -/// as required. -/// -/// Note that the reseeding is done as an extra precaution against entropy -/// leaks and is in theory unnecessary — to predict `ThreadRng`'s output, an -/// attacker would have to either determine most of the RNG's seed or internal -/// state, or crack the algorithm used. -/// -/// Like [`StdRng`], `ThreadRng` is a cryptographically secure PRNG. The current -/// algorithm used is [HC-128], which is an array-based PRNG that trades memory -/// usage for better performance. This makes it similar to ISAAC, the algorithm -/// used in `ThreadRng` before rand 0.5. -/// -/// Cloning this handle just produces a new reference to the same thread-local -/// generator. -/// -/// [`thread_rng`]: ../fn.thread_rng.html -/// [`ReseedingRng`]: adapter/struct.ReseedingRng.html -/// [`StdRng`]: struct.StdRng.html -/// [`EntropyRng`]: struct.EntropyRng.html -/// [HC-128]: ../../rand_hc/struct.Hc128Rng.html -#[derive(Clone, Debug)] -pub struct ThreadRng { - // use of raw pointer implies type is neither Send nor Sync - rng: *mut ReseedingRng<Hc128Core, EntropyRng>, -} - -thread_local!( - static THREAD_RNG_KEY: UnsafeCell<ReseedingRng<Hc128Core, EntropyRng>> = { - let mut entropy_source = EntropyRng::new(); - let r = Hc128Core::from_rng(&mut entropy_source).unwrap_or_else(|err| - panic!("could not initialize thread_rng: {}", err)); - let rng = ReseedingRng::new(r, - THREAD_RNG_RESEED_THRESHOLD, - entropy_source); - UnsafeCell::new(rng) - } -); - -/// Retrieve the lazily-initialized thread-local random number generator, -/// seeded by the system. Intended to be used in method chaining style, -/// e.g. `thread_rng().gen::<i32>()`, or cached locally, e.g. -/// `let mut rng = thread_rng();`. Invoked by the `Default` trait, making -/// `ThreadRng::default()` equivelent. -/// -/// For more information see [`ThreadRng`]. -/// -/// [`ThreadRng`]: rngs/struct.ThreadRng.html -pub fn thread_rng() -> ThreadRng { - ThreadRng { rng: THREAD_RNG_KEY.with(|t| t.get()) } -} - -impl Default for ThreadRng { - fn default() -> ThreadRng { - ::prelude::thread_rng() - } -} - -impl RngCore for ThreadRng { - #[inline(always)] - fn next_u32(&mut self) -> u32 { - unsafe { (*self.rng).next_u32() } - } - - #[inline(always)] - fn next_u64(&mut self) -> u64 { - unsafe { (*self.rng).next_u64() } - } - - fn fill_bytes(&mut self, dest: &mut [u8]) { - unsafe { (*self.rng).fill_bytes(dest) } - } - - fn try_fill_bytes(&mut self, dest: &mut [u8]) -> Result<(), Error> { - unsafe { (*self.rng).try_fill_bytes(dest) } - } -} - -impl CryptoRng for ThreadRng {} - - -#[cfg(test)] -mod test { - #[test] - fn test_thread_rng() { - use Rng; - let mut r = ::thread_rng(); - r.gen::<i32>(); - assert_eq!(r.gen_range(0, 1), 0); - } -} diff --git a/rand/src/seq/index.rs b/rand/src/seq/index.rs deleted file mode 100644 index 3d4df3a..0000000 --- a/rand/src/seq/index.rs +++ /dev/null @@ -1,378 +0,0 @@ -// Copyright 2018 Developers of the Rand project. -// -// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or -// https://www.apache.org/licenses/LICENSE-2.0> or the MIT license -// <LICENSE-MIT or https://opensource.org/licenses/MIT>, at your -// option. This file may not be copied, modified, or distributed -// except according to those terms. - -//! Index sampling - -#[cfg(feature="alloc")] use core::slice; - -#[cfg(feature="std")] use std::vec; -#[cfg(all(feature="alloc", not(feature="std")))] use alloc::vec::{self, Vec}; -// BTreeMap is not as fast in tests, but better than nothing. -#[cfg(feature="std")] use std::collections::{HashSet}; -#[cfg(all(feature="alloc", not(feature="std")))] use alloc::collections::BTreeSet; - -#[cfg(feature="alloc")] use distributions::{Distribution, Uniform}; -use Rng; - -/// A vector of indices. -/// -/// Multiple internal representations are possible. -#[derive(Clone, Debug)] -pub enum IndexVec { - #[doc(hidden)] U32(Vec<u32>), - #[doc(hidden)] USize(Vec<usize>), -} - -impl IndexVec { - /// Returns the number of indices - pub fn len(&self) -> usize { - match self { - &IndexVec::U32(ref v) => v.len(), - &IndexVec::USize(ref v) => v.len(), - } - } - - /// Return the value at the given `index`. - /// - /// (Note: we cannot implement `std::ops::Index` because of lifetime - /// restrictions.) - pub fn index(&self, index: usize) -> usize { - match self { - &IndexVec::U32(ref v) => v[index] as usize, - &IndexVec::USize(ref v) => v[index], - } - } - - /// Return result as a `Vec<usize>`. Conversion may or may not be trivial. - pub fn into_vec(self) -> Vec<usize> { - match self { - IndexVec::U32(v) => v.into_iter().map(|i| i as usize).collect(), - IndexVec::USize(v) => v, - } - } - - /// Iterate over the indices as a sequence of `usize` values - pub fn iter<'a>(&'a self) -> IndexVecIter<'a> { - match self { - &IndexVec::U32(ref v) => IndexVecIter::U32(v.iter()), - &IndexVec::USize(ref v) => IndexVecIter::USize(v.iter()), - } - } - - /// Convert into an iterator over the indices as a sequence of `usize` values - pub fn into_iter(self) -> IndexVecIntoIter { - match self { - IndexVec::U32(v) => IndexVecIntoIter::U32(v.into_iter()), - IndexVec::USize(v) => IndexVecIntoIter::USize(v.into_iter()), - } - } -} - -impl PartialEq for IndexVec { - fn eq(&self, other: &IndexVec) -> bool { - use self::IndexVec::*; - match (self, other) { - (&U32(ref v1), &U32(ref v2)) => v1 == v2, - (&USize(ref v1), &USize(ref v2)) => v1 == v2, - (&U32(ref v1), &USize(ref v2)) => (v1.len() == v2.len()) - && (v1.iter().zip(v2.iter()).all(|(x, y)| *x as usize == *y)), - (&USize(ref v1), &U32(ref v2)) => (v1.len() == v2.len()) - && (v1.iter().zip(v2.iter()).all(|(x, y)| *x == *y as usize)), - } - } -} - -impl From<Vec<u32>> for IndexVec { - fn from(v: Vec<u32>) -> Self { - IndexVec::U32(v) - } -} - -impl From<Vec<usize>> for IndexVec { - fn from(v: Vec<usize>) -> Self { - IndexVec::USize(v) - } -} - -/// Return type of `IndexVec::iter`. -#[derive(Debug)] -pub enum IndexVecIter<'a> { - #[doc(hidden)] U32(slice::Iter<'a, u32>), - #[doc(hidden)] USize(slice::Iter<'a, usize>), -} - -impl<'a> Iterator for IndexVecIter<'a> { - type Item = usize; - fn next(&mut self) -> Option<usize> { - use self::IndexVecIter::*; - match self { - &mut U32(ref mut iter) => iter.next().map(|i| *i as usize), - &mut USize(ref mut iter) => iter.next().cloned(), - } - } - - fn size_hint(&self) -> (usize, Option<usize>) { - match self { - &IndexVecIter::U32(ref v) => v.size_hint(), - &IndexVecIter::USize(ref v) => v.size_hint(), - } - } -} - -impl<'a> ExactSizeIterator for IndexVecIter<'a> {} - -/// Return type of `IndexVec::into_iter`. -#[derive(Clone, Debug)] -pub enum IndexVecIntoIter { - #[doc(hidden)] U32(vec::IntoIter<u32>), - #[doc(hidden)] USize(vec::IntoIter<usize>), -} - -impl Iterator for IndexVecIntoIter { - type Item = usize; - - fn next(&mut self) -> Option<Self::Item> { - use self::IndexVecIntoIter::*; - match self { - &mut U32(ref mut v) => v.next().map(|i| i as usize), - &mut USize(ref mut v) => v.next(), - } - } - - fn size_hint(&self) -> (usize, Option<usize>) { - use self::IndexVecIntoIter::*; - match self { - &U32(ref v) => v.size_hint(), - &USize(ref v) => v.size_hint(), - } - } -} - -impl ExactSizeIterator for IndexVecIntoIter {} - - -/// Randomly sample exactly `amount` distinct indices from `0..length`, and -/// return them in random order (fully shuffled). -/// -/// This method is used internally by the slice sampling methods, but it can -/// sometimes be useful to have the indices themselves so this is provided as -/// an alternative. -/// -/// The implementation used is not specified; we automatically select the -/// fastest available algorithm for the `length` and `amount` parameters -/// (based on detailed profiling on an Intel Haswell CPU). Roughly speaking, -/// complexity is `O(amount)`, except that when `amount` is small, performance -/// is closer to `O(amount^2)`, and when `length` is close to `amount` then -/// `O(length)`. -/// -/// Note that performance is significantly better over `u32` indices than over -/// `u64` indices. Because of this we hide the underlying type behind an -/// abstraction, `IndexVec`. -/// -/// If an allocation-free `no_std` function is required, it is suggested -/// to adapt the internal `sample_floyd` implementation. -/// -/// Panics if `amount > length`. -pub fn sample<R>(rng: &mut R, length: usize, amount: usize) -> IndexVec - where R: Rng + ?Sized, -{ - if amount > length { - panic!("`amount` of samples must be less than or equal to `length`"); - } - if length > (::core::u32::MAX as usize) { - // We never want to use inplace here, but could use floyd's alg - // Lazy version: always use the cache alg. - return sample_rejection(rng, length, amount); - } - let amount = amount as u32; - let length = length as u32; - - // Choice of algorithm here depends on both length and amount. See: - // https://github.com/rust-random/rand/pull/479 - // We do some calculations with f32. Accuracy is not very important. - - if amount < 163 { - const C: [[f32; 2]; 2] = [[1.6, 8.0/45.0], [10.0, 70.0/9.0]]; - let j = if length < 500_000 { 0 } else { 1 }; - let amount_fp = amount as f32; - let m4 = C[0][j] * amount_fp; - // Short-cut: when amount < 12, floyd's is always faster - if amount > 11 && (length as f32) < (C[1][j] + m4) * amount_fp { - sample_inplace(rng, length, amount) - } else { - sample_floyd(rng, length, amount) - } - } else { - const C: [f32; 2] = [270.0, 330.0/9.0]; - let j = if length < 500_000 { 0 } else { 1 }; - if (length as f32) < C[j] * (amount as f32) { - sample_inplace(rng, length, amount) - } else { - // note: could have a specific u32 impl, but I'm lazy and - // generics don't have usable conversions - sample_rejection(rng, length as usize, amount as usize) - } - } -} - -/// Randomly sample exactly `amount` indices from `0..length`, using Floyd's -/// combination algorithm. -/// -/// The output values are fully shuffled. (Overhead is under 50%.) -/// -/// This implementation uses `O(amount)` memory and `O(amount^2)` time. -fn sample_floyd<R>(rng: &mut R, length: u32, amount: u32) -> IndexVec - where R: Rng + ?Sized, -{ - // For small amount we use Floyd's fully-shuffled variant. For larger - // amounts this is slow due to Vec::insert performance, so we shuffle - // afterwards. Benchmarks show little overhead from extra logic. - let floyd_shuffle = amount < 50; - - debug_assert!(amount <= length); - let mut indices = Vec::with_capacity(amount as usize); - for j in length - amount .. length { - let t = rng.gen_range(0, j + 1); - if floyd_shuffle { - if let Some(pos) = indices.iter().position(|&x| x == t) { - indices.insert(pos, j); - continue; - } - } else { - if indices.contains(&t) { - indices.push(j); - continue; - } - } - indices.push(t); - } - if !floyd_shuffle { - // Reimplement SliceRandom::shuffle with smaller indices - for i in (1..amount).rev() { - // invariant: elements with index > i have been locked in place. - indices.swap(i as usize, rng.gen_range(0, i + 1) as usize); - } - } - IndexVec::from(indices) -} - -/// Randomly sample exactly `amount` indices from `0..length`, using an inplace -/// partial Fisher-Yates method. -/// Sample an amount of indices using an inplace partial fisher yates method. -/// -/// This allocates the entire `length` of indices and randomizes only the first `amount`. -/// It then truncates to `amount` and returns. -/// -/// This method is not appropriate for large `length` and potentially uses a lot -/// of memory; because of this we only implement for `u32` index (which improves -/// performance in all cases). -/// -/// Set-up is `O(length)` time and memory and shuffling is `O(amount)` time. -fn sample_inplace<R>(rng: &mut R, length: u32, amount: u32) -> IndexVec - where R: Rng + ?Sized, -{ - debug_assert!(amount <= length); - let mut indices: Vec<u32> = Vec::with_capacity(length as usize); - indices.extend(0..length); - for i in 0..amount { - let j: u32 = rng.gen_range(i, length); - indices.swap(i as usize, j as usize); - } - indices.truncate(amount as usize); - debug_assert_eq!(indices.len(), amount as usize); - IndexVec::from(indices) -} - -/// Randomly sample exactly `amount` indices from `0..length`, using rejection -/// sampling. -/// -/// Since `amount <<< length` there is a low chance of a random sample in -/// `0..length` being a duplicate. We test for duplicates and resample where -/// necessary. The algorithm is `O(amount)` time and memory. -fn sample_rejection<R>(rng: &mut R, length: usize, amount: usize) -> IndexVec - where R: Rng + ?Sized, -{ - debug_assert!(amount < length); - #[cfg(feature="std")] let mut cache = HashSet::with_capacity(amount); - #[cfg(not(feature="std"))] let mut cache = BTreeSet::new(); - let distr = Uniform::new(0, length); - let mut indices = Vec::with_capacity(amount); - for _ in 0..amount { - let mut pos = distr.sample(rng); - while !cache.insert(pos) { - pos = distr.sample(rng); - } - indices.push(pos); - } - - debug_assert_eq!(indices.len(), amount); - IndexVec::from(indices) -} - -#[cfg(test)] -mod test { - use super::*; - - #[test] - fn test_sample_boundaries() { - let mut r = ::test::rng(404); - - assert_eq!(sample_inplace(&mut r, 0, 0).len(), 0); - assert_eq!(sample_inplace(&mut r, 1, 0).len(), 0); - assert_eq!(sample_inplace(&mut r, 1, 1).into_vec(), vec![0]); - - assert_eq!(sample_rejection(&mut r, 1, 0).len(), 0); - - assert_eq!(sample_floyd(&mut r, 0, 0).len(), 0); - assert_eq!(sample_floyd(&mut r, 1, 0).len(), 0); - assert_eq!(sample_floyd(&mut r, 1, 1).into_vec(), vec![0]); - - // These algorithms should be fast with big numbers. Test average. - let sum: usize = sample_rejection(&mut r, 1 << 25, 10) - .into_iter().sum(); - assert!(1 << 25 < sum && sum < (1 << 25) * 25); - - let sum: usize = sample_floyd(&mut r, 1 << 25, 10) - .into_iter().sum(); - assert!(1 << 25 < sum && sum < (1 << 25) * 25); - } - - #[test] - fn test_sample_alg() { - let seed_rng = ::test::rng; - - // We can't test which algorithm is used directly, but Floyd's alg - // should produce different results from the others. (Also, `inplace` - // and `cached` currently use different sizes thus produce different results.) - - // A small length and relatively large amount should use inplace - let (length, amount): (usize, usize) = (100, 50); - let v1 = sample(&mut seed_rng(420), length, amount); - let v2 = sample_inplace(&mut seed_rng(420), length as u32, amount as u32); - assert!(v1.iter().all(|e| e < length)); - assert_eq!(v1, v2); - - // Test Floyd's alg does produce different results - let v3 = sample_floyd(&mut seed_rng(420), length as u32, amount as u32); - assert!(v1 != v3); - - // A large length and small amount should use Floyd - let (length, amount): (usize, usize) = (1<<20, 50); - let v1 = sample(&mut seed_rng(421), length, amount); - let v2 = sample_floyd(&mut seed_rng(421), length as u32, amount as u32); - assert!(v1.iter().all(|e| e < length)); - assert_eq!(v1, v2); - - // A large length and larger amount should use cache - let (length, amount): (usize, usize) = (1<<20, 600); - let v1 = sample(&mut seed_rng(422), length, amount); - let v2 = sample_rejection(&mut seed_rng(422), length, amount); - assert!(v1.iter().all(|e| e < length)); - assert_eq!(v1, v2); - } -} diff --git a/rand/src/seq/mod.rs b/rand/src/seq/mod.rs deleted file mode 100644 index 9959602..0000000 --- a/rand/src/seq/mod.rs +++ /dev/null @@ -1,836 +0,0 @@ -// Copyright 2018 Developers of the Rand project. -// -// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or -// https://www.apache.org/licenses/LICENSE-2.0> or the MIT license -// <LICENSE-MIT or https://opensource.org/licenses/MIT>, at your -// option. This file may not be copied, modified, or distributed -// except according to those terms. - -//! Functions for randomly accessing and sampling sequences. -//! -//! TODO: module doc - - -#[cfg(feature="alloc")] pub mod index; - -#[cfg(feature="alloc")] use core::ops::Index; - -#[cfg(all(feature="alloc", not(feature="std")))] use alloc::vec::Vec; - -use Rng; -#[cfg(feature="alloc")] use distributions::WeightedError; -#[cfg(feature="alloc")] use distributions::uniform::{SampleUniform, SampleBorrow}; - -/// Extension trait on slices, providing random mutation and sampling methods. -/// -/// An implementation is provided for slices. This may also be implementable for -/// other types. -pub trait SliceRandom { - /// The element type. - type Item; - - /// Returns a reference to one random element of the slice, or `None` if the - /// slice is empty. - /// - /// Depending on the implementation, complexity is expected to be `O(1)`. - /// - /// # Example - /// - /// ``` - /// use rand::thread_rng; - /// use rand::seq::SliceRandom; - /// - /// let choices = [1, 2, 4, 8, 16, 32]; - /// let mut rng = thread_rng(); - /// println!("{:?}", choices.choose(&mut rng)); - /// assert_eq!(choices[..0].choose(&mut rng), None); - /// ``` - fn choose<R>(&self, rng: &mut R) -> Option<&Self::Item> - where R: Rng + ?Sized; - - /// Returns a mutable reference to one random element of the slice, or - /// `None` if the slice is empty. - /// - /// Depending on the implementation, complexity is expected to be `O(1)`. - fn choose_mut<R>(&mut self, rng: &mut R) -> Option<&mut Self::Item> - where R: Rng + ?Sized; - - /// Produces an iterator that chooses `amount` elements from the slice at - /// random without repeating any, and returns them in random order. - /// - /// In case this API is not sufficiently flexible, use `index::sample` then - /// apply the indices to the slice. - /// - /// Complexity is expected to be the same as `index::sample`. - /// - /// # Example - /// ``` - /// use rand::seq::SliceRandom; - /// - /// let mut rng = &mut rand::thread_rng(); - /// let sample = "Hello, audience!".as_bytes(); - /// - /// // collect the results into a vector: - /// let v: Vec<u8> = sample.choose_multiple(&mut rng, 3).cloned().collect(); - /// - /// // store in a buffer: - /// let mut buf = [0u8; 5]; - /// for (b, slot) in sample.choose_multiple(&mut rng, buf.len()).zip(buf.iter_mut()) { - /// *slot = *b; - /// } - /// ``` - #[cfg(feature = "alloc")] - fn choose_multiple<R>(&self, rng: &mut R, amount: usize) -> SliceChooseIter<Self, Self::Item> - where R: Rng + ?Sized; - - /// Similar to [`choose`], where the likelihood of each outcome may be - /// specified. The specified function `weight` maps items `x` to a relative - /// likelihood `weight(x)`. The probability of each item being selected is - /// therefore `weight(x) / s`, where `s` is the sum of all `weight(x)`. - /// - /// # Example - /// - /// ``` - /// use rand::prelude::*; - /// - /// let choices = [('a', 2), ('b', 1), ('c', 1)]; - /// let mut rng = thread_rng(); - /// // 50% chance to print 'a', 25% chance to print 'b', 25% chance to print 'c' - /// println!("{:?}", choices.choose_weighted(&mut rng, |item| item.1).unwrap().0); - /// ``` - /// [`choose`]: trait.SliceRandom.html#method.choose - #[cfg(feature = "alloc")] - fn choose_weighted<R, F, B, X>(&self, rng: &mut R, weight: F) -> Result<&Self::Item, WeightedError> - where R: Rng + ?Sized, - F: Fn(&Self::Item) -> B, - B: SampleBorrow<X>, - X: SampleUniform + - for<'a> ::core::ops::AddAssign<&'a X> + - ::core::cmp::PartialOrd<X> + - Clone + - Default; - - /// Similar to [`choose_mut`], where the likelihood of each outcome may be - /// specified. The specified function `weight` maps items `x` to a relative - /// likelihood `weight(x)`. The probability of each item being selected is - /// therefore `weight(x) / s`, where `s` is the sum of all `weight(x)`. - /// - /// See also [`choose_weighted`]. - /// - /// [`choose_mut`]: trait.SliceRandom.html#method.choose_mut - /// [`choose_weighted`]: trait.SliceRandom.html#method.choose_weighted - #[cfg(feature = "alloc")] - fn choose_weighted_mut<R, F, B, X>(&mut self, rng: &mut R, weight: F) -> Result<&mut Self::Item, WeightedError> - where R: Rng + ?Sized, - F: Fn(&Self::Item) -> B, - B: SampleBorrow<X>, - X: SampleUniform + - for<'a> ::core::ops::AddAssign<&'a X> + - ::core::cmp::PartialOrd<X> + - Clone + - Default; - - /// Shuffle a mutable slice in place. - /// - /// Depending on the implementation, complexity is expected to be `O(1)`. - /// - /// # Example - /// - /// ``` - /// use rand::thread_rng; - /// use rand::seq::SliceRandom; - /// - /// let mut rng = thread_rng(); - /// let mut y = [1, 2, 3, 4, 5]; - /// println!("Unshuffled: {:?}", y); - /// y.shuffle(&mut rng); - /// println!("Shuffled: {:?}", y); - /// ``` - fn shuffle<R>(&mut self, rng: &mut R) where R: Rng + ?Sized; - - /// Shuffle a slice in place, but exit early. - /// - /// Returns two mutable slices from the source slice. The first contains - /// `amount` elements randomly permuted. The second has the remaining - /// elements that are not fully shuffled. - /// - /// This is an efficient method to select `amount` elements at random from - /// the slice, provided the slice may be mutated. - /// - /// If you only need to choose elements randomly and `amount > self.len()/2` - /// then you may improve performance by taking - /// `amount = values.len() - amount` and using only the second slice. - /// - /// If `amount` is greater than the number of elements in the slice, this - /// will perform a full shuffle. - /// - /// Complexity is expected to be `O(m)` where `m = amount`. - fn partial_shuffle<R>(&mut self, rng: &mut R, amount: usize) - -> (&mut [Self::Item], &mut [Self::Item]) where R: Rng + ?Sized; -} - -/// Extension trait on iterators, providing random sampling methods. -pub trait IteratorRandom: Iterator + Sized { - /// Choose one element at random from the iterator. If you have a slice, - /// it's significantly faster to call the [`choose`] or [`choose_mut`] - /// functions using the slice instead. - /// - /// Returns `None` if and only if the iterator is empty. - /// - /// Complexity is `O(n)`, where `n` is the length of the iterator. - /// This likely consumes multiple random numbers, but the exact number - /// is unspecified. - /// - /// [`choose`]: trait.SliceRandom.html#method.choose - /// [`choose_mut`]: trait.SliceRandom.html#method.choose_mut - fn choose<R>(mut self, rng: &mut R) -> Option<Self::Item> - where R: Rng + ?Sized - { - let (mut lower, mut upper) = self.size_hint(); - let mut consumed = 0; - let mut result = None; - - if upper == Some(lower) { - return if lower == 0 { None } else { self.nth(rng.gen_range(0, lower)) }; - } - - // Continue until the iterator is exhausted - loop { - if lower > 1 { - let ix = rng.gen_range(0, lower + consumed); - let skip; - if ix < lower { - result = self.nth(ix); - skip = lower - (ix + 1); - } else { - skip = lower; - } - if upper == Some(lower) { - return result; - } - consumed += lower; - if skip > 0 { - self.nth(skip - 1); - } - } else { - let elem = self.next(); - if elem.is_none() { - return result; - } - consumed += 1; - let denom = consumed as f64; // accurate to 2^53 elements - if rng.gen_bool(1.0 / denom) { - result = elem; - } - } - - let hint = self.size_hint(); - lower = hint.0; - upper = hint.1; - } - } - - /// Collects `amount` values at random from the iterator into a supplied - /// buffer. - /// - /// Although the elements are selected randomly, the order of elements in - /// the buffer is neither stable nor fully random. If random ordering is - /// desired, shuffle the result. - /// - /// Returns the number of elements added to the buffer. This equals `amount` - /// unless the iterator contains insufficient elements, in which case this - /// equals the number of elements available. - /// - /// Complexity is `O(n)` where `n` is the length of the iterator. - fn choose_multiple_fill<R>(mut self, rng: &mut R, buf: &mut [Self::Item]) - -> usize where R: Rng + ?Sized - { - let amount = buf.len(); - let mut len = 0; - while len < amount { - if let Some(elem) = self.next() { - buf[len] = elem; - len += 1; - } else { - // Iterator exhausted; stop early - return len; - } - } - - // Continue, since the iterator was not exhausted - for (i, elem) in self.enumerate() { - let k = rng.gen_range(0, i + 1 + amount); - if let Some(slot) = buf.get_mut(k) { - *slot = elem; - } - } - len - } - - /// Collects `amount` values at random from the iterator into a vector. - /// - /// This is equivalent to `choose_multiple_fill` except for the result type. - /// - /// Although the elements are selected randomly, the order of elements in - /// the buffer is neither stable nor fully random. If random ordering is - /// desired, shuffle the result. - /// - /// The length of the returned vector equals `amount` unless the iterator - /// contains insufficient elements, in which case it equals the number of - /// elements available. - /// - /// Complexity is `O(n)` where `n` is the length of the iterator. - #[cfg(feature = "alloc")] - fn choose_multiple<R>(mut self, rng: &mut R, amount: usize) -> Vec<Self::Item> - where R: Rng + ?Sized - { - let mut reservoir = Vec::with_capacity(amount); - reservoir.extend(self.by_ref().take(amount)); - - // Continue unless the iterator was exhausted - // - // note: this prevents iterators that "restart" from causing problems. - // If the iterator stops once, then so do we. - if reservoir.len() == amount { - for (i, elem) in self.enumerate() { - let k = rng.gen_range(0, i + 1 + amount); - if let Some(slot) = reservoir.get_mut(k) { - *slot = elem; - } - } - } else { - // Don't hang onto extra memory. There is a corner case where - // `amount` was much less than `self.len()`. - reservoir.shrink_to_fit(); - } - reservoir - } -} - - -impl<T> SliceRandom for [T] { - type Item = T; - - fn choose<R>(&self, rng: &mut R) -> Option<&Self::Item> - where R: Rng + ?Sized - { - if self.is_empty() { - None - } else { - Some(&self[rng.gen_range(0, self.len())]) - } - } - - fn choose_mut<R>(&mut self, rng: &mut R) -> Option<&mut Self::Item> - where R: Rng + ?Sized - { - if self.is_empty() { - None - } else { - let len = self.len(); - Some(&mut self[rng.gen_range(0, len)]) - } - } - - #[cfg(feature = "alloc")] - fn choose_multiple<R>(&self, rng: &mut R, amount: usize) - -> SliceChooseIter<Self, Self::Item> - where R: Rng + ?Sized - { - let amount = ::core::cmp::min(amount, self.len()); - SliceChooseIter { - slice: self, - _phantom: Default::default(), - indices: index::sample(rng, self.len(), amount).into_iter(), - } - } - - #[cfg(feature = "alloc")] - fn choose_weighted<R, F, B, X>(&self, rng: &mut R, weight: F) -> Result<&Self::Item, WeightedError> - where R: Rng + ?Sized, - F: Fn(&Self::Item) -> B, - B: SampleBorrow<X>, - X: SampleUniform + - for<'a> ::core::ops::AddAssign<&'a X> + - ::core::cmp::PartialOrd<X> + - Clone + - Default { - use distributions::{Distribution, WeightedIndex}; - let distr = WeightedIndex::new(self.iter().map(weight))?; - Ok(&self[distr.sample(rng)]) - } - - #[cfg(feature = "alloc")] - fn choose_weighted_mut<R, F, B, X>(&mut self, rng: &mut R, weight: F) -> Result<&mut Self::Item, WeightedError> - where R: Rng + ?Sized, - F: Fn(&Self::Item) -> B, - B: SampleBorrow<X>, - X: SampleUniform + - for<'a> ::core::ops::AddAssign<&'a X> + - ::core::cmp::PartialOrd<X> + - Clone + - Default { - use distributions::{Distribution, WeightedIndex}; - let distr = WeightedIndex::new(self.iter().map(weight))?; - Ok(&mut self[distr.sample(rng)]) - } - - fn shuffle<R>(&mut self, rng: &mut R) where R: Rng + ?Sized - { - for i in (1..self.len()).rev() { - // invariant: elements with index > i have been locked in place. - self.swap(i, rng.gen_range(0, i + 1)); - } - } - - fn partial_shuffle<R>(&mut self, rng: &mut R, amount: usize) - -> (&mut [Self::Item], &mut [Self::Item]) where R: Rng + ?Sized - { - // This applies Durstenfeld's algorithm for the - // [Fisher–Yates shuffle](https://en.wikipedia.org/wiki/Fisher%E2%80%93Yates_shuffle#The_modern_algorithm) - // for an unbiased permutation, but exits early after choosing `amount` - // elements. - - let len = self.len(); - let end = if amount >= len { 0 } else { len - amount }; - - for i in (end..len).rev() { - // invariant: elements with index > i have been locked in place. - self.swap(i, rng.gen_range(0, i + 1)); - } - let r = self.split_at_mut(end); - (r.1, r.0) - } -} - -impl<I> IteratorRandom for I where I: Iterator + Sized {} - - -/// Iterator over multiple choices, as returned by [`SliceRandom::choose_multiple]( -/// trait.SliceRandom.html#method.choose_multiple). -#[cfg(feature = "alloc")] -#[derive(Debug)] -pub struct SliceChooseIter<'a, S: ?Sized + 'a, T: 'a> { - slice: &'a S, - _phantom: ::core::marker::PhantomData<T>, - indices: index::IndexVecIntoIter, -} - -#[cfg(feature = "alloc")] -impl<'a, S: Index<usize, Output = T> + ?Sized + 'a, T: 'a> Iterator for SliceChooseIter<'a, S, T> { - type Item = &'a T; - - fn next(&mut self) -> Option<Self::Item> { - // TODO: investigate using SliceIndex::get_unchecked when stable - self.indices.next().map(|i| &self.slice[i as usize]) - } - - fn size_hint(&self) -> (usize, Option<usize>) { - (self.indices.len(), Some(self.indices.len())) - } -} - -#[cfg(feature = "alloc")] -impl<'a, S: Index<usize, Output = T> + ?Sized + 'a, T: 'a> ExactSizeIterator - for SliceChooseIter<'a, S, T> -{ - fn len(&self) -> usize { - self.indices.len() - } -} - - -/// Randomly sample `amount` elements from a finite iterator. -/// -/// Deprecated: use [`IteratorRandom::choose_multiple`] instead. -/// -/// [`IteratorRandom::choose_multiple`]: trait.IteratorRandom.html#method.choose_multiple -#[cfg(feature = "alloc")] -#[deprecated(since="0.6.0", note="use IteratorRandom::choose_multiple instead")] -pub fn sample_iter<T, I, R>(rng: &mut R, iterable: I, amount: usize) -> Result<Vec<T>, Vec<T>> - where I: IntoIterator<Item=T>, - R: Rng + ?Sized, -{ - use seq::IteratorRandom; - let iter = iterable.into_iter(); - let result = iter.choose_multiple(rng, amount); - if result.len() == amount { - Ok(result) - } else { - Err(result) - } -} - -/// Randomly sample exactly `amount` values from `slice`. -/// -/// The values are non-repeating and in random order. -/// -/// This implementation uses `O(amount)` time and memory. -/// -/// Panics if `amount > slice.len()` -/// -/// Deprecated: use [`SliceRandom::choose_multiple`] instead. -/// -/// [`SliceRandom::choose_multiple`]: trait.SliceRandom.html#method.choose_multiple -#[cfg(feature = "alloc")] -#[deprecated(since="0.6.0", note="use SliceRandom::choose_multiple instead")] -pub fn sample_slice<R, T>(rng: &mut R, slice: &[T], amount: usize) -> Vec<T> - where R: Rng + ?Sized, - T: Clone -{ - let indices = index::sample(rng, slice.len(), amount).into_iter(); - - let mut out = Vec::with_capacity(amount); - out.extend(indices.map(|i| slice[i].clone())); - out -} - -/// Randomly sample exactly `amount` references from `slice`. -/// -/// The references are non-repeating and in random order. -/// -/// This implementation uses `O(amount)` time and memory. -/// -/// Panics if `amount > slice.len()` -/// -/// Deprecated: use [`SliceRandom::choose_multiple`] instead. -/// -/// [`SliceRandom::choose_multiple`]: trait.SliceRandom.html#method.choose_multiple -#[cfg(feature = "alloc")] -#[deprecated(since="0.6.0", note="use SliceRandom::choose_multiple instead")] -pub fn sample_slice_ref<'a, R, T>(rng: &mut R, slice: &'a [T], amount: usize) -> Vec<&'a T> - where R: Rng + ?Sized -{ - let indices = index::sample(rng, slice.len(), amount).into_iter(); - - let mut out = Vec::with_capacity(amount); - out.extend(indices.map(|i| &slice[i])); - out -} - -#[cfg(test)] -mod test { - use super::*; - #[cfg(feature = "alloc")] use {Rng, SeedableRng}; - #[cfg(feature = "alloc")] use rngs::SmallRng; - #[cfg(all(feature="alloc", not(feature="std")))] - use alloc::vec::Vec; - - #[test] - fn test_slice_choose() { - let mut r = ::test::rng(107); - let chars = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n']; - let mut chosen = [0i32; 14]; - for _ in 0..1000 { - let picked = *chars.choose(&mut r).unwrap(); - chosen[(picked as usize) - ('a' as usize)] += 1; - } - for count in chosen.iter() { - let err = *count - (1000 / (chars.len() as i32)); - assert!(-20 <= err && err <= 20); - } - - chosen.iter_mut().for_each(|x| *x = 0); - for _ in 0..1000 { - *chosen.choose_mut(&mut r).unwrap() += 1; - } - for count in chosen.iter() { - let err = *count - (1000 / (chosen.len() as i32)); - assert!(-20 <= err && err <= 20); - } - - let mut v: [isize; 0] = []; - assert_eq!(v.choose(&mut r), None); - assert_eq!(v.choose_mut(&mut r), None); - } - - #[derive(Clone)] - struct UnhintedIterator<I: Iterator + Clone> { - iter: I, - } - impl<I: Iterator + Clone> Iterator for UnhintedIterator<I> { - type Item = I::Item; - fn next(&mut self) -> Option<Self::Item> { - self.iter.next() - } - } - - #[derive(Clone)] - struct ChunkHintedIterator<I: ExactSizeIterator + Iterator + Clone> { - iter: I, - chunk_remaining: usize, - chunk_size: usize, - hint_total_size: bool, - } - impl<I: ExactSizeIterator + Iterator + Clone> Iterator for ChunkHintedIterator<I> { - type Item = I::Item; - fn next(&mut self) -> Option<Self::Item> { - if self.chunk_remaining == 0 { - self.chunk_remaining = ::core::cmp::min(self.chunk_size, - self.iter.len()); - } - self.chunk_remaining = self.chunk_remaining.saturating_sub(1); - - self.iter.next() - } - fn size_hint(&self) -> (usize, Option<usize>) { - (self.chunk_remaining, - if self.hint_total_size { Some(self.iter.len()) } else { None }) - } - } - - #[derive(Clone)] - struct WindowHintedIterator<I: ExactSizeIterator + Iterator + Clone> { - iter: I, - window_size: usize, - hint_total_size: bool, - } - impl<I: ExactSizeIterator + Iterator + Clone> Iterator for WindowHintedIterator<I> { - type Item = I::Item; - fn next(&mut self) -> Option<Self::Item> { - self.iter.next() - } - fn size_hint(&self) -> (usize, Option<usize>) { - (::core::cmp::min(self.iter.len(), self.window_size), - if self.hint_total_size { Some(self.iter.len()) } else { None }) - } - } - - #[test] - fn test_iterator_choose() { - let r = &mut ::test::rng(109); - fn test_iter<R: Rng + ?Sized, Iter: Iterator<Item=usize> + Clone>(r: &mut R, iter: Iter) { - let mut chosen = [0i32; 9]; - for _ in 0..1000 { - let picked = iter.clone().choose(r).unwrap(); - chosen[picked] += 1; - } - for count in chosen.iter() { - // Samples should follow Binomial(1000, 1/9) - // Octave: binopdf(x, 1000, 1/9) gives the prob of *count == x - // Note: have seen 153, which is unlikely but not impossible. - assert!(72 < *count && *count < 154, "count not close to 1000/9: {}", count); - } - } - - test_iter(r, 0..9); - test_iter(r, [0, 1, 2, 3, 4, 5, 6, 7, 8].iter().cloned()); - #[cfg(feature = "alloc")] - test_iter(r, (0..9).collect::<Vec<_>>().into_iter()); - test_iter(r, UnhintedIterator { iter: 0..9 }); - test_iter(r, ChunkHintedIterator { iter: 0..9, chunk_size: 4, chunk_remaining: 4, hint_total_size: false }); - test_iter(r, ChunkHintedIterator { iter: 0..9, chunk_size: 4, chunk_remaining: 4, hint_total_size: true }); - test_iter(r, WindowHintedIterator { iter: 0..9, window_size: 2, hint_total_size: false }); - test_iter(r, WindowHintedIterator { iter: 0..9, window_size: 2, hint_total_size: true }); - - assert_eq!((0..0).choose(r), None); - assert_eq!(UnhintedIterator{ iter: 0..0 }.choose(r), None); - } - - #[test] - fn test_shuffle() { - let mut r = ::test::rng(108); - let empty: &mut [isize] = &mut []; - empty.shuffle(&mut r); - let mut one = [1]; - one.shuffle(&mut r); - let b: &[_] = &[1]; - assert_eq!(one, b); - - let mut two = [1, 2]; - two.shuffle(&mut r); - assert!(two == [1, 2] || two == [2, 1]); - - fn move_last(slice: &mut [usize], pos: usize) { - // use slice[pos..].rotate_left(1); once we can use that - let last_val = slice[pos]; - for i in pos..slice.len() - 1 { - slice[i] = slice[i + 1]; - } - *slice.last_mut().unwrap() = last_val; - } - let mut counts = [0i32; 24]; - for _ in 0..10000 { - let mut arr: [usize; 4] = [0, 1, 2, 3]; - arr.shuffle(&mut r); - let mut permutation = 0usize; - let mut pos_value = counts.len(); - for i in 0..4 { - pos_value /= 4 - i; - let pos = arr.iter().position(|&x| x == i).unwrap(); - assert!(pos < (4 - i)); - permutation += pos * pos_value; - move_last(&mut arr, pos); - assert_eq!(arr[3], i); - } - for i in 0..4 { - assert_eq!(arr[i], i); - } - counts[permutation] += 1; - } - for count in counts.iter() { - let err = *count - 10000i32 / 24; - assert!(-50 <= err && err <= 50); - } - } - - #[test] - fn test_partial_shuffle() { - let mut r = ::test::rng(118); - - let mut empty: [u32; 0] = []; - let res = empty.partial_shuffle(&mut r, 10); - assert_eq!((res.0.len(), res.1.len()), (0, 0)); - - let mut v = [1, 2, 3, 4, 5]; - let res = v.partial_shuffle(&mut r, 2); - assert_eq!((res.0.len(), res.1.len()), (2, 3)); - assert!(res.0[0] != res.0[1]); - // First elements are only modified if selected, so at least one isn't modified: - assert!(res.1[0] == 1 || res.1[1] == 2 || res.1[2] == 3); - } - - #[test] - #[cfg(feature = "alloc")] - fn test_sample_iter() { - let min_val = 1; - let max_val = 100; - - let mut r = ::test::rng(401); - let vals = (min_val..max_val).collect::<Vec<i32>>(); - let small_sample = vals.iter().choose_multiple(&mut r, 5); - let large_sample = vals.iter().choose_multiple(&mut r, vals.len() + 5); - - assert_eq!(small_sample.len(), 5); - assert_eq!(large_sample.len(), vals.len()); - // no randomization happens when amount >= len - assert_eq!(large_sample, vals.iter().collect::<Vec<_>>()); - - assert!(small_sample.iter().all(|e| { - **e >= min_val && **e <= max_val - })); - } - - #[test] - #[cfg(feature = "alloc")] - #[allow(deprecated)] - fn test_sample_slice_boundaries() { - let empty: &[u8] = &[]; - - let mut r = ::test::rng(402); - - // sample 0 items - assert_eq!(&sample_slice(&mut r, empty, 0)[..], [0u8; 0]); - assert_eq!(&sample_slice(&mut r, &[42, 2, 42], 0)[..], [0u8; 0]); - - // sample 1 item - assert_eq!(&sample_slice(&mut r, &[42], 1)[..], [42]); - let v = sample_slice(&mut r, &[1, 42], 1)[0]; - assert!(v == 1 || v == 42); - - // sample "all" the items - let v = sample_slice(&mut r, &[42, 133], 2); - assert!(&v[..] == [42, 133] || v[..] == [133, 42]); - - // Make sure lucky 777's aren't lucky - let slice = &[42, 777]; - let mut num_42 = 0; - let total = 1000; - for _ in 0..total { - let v = sample_slice(&mut r, slice, 1); - assert_eq!(v.len(), 1); - let v = v[0]; - assert!(v == 42 || v == 777); - if v == 42 { - num_42 += 1; - } - } - let ratio_42 = num_42 as f64 / 1000 as f64; - assert!(0.4 <= ratio_42 || ratio_42 <= 0.6, "{}", ratio_42); - } - - #[test] - #[cfg(feature = "alloc")] - #[allow(deprecated)] - fn test_sample_slice() { - let seeded_rng = SmallRng::from_seed; - - let mut r = ::test::rng(403); - - for n in 1..20 { - let length = 5*n - 4; // 1, 6, ... - let amount = r.gen_range(0, length); - let mut seed = [0u8; 16]; - r.fill(&mut seed); - - // assert the basics work - let regular = index::sample(&mut seeded_rng(seed), length, amount); - assert_eq!(regular.len(), amount); - assert!(regular.iter().all(|e| e < length)); - - // also test that sampling the slice works - let vec: Vec<u32> = (0..(length as u32)).collect(); - let result = sample_slice(&mut seeded_rng(seed), &vec, amount); - assert_eq!(result, regular.iter().map(|i| i as u32).collect::<Vec<_>>()); - - let result = sample_slice_ref(&mut seeded_rng(seed), &vec, amount); - assert!(result.iter().zip(regular.iter()).all(|(i,j)| **i == j as u32)); - } - } - - #[test] - #[cfg(feature = "alloc")] - fn test_weighted() { - let mut r = ::test::rng(406); - const N_REPS: u32 = 3000; - let weights = [1u32, 2, 3, 0, 5, 6, 7, 1, 2, 3, 4, 5, 6, 7]; - let total_weight = weights.iter().sum::<u32>() as f32; - - let verify = |result: [i32; 14]| { - for (i, count) in result.iter().enumerate() { - let exp = (weights[i] * N_REPS) as f32 / total_weight; - let mut err = (*count as f32 - exp).abs(); - if err != 0.0 { - err /= exp; - } - assert!(err <= 0.25); - } - }; - - // choose_weighted - fn get_weight<T>(item: &(u32, T)) -> u32 { - item.0 - } - let mut chosen = [0i32; 14]; - let mut items = [(0u32, 0usize); 14]; // (weight, index) - for (i, item) in items.iter_mut().enumerate() { - *item = (weights[i], i); - } - for _ in 0..N_REPS { - let item = items.choose_weighted(&mut r, get_weight).unwrap(); - chosen[item.1] += 1; - } - verify(chosen); - - // choose_weighted_mut - let mut items = [(0u32, 0i32); 14]; // (weight, count) - for (i, item) in items.iter_mut().enumerate() { - *item = (weights[i], 0); - } - for _ in 0..N_REPS { - items.choose_weighted_mut(&mut r, get_weight).unwrap().1 += 1; - } - for (ch, item) in chosen.iter_mut().zip(items.iter()) { - *ch = item.1; - } - verify(chosen); - - // Check error cases - let empty_slice = &mut [10][0..0]; - assert_eq!(empty_slice.choose_weighted(&mut r, |_| 1), Err(WeightedError::NoItem)); - assert_eq!(empty_slice.choose_weighted_mut(&mut r, |_| 1), Err(WeightedError::NoItem)); - assert_eq!(['x'].choose_weighted_mut(&mut r, |_| 0), Err(WeightedError::AllWeightsZero)); - assert_eq!([0, -1].choose_weighted_mut(&mut r, |x| *x), Err(WeightedError::NegativeWeight)); - assert_eq!([-1, 0].choose_weighted_mut(&mut r, |x| *x), Err(WeightedError::NegativeWeight)); - } -} |