]> git.lizzy.rs Git - rust.git/blob - src/libstd/rand/mod.rs
add inline attributes to stage 0 methods
[rust.git] / src / libstd / rand / mod.rs
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.
4 //
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.
10
11 //! Utilities for random number generation
12 //!
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>()`.
17 //!
18 //! See the `distributions` submodule for sampling random numbers from
19 //! distributions like normal and exponential.
20 //!
21 //! # Thread-local RNG
22 //!
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.
29 //!
30 //! # Cryptographic security
31 //!
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.
37 //!
38 //! *Note*: many Unix systems provide `/dev/random` as well as `/dev/urandom`.
39 //! This module uses `/dev/urandom` for the following reasons:
40 //!
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
54 //!     `ReaderRng`.
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.)
58
59 #![unstable(feature = "rand", issue = "0")]
60
61 use cell::RefCell;
62 use fmt;
63 use io;
64 use mem;
65 use rc::Rc;
66 use sys;
67
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;
72
73 pub use core_rand::{Rand, Rng, SeedableRng};
74 pub use core_rand::{XorShiftRng, IsaacRng, Isaac64Rng};
75 pub use core_rand::reseeding;
76
77 pub mod reader;
78
79 /// The standard RNG. This is designed to be efficient on the current
80 /// platform.
81 #[derive(Copy, Clone)]
82 pub struct StdRng {
83     rng: IsaacWordRng,
84 }
85
86 impl StdRng {
87     /// Create a randomly seeded instance of `StdRng`.
88     ///
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
94     /// appropriate.
95     ///
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() })
100     }
101 }
102
103 impl Rng for StdRng {
104     #[inline]
105     fn next_u32(&mut self) -> u32 {
106         self.rng.next_u32()
107     }
108
109     #[inline]
110     fn next_u64(&mut self) -> u64 {
111         self.rng.next_u64()
112     }
113 }
114
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
118         // randomness.
119         self.rng.reseed(unsafe {mem::transmute(seed)})
120     }
121
122     fn from_seed(seed: &'a [usize]) -> StdRng {
123         StdRng { rng: SeedableRng::from_seed(unsafe {mem::transmute(seed)}) }
124     }
125 }
126
127 /// Controls how the thread-local RNG is reseeded.
128 struct ThreadRngReseeder;
129
130 impl reseeding::Reseeder<StdRng> for ThreadRngReseeder {
131     fn reseed(&mut self, rng: &mut StdRng) {
132         *rng = match StdRng::new() {
133             Ok(r) => r,
134             Err(e) => panic!("could not reseed thread_rng: {}", e)
135         }
136     }
137 }
138 const THREAD_RNG_RESEED_THRESHOLD: usize = 32_768;
139 type ThreadRngInner = reseeding::ReseedingRng<StdRng, ThreadRngReseeder>;
140
141 /// The thread-local RNG.
142 #[derive(Clone)]
143 pub struct ThreadRng {
144     rng: Rc<RefCell<ThreadRngInner>>,
145 }
146
147 impl fmt::Debug for ThreadRng {
148     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
149         f.pad("ThreadRng { .. }")
150     }
151 }
152
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>()`.
156 ///
157 /// The RNG provided will reseed itself from the operating system
158 /// after generating a certain amount of randomness.
159 ///
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() {
168             Ok(r) => r,
169             Err(e) => panic!("could not initialize thread_rng: {}", e)
170         };
171         let rng = reseeding::ReseedingRng::new(r,
172                                                THREAD_RNG_RESEED_THRESHOLD,
173                                                ThreadRngReseeder);
174         Rc::new(RefCell::new(rng))
175     });
176
177     ThreadRng { rng: THREAD_RNG_KEY.with(|t| t.clone()) }
178 }
179
180 impl Rng for ThreadRng {
181     fn next_u32(&mut self) -> u32 {
182         self.rng.borrow_mut().next_u32()
183     }
184
185     fn next_u64(&mut self) -> u64 {
186         self.rng.borrow_mut().next_u64()
187     }
188
189     #[inline]
190     fn fill_bytes(&mut self, bytes: &mut [u8]) {
191         self.rng.borrow_mut().fill_bytes(bytes)
192     }
193 }
194
195 /// A random number generator that retrieves randomness straight from
196 /// the operating system. Platform sources:
197 ///
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.
204 ///
205 /// This does not block.
206 pub struct OsRng(sys::rand::OsRng);
207
208 impl OsRng {
209     /// Create a new `OsRng`.
210     pub fn new() -> io::Result<OsRng> {
211         sys::rand::OsRng::new().map(OsRng)
212     }
213 }
214
215 impl Rng for OsRng {
216     #[inline]
217     fn next_u32(&mut self) -> u32 {
218         self.0.next_u32()
219     }
220
221     #[inline]
222     fn next_u64(&mut self) -> u64 {
223         self.0.next_u64()
224     }
225
226     #[inline]
227     fn fill_bytes(&mut self, bytes: &mut [u8]) {
228         self.0.fill_bytes(bytes)
229     }
230 }
231
232
233 #[cfg(test)]
234 mod tests {
235     use sync::mpsc::channel;
236     use rand::Rng;
237     use super::OsRng;
238     use thread;
239
240     #[test]
241     fn test_os_rng() {
242         let mut r = OsRng::new().unwrap();
243
244         r.next_u32();
245         r.next_u64();
246
247         let mut v = [0; 1000];
248         r.fill_bytes(&mut v);
249     }
250
251     #[test]
252     #[cfg_attr(target_os = "emscripten", ignore)]
253     fn test_os_rng_tasks() {
254
255         let mut txs = vec![];
256         for _ in 0..20 {
257             let (tx, rx) = channel();
258             txs.push(tx);
259
260             thread::spawn(move|| {
261                 // wait until all the threads are ready to go.
262                 rx.recv().unwrap();
263
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();
267                 thread::yield_now();
268                 let mut v = [0; 1000];
269
270                 for _ in 0..100 {
271                     r.next_u32();
272                     thread::yield_now();
273                     r.next_u64();
274                     thread::yield_now();
275                     r.fill_bytes(&mut v);
276                     thread::yield_now();
277                 }
278             });
279         }
280
281         // start all the threads
282         for tx in &txs {
283             tx.send(()).unwrap();
284         }
285     }
286 }