#![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://docs.rs/rand/0.5.6")]
#![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="i128_support", feature="nightly"), allow(stable_features))] #![cfg_attr(all(feature="i128_support", feature="nightly"), feature(i128_type, i128))]
#![cfg_attr(feature = "stdweb", recursion_limit="128")]
#[cfg(feature="std")] extern crate std as core;
#[cfg(all(feature = "alloc", not(feature="std")))] extern crate alloc;
#[cfg(test)] #[cfg(feature="serde1")] extern crate bincode;
#[cfg(feature="serde1")] extern crate serde;
#[cfg(feature="serde1")] #[macro_use] extern crate serde_derive;
#[cfg(all(target_arch="wasm32", not(target_os="emscripten"), feature="stdweb"))]
#[macro_use]
extern crate stdweb;
extern crate rand_core;
#[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;
pub mod prng;
pub mod rngs;
#[cfg(feature = "alloc")] pub mod seq;
#[cfg(feature="std")] #[doc(hidden)] pub use rngs::adapter::read;
#[doc(hidden)] pub use rngs::adapter::ReseedingRng;
#[allow(deprecated)]
#[cfg(feature="std")] #[doc(hidden)] pub use rngs::EntropyRng;
#[allow(deprecated)]
#[cfg(all(feature="std",
any(target_os = "linux", target_os = "android",
target_os = "netbsd",
target_os = "dragonfly",
target_os = "haiku",
target_os = "emscripten",
target_os = "solaris",
target_os = "cloudabi",
target_os = "macos", target_os = "ios",
target_os = "freebsd",
target_os = "openbsd", target_os = "bitrig",
target_os = "redox",
target_os = "fuchsia",
windows,
all(target_arch = "wasm32", feature = "stdweb")
)))]
#[doc(hidden)]
pub use rngs::OsRng;
#[doc(hidden)] pub use prng::{ChaChaRng, IsaacRng, Isaac64Rng, XorShiftRng};
#[doc(hidden)] pub use rngs::StdRng;
#[allow(deprecated)]
#[doc(hidden)]
pub mod jitter {
pub use rngs::{JitterRng, TimerError};
}
#[allow(deprecated)]
#[cfg(all(feature="std",
any(target_os = "linux", target_os = "android",
target_os = "netbsd",
target_os = "dragonfly",
target_os = "haiku",
target_os = "emscripten",
target_os = "solaris",
target_os = "cloudabi",
target_os = "macos", target_os = "ios",
target_os = "freebsd",
target_os = "openbsd", target_os = "bitrig",
target_os = "redox",
target_os = "fuchsia",
windows,
all(target_arch = "wasm32", feature = "stdweb")
)))]
#[doc(hidden)]
pub mod os {
pub use rngs::OsRng;
}
#[allow(deprecated)]
#[doc(hidden)]
pub mod chacha {
pub use prng::ChaChaRng;
}
#[doc(hidden)]
pub mod isaac {
pub use prng::{IsaacRng, Isaac64Rng};
}
#[cfg(feature="std")] #[doc(hidden)] pub use rngs::ThreadRng;
use core::{marker, mem, slice};
use distributions::{Distribution, Standard};
use distributions::uniform::{SampleUniform, UniformSampler};
#[deprecated(since="0.5.0", note="replaced by distributions::Standard")]
pub trait Rand : Sized {
fn rand<R: Rng>(rng: &mut R) -> Self;
}
pub trait Rng: RngCore {
#[inline]
fn gen<T>(&mut self) -> T where Standard: Distribution<T> {
Standard.sample(self)
}
fn gen_range<T: PartialOrd + SampleUniform>(&mut self, low: T, high: T) -> T {
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)
}
fn choose<'a, T>(&mut self, values: &'a [T]) -> Option<&'a T> {
if values.is_empty() {
None
} else {
Some(&values[self.gen_range(0, values.len())])
}
}
fn choose_mut<'a, T>(&mut self, values: &'a mut [T]) -> Option<&'a mut T> {
if values.is_empty() {
None
} else {
let len = values.len();
Some(&mut values[self.gen_range(0, len)])
}
}
fn shuffle<T>(&mut self, values: &mut [T]) {
let mut i = values.len();
while i >= 2 {
i -= 1;
values.swap(i, self.gen_range(0, i + 1));
}
}
#[allow(deprecated)]
#[deprecated(since="0.5.0", note="use Rng::sample_iter(&Standard) instead")]
fn gen_iter<T>(&mut self) -> Generator<T, &mut Self> where Standard: Distribution<T> {
Generator { rng: self, _marker: marker::PhantomData }
}
#[deprecated(since="0.5.0", note="use gen_bool instead")]
fn gen_weighted_bool(&mut self, n: u32) -> bool {
n <= 1 || self.gen_range(0, n) == 0
}
#[allow(deprecated)]
#[deprecated(since="0.5.0", note="use sample_iter(&Alphanumeric) instead")]
fn gen_ascii_chars(&mut self) -> AsciiGenerator<&mut Self> {
AsciiGenerator { rng: 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(feature="i128_support")] 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(feature="i128_support")] 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,);
#[derive(Debug)]
#[allow(deprecated)]
#[deprecated(since="0.5.0", note="use Rng::sample_iter instead")]
pub struct Generator<T, R: RngCore> {
rng: R,
_marker: marker::PhantomData<fn() -> T>,
}
#[allow(deprecated)]
impl<T, R: RngCore> Iterator for Generator<T, R> where Standard: Distribution<T> {
type Item = T;
fn next(&mut self) -> Option<T> {
Some(self.rng.gen())
}
}
#[derive(Debug)]
#[allow(deprecated)]
#[deprecated(since="0.5.0", note="use distributions::Alphanumeric instead")]
pub struct AsciiGenerator<R: RngCore> {
rng: R,
}
#[allow(deprecated)]
impl<R: RngCore> Iterator for AsciiGenerator<R> {
type Item = char;
fn next(&mut self) -> Option<char> {
const GEN_ASCII_STR_CHARSET: &[u8] =
b"ABCDEFGHIJKLMNOPQRSTUVWXYZ\
abcdefghijklmnopqrstuvwxyz\
0123456789";
Some(*self.rng.choose(GEN_ASCII_STR_CHARSET).unwrap() as char)
}
}
#[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(EntropyRng::new()).unwrap_or_else(|err|
panic!("FromEntropy::from_entropy() failed: {}", err))
}
}
#[deprecated(since="0.5.0", note="removed in favor of SmallRng")]
#[cfg(feature="std")]
pub fn weak_rng() -> XorShiftRng {
XorShiftRng::from_rng(thread_rng()).unwrap_or_else(|err|
panic!("weak_rng failed: {:?}", err))
}
#[cfg(feature="std")]
#[inline]
pub fn random<T>() -> T where Standard: Distribution<T> {
thread_rng().gen()
}
#[cfg(feature="std")]
#[inline]
#[deprecated(since="0.4.0", note="renamed to seq::sample_iter")]
pub fn sample<T, I, R>(rng: &mut R, iterable: I, amount: usize) -> Vec<T>
where I: IntoIterator<Item=T>,
R: Rng,
{
seq::sample_iter(rng, iterable, amount)
.unwrap_or_else(|e| e)
}
#[cfg(test)]
mod test {
use rngs::mock::StepRng;
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(-3, 42);
assert!(a >= -3 && a < 42);
assert_eq!(r.gen_range(0, 1), 0);
assert_eq!(r.gen_range(-12, -11), -12);
}
for _ in 0..1000 {
let a = r.gen_range(10, 42);
assert!(a >= 10 && a < 42);
assert_eq!(r.gen_range(0, 1), 0);
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]
#[allow(deprecated)]
fn test_gen_weighted_bool() {
let mut r = rng(104);
assert_eq!(r.gen_weighted_bool(0), true);
assert_eq!(r.gen_weighted_bool(1), true);
}
#[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_choose() {
let mut r = rng(107);
assert_eq!(r.choose(&[1, 1, 1]).map(|&x|x), Some(1));
let v: &[isize] = &[];
assert_eq!(r.choose(v), None);
}
#[test]
fn test_shuffle() {
let mut r = rng(108);
let empty: &mut [isize] = &mut [];
r.shuffle(empty);
let mut one = [1];
r.shuffle(&mut one);
let b: &[_] = &[1];
assert_eq!(one, b);
let mut two = [1, 2];
r.shuffle(&mut two);
assert!(two == [1, 2] || two == [2, 1]);
let mut x = [1, 1, 1];
r.shuffle(&mut x);
let b: &[_] = &[1, 1, 1];
assert_eq!(x, b);
}
#[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>();
let mut v = [1, 1, 1];
r.shuffle(&mut v);
let b: &[_] = &[1, 1, 1];
assert_eq!(v, b);
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>();
let mut v = [1, 1, 1];
r.shuffle(&mut v);
let b: &[_] = &[1, 1, 1];
assert_eq!(v, b);
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();
}
}