#![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;
extern crate rand_jitter;
#[cfg(feature = "rand_os")]
extern crate rand_os;
extern crate rand_core;
extern crate rand_isaac; extern crate rand_chacha; 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)*) => () }
pub use rand_core::{RngCore, CryptoRng, SeedableRng};
pub use rand_core::{ErrorKind, Error};
#[cfg(feature="std")] pub use rngs::thread::thread_rng;
pub mod distributions;
pub mod prelude;
#[deprecated(since="0.6.0")]
pub mod prng;
pub mod rngs;
pub mod seq;
#[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};
pub trait Rng: RngCore {
#[inline]
fn gen<T>(&mut self) -> T where Standard: Distribution<T> {
Standard.sample(self)
}
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)
}
fn sample<T, D: Distribution<T>>(&mut self, distr: D) -> T {
distr.sample(self)
}
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)
}
fn fill<T: AsByteSliceMut + ?Sized>(&mut self, dest: &mut T) {
self.fill_bytes(dest.as_byte_slice_mut());
dest.to_le();
}
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(())
}
#[inline]
fn gen_bool(&mut self, p: f64) -> bool {
let d = distributions::Bernoulli::new(p);
self.sample(d)
}
#[inline]
fn gen_ratio(&mut self, numerator: u32, denominator: u32) -> bool {
let d = distributions::Bernoulli::from_ratio(numerator, denominator);
self.sample(d)
}
#[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)
}
#[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)
}
#[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 {}
pub trait AsByteSliceMut {
fn as_byte_slice_mut(&mut self) -> &mut [u8];
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 {
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,);
#[cfg(feature="std")]
pub trait FromEntropy: SeedableRng {
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))
}
}
#[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);
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);
for (i, &byte) in v.iter().enumerate() {
if byte == 0 {
panic!("byte {} of {} is zero", i, n)
}
}
}
}
#[test]
fn test_fill() {
let x = 9041086907909331047; let mut rng = StepRng::new(x, 0);
let mut array = [0u64; 2];
rng.fill(&mut array[..]);
assert_eq!(array, [x, x]);
assert_eq!(rng.next_u64(), x);
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() {
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;
}
}
let expected = (NUM * N) / DENOM; assert!(((sum - expected) as i32).abs() < 500);
}
}