1 // Copyright 2013 The Rust Project Developers. See the COPYRIGHT
2 // file at the top-level directory of this distribution and at
3 // http://rust-lang.org/COPYRIGHT.
5 // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
6 // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
7 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
8 // option. This file may not be copied, modified, or distributed
9 // except according to those terms.
11 //! Utilities for random number generation
13 //! The key functions are `random()` and `Rng::gen()`. These are polymorphic
14 //! and so can be used to generate any type that implements `Rand`. Type inference
15 //! means that often a simple call to `rand::random()` or `rng.gen()` will
16 //! suffice, but sometimes an annotation is required, e.g. `rand::random::<f64>()`.
18 //! See the `distributions` submodule for sampling random numbers from
19 //! distributions like normal and exponential.
21 //! # Thread-local RNG
23 //! There is built-in support for a RNG associated with each thread stored
24 //! in thread-local storage. This RNG can be accessed via `thread_rng`, or
25 //! used implicitly via `random`. This RNG is normally randomly seeded
26 //! from an operating-system source of randomness, e.g. `/dev/urandom` on
27 //! Unix systems, and will automatically reseed itself from this source
28 //! after generating 32 KiB of random data.
30 //! # Cryptographic security
32 //! An application that requires an entropy source for cryptographic purposes
33 //! must use `OsRng`, which reads randomness from the source that the operating
34 //! system provides (e.g. `/dev/urandom` on Unixes or `CryptGenRandom()` on Windows).
35 //! The other random number generators provided by this module are not suitable
36 //! for such purposes.
38 //! *Note*: many Unix systems provide `/dev/random` as well as `/dev/urandom`.
39 //! This module uses `/dev/urandom` for the following reasons:
41 //! - On Linux, `/dev/random` may block if entropy pool is empty; `/dev/urandom` will not block.
42 //! This does not mean that `/dev/random` provides better output than
43 //! `/dev/urandom`; the kernel internally runs a cryptographically secure pseudorandom
44 //! number generator (CSPRNG) based on entropy pool for random number generation,
45 //! so the "quality" of `/dev/random` is not better than `/dev/urandom` in most cases.
46 //! However, this means that `/dev/urandom` can yield somewhat predictable randomness
47 //! if the entropy pool is very small, such as immediately after first booting.
48 //! Linux 3.17 added the `getrandom(2)` system call which solves the issue: it blocks if entropy
49 //! pool is not initialized yet, but it does not block once initialized.
50 //! `getrandom(2)` was based on `getentropy(2)`, an existing system call in OpenBSD.
51 //! `OsRng` tries to use `getrandom(2)` if available, and use `/dev/urandom` fallback if not.
52 //! If an application does not have `getrandom` and likely to be run soon after first booting,
53 //! or on a system with very few entropy sources, one should consider using `/dev/random` via
55 //! - On some systems (e.g. FreeBSD, OpenBSD and Mac OS X) there is no difference
56 //! between the two sources. (Also note that, on some systems e.g. FreeBSD, both `/dev/random`
57 //! and `/dev/urandom` may block once if the CSPRNG has not seeded yet.)
59 #![unstable(feature = "rand", issue = "0")]
68 #[cfg(target_pointer_width = "32")]
69 use core_rand::IsaacRng as IsaacWordRng;
70 #[cfg(target_pointer_width = "64")]
71 use core_rand::Isaac64Rng as IsaacWordRng;
73 pub use core_rand::{Rand, Rng, SeedableRng};
74 pub use core_rand::{XorShiftRng, IsaacRng, Isaac64Rng};
75 pub use core_rand::reseeding;
79 /// The standard RNG. This is designed to be efficient on the current
81 #[derive(Copy, Clone)]
87 /// Create a randomly seeded instance of `StdRng`.
89 /// This is a very expensive operation as it has to read
90 /// randomness from the operating system and use this in an
91 /// expensive seeding operation. If one is only generating a small
92 /// number of random numbers, or doesn't need the utmost speed for
93 /// generating each number, `thread_rng` and/or `random` may be more
96 /// Reading the randomness from the OS may fail, and any error is
97 /// propagated via the `io::Result` return value.
98 pub fn new() -> io::Result<StdRng> {
99 OsRng::new().map(|mut r| StdRng { rng: r.gen() })
103 impl Rng for StdRng {
105 fn next_u32(&mut self) -> u32 {
110 fn next_u64(&mut self) -> u64 {
115 impl<'a> SeedableRng<&'a [usize]> for StdRng {
116 fn reseed(&mut self, seed: &'a [usize]) {
117 // the internal RNG can just be seeded from the above
119 self.rng.reseed(unsafe {mem::transmute(seed)})
122 fn from_seed(seed: &'a [usize]) -> StdRng {
123 StdRng { rng: SeedableRng::from_seed(unsafe {mem::transmute(seed)}) }
127 /// Controls how the thread-local RNG is reseeded.
128 struct ThreadRngReseeder;
130 impl reseeding::Reseeder<StdRng> for ThreadRngReseeder {
131 fn reseed(&mut self, rng: &mut StdRng) {
132 *rng = match StdRng::new() {
134 Err(e) => panic!("could not reseed thread_rng: {}", e)
138 const THREAD_RNG_RESEED_THRESHOLD: usize = 32_768;
139 type ThreadRngInner = reseeding::ReseedingRng<StdRng, ThreadRngReseeder>;
141 /// The thread-local RNG.
143 pub struct ThreadRng {
144 rng: Rc<RefCell<ThreadRngInner>>,
147 impl fmt::Debug for ThreadRng {
148 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
149 f.pad("ThreadRng { .. }")
153 /// Retrieve the lazily-initialized thread-local random number
154 /// generator, seeded by the system. Intended to be used in method
155 /// chaining style, e.g. `thread_rng().gen::<isize>()`.
157 /// The RNG provided will reseed itself from the operating system
158 /// after generating a certain amount of randomness.
160 /// The internal RNG used is platform and architecture dependent, even
161 /// if the operating system random number generator is rigged to give
162 /// the same sequence always. If absolute consistency is required,
163 /// explicitly select an RNG, e.g. `IsaacRng` or `Isaac64Rng`.
164 pub fn thread_rng() -> ThreadRng {
165 // used to make space in TLS for a random number generator
166 thread_local!(static THREAD_RNG_KEY: Rc<RefCell<ThreadRngInner>> = {
167 let r = match StdRng::new() {
169 Err(e) => panic!("could not initialize thread_rng: {}", e)
171 let rng = reseeding::ReseedingRng::new(r,
172 THREAD_RNG_RESEED_THRESHOLD,
174 Rc::new(RefCell::new(rng))
177 ThreadRng { rng: THREAD_RNG_KEY.with(|t| t.clone()) }
180 impl Rng for ThreadRng {
181 fn next_u32(&mut self) -> u32 {
182 self.rng.borrow_mut().next_u32()
185 fn next_u64(&mut self) -> u64 {
186 self.rng.borrow_mut().next_u64()
190 fn fill_bytes(&mut self, bytes: &mut [u8]) {
191 self.rng.borrow_mut().fill_bytes(bytes)
195 /// A random number generator that retrieves randomness straight from
196 /// the operating system. Platform sources:
198 /// - Unix-like systems (Linux, Android, Mac OSX): read directly from
199 /// `/dev/urandom`, or from `getrandom(2)` system call if available.
200 /// - Windows: calls `CryptGenRandom`, using the default cryptographic
201 /// service provider with the `PROV_RSA_FULL` type.
202 /// - iOS: calls SecRandomCopyBytes as /dev/(u)random is sandboxed.
203 /// - OpenBSD: uses the `getentropy(2)` system call.
205 /// This does not block.
206 pub struct OsRng(sys::rand::OsRng);
209 /// Create a new `OsRng`.
210 pub fn new() -> io::Result<OsRng> {
211 sys::rand::OsRng::new().map(OsRng)
217 fn next_u32(&mut self) -> u32 {
222 fn next_u64(&mut self) -> u64 {
227 fn fill_bytes(&mut self, bytes: &mut [u8]) {
228 self.0.fill_bytes(bytes)
235 use sync::mpsc::channel;
242 let mut r = OsRng::new().unwrap();
247 let mut v = [0; 1000];
248 r.fill_bytes(&mut v);
252 #[cfg_attr(target_os = "emscripten", ignore)]
253 fn test_os_rng_tasks() {
255 let mut txs = vec![];
257 let (tx, rx) = channel();
260 thread::spawn(move|| {
261 // wait until all the threads are ready to go.
264 // deschedule to attempt to interleave things as much
265 // as possible (XXX: is this a good test?)
266 let mut r = OsRng::new().unwrap();
268 let mut v = [0; 1000];
275 r.fill_bytes(&mut v);
281 // start all the threads
283 tx.send(()).unwrap();