mod.rs.html -- source
Description: Source to the Rust file `src/libstd/rand/mod.rs`.
Keywords: rust, rustlang, rust-lang

      1
      2
      3
      4
      5
      6
      7
      8
      9
     10
     11
     12
     13
     14
     15
     16
     17
     18
     19
     20
     21
     22
     23
     24
     25
     26
     27
     28
     29
     30
     31
     32
     33
     34
     35
     36
     37
     38
     39
     40
     41
     42
     43
     44
     45
     46
     47
     48
     49
     50
     51
     52
     53
     54
     55
     56
     57
     58
     59
     60
     61
     62
     63
     64
     65
     66
     67
     68
     69
     70
     71
     72
     73
     74
     75
     76
     77
     78
     79
     80
     81
     82
     83
     84
     85
     86
     87
     88
     89
     90
     91
     92
     93
     94
     95
     96
     97
     98
     99
    100
    101
    102
    103
    104
    105
    106
    107
    108
    109
    110
    111
    112
    113
    114
    115
    116
    117
    118
    119
    120
    121
    122
    123
    124
    125
    126
    127
    128
    129
    130
    131
    132
    133
    134
    135
    136
    137
    138
    139
    140
    141
    142
    143
    144
    145
    146
    147
    148
    149
    150
    151
    152
    153
    154
    155
    156
    157
    158
    159
    160
    161
    162
    163
    164
    165
    166
    167
    168
    169
    170
    171
    172
    173
    174
    175
    176
    177
    178
    179
    180
    181
    182
    183
    184
    185
    186
    187
    188
    189
    190
    191
    192
    193
    194
    195
    196
    197
    198
    199
    200
    201
    202
    203
    204
    205
    206
    207
    208
    209
    210
    211
    212
    213
    214
    215
    216
    217
    218
    219
    220
    221
    222
    223
    224
    225
    226
    227
    228
    229
    230
    231
    232
    233
    234
    235
    236
    237
    238
    239
    240
    241
    242
    243
    244
    245
    246
    247
    248
    249
    250
    251
    252
    253
    254
    255
    256
    257
    258
    259
    260
    261
    262
    263
    264
    265
    266
    267
    268
    269
    270
    271
    272
    273
    274
    275
    276
    277
    278
    279
    280
    281
    282
    283
    284
    285
    286

    // Copyright 2013 The Rust Project Developers. See the COPYRIGHT
    // file at the top-level directory of this distribution and at
    // http://rust-lang.org/COPYRIGHT.
    //
    // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
    // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
    // <LICENSE-MIT or http://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
    //!
    //! The key functions are `random()` and `Rng::gen()`. These are polymorphic
    //! and so can be used to generate any type that implements `Rand`. Type inference
    //! means that often a simple call to `rand::random()` or `rng.gen()` will
    //! suffice, but sometimes an annotation is required, e.g. `rand::random::<f64>()`.
    //!
    //! See the `distributions` submodule for sampling random numbers from
    //! distributions like normal and exponential.
    //!
    //! # Thread-local RNG
    //!
    //! There is built-in support for a RNG associated with each thread stored
    //! in thread-local storage. This RNG can be accessed via `thread_rng`, or
    //! used implicitly via `random`. This RNG is normally randomly seeded
    //! from an operating-system source of randomness, e.g. `/dev/urandom` on
    //! Unix systems, and will automatically reseed itself from this source
    //! after generating 32 KiB of random data.
    //!
    //! # Cryptographic security
    //!
    //! An application that requires an entropy source for cryptographic purposes
    //! must use `OsRng`, which reads randomness from the source that the operating
    //! system provides (e.g. `/dev/urandom` on Unixes or `CryptGenRandom()` on Windows).
    //! The other random number generators provided by this module are not suitable
    //! for such purposes.
    //!
    //! *Note*: many Unix systems provide `/dev/random` as well as `/dev/urandom`.
    //! This module uses `/dev/urandom` for the following reasons:
    //!
    //! -   On Linux, `/dev/random` may block if entropy pool is empty; `/dev/urandom` will not block.
    //!     This does not mean that `/dev/random` provides better output than
    //!     `/dev/urandom`; the kernel internally runs a cryptographically secure pseudorandom
    //!     number generator (CSPRNG) based on entropy pool for random number generation,
    //!     so the "quality" of `/dev/random` is not better than `/dev/urandom` in most cases.
    //!     However, this means that `/dev/urandom` can yield somewhat predictable randomness
    //!     if the entropy pool is very small, such as immediately after first booting.
    //!     Linux 3.17 added the `getrandom(2)` system call which solves the issue: it blocks if entropy
    //!     pool is not initialized yet, but it does not block once initialized.
    //!     `getrandom(2)` was based on `getentropy(2)`, an existing system call in OpenBSD.
    //!     `OsRng` tries to use `getrandom(2)` if available, and use `/dev/urandom` fallback if not.
    //!     If an application does not have `getrandom` and likely to be run soon after first booting,
    //!     or on a system with very few entropy sources, one should consider using `/dev/random` via
    //!     `ReaderRng`.
    //! -   On some systems (e.g. FreeBSD, OpenBSD and macOS) there is no difference
    //!     between the two sources. (Also note that, on some systems e.g. FreeBSD, both `/dev/random`
    //!     and `/dev/urandom` may block once if the CSPRNG has not seeded yet.)

    #![unstable(feature = "rand", issue = "27703")]

    use cell::RefCell;
    use fmt;
    use io;
    use mem;
    use rc::Rc;
    use sys;

    #[cfg(target_pointer_width = "32")]
    use core_rand::IsaacRng as IsaacWordRng;
    #[cfg(target_pointer_width = "64")]
    use core_rand::Isaac64Rng as IsaacWordRng;

    pub use core_rand::{Rand, Rng, SeedableRng};
    pub use core_rand::{XorShiftRng, IsaacRng, Isaac64Rng};
    pub use core_rand::reseeding;

    pub mod reader;

    /// The standard RNG. This is designed to be efficient on the current
    /// platform.
    #[derive(Copy, Clone)]
    pub struct StdRng {
        rng: IsaacWordRng,
    }

    impl StdRng {
        /// Create a randomly seeded instance of `StdRng`.
        ///
        /// This is a very expensive operation as it has to read
        /// randomness from the operating system and use this in an
        /// expensive seeding operation. If one is only generating a small
        /// number of random numbers, or doesn't need the utmost speed for
        /// generating each number, `thread_rng` and/or `random` may be more
        /// appropriate.
        ///
        /// Reading the randomness from the OS may fail, and any error is
        /// propagated via the `io::Result` return value.
        pub fn new() -> io::Result<StdRng> {
            OsRng::new().map(|mut r| StdRng { rng: r.gen() })
        }
    }

    impl Rng for StdRng {
        #[inline]
        fn next_u32(&mut self) -> u32 {
            self.rng.next_u32()
        }

        #[inline]
        fn next_u64(&mut self) -> u64 {
            self.rng.next_u64()
        }
    }

    impl<'a> SeedableRng<&'a [usize]> for StdRng {
        fn reseed(&mut self, seed: &'a [usize]) {
            // the internal RNG can just be seeded from the above
            // randomness.
            self.rng.reseed(unsafe {mem::transmute(seed)})
        }

        fn from_seed(seed: &'a [usize]) -> StdRng {
            StdRng { rng: SeedableRng::from_seed(unsafe {mem::transmute(seed)}) }
        }
    }

    /// Controls how the thread-local RNG is reseeded.
    struct ThreadRngReseeder;

    impl reseeding::Reseeder<StdRng> for ThreadRngReseeder {
        fn reseed(&mut self, rng: &mut StdRng) {
            *rng = match StdRng::new() {
                Ok(r) => r,
                Err(e) => panic!("could not reseed thread_rng: {}", e)
            }
        }
    }
    const THREAD_RNG_RESEED_THRESHOLD: usize = 32_768;
    type ThreadRngInner = reseeding::ReseedingRng<StdRng, ThreadRngReseeder>;

    /// The thread-local RNG.
    #[derive(Clone)]
    pub struct ThreadRng {
        rng: Rc<RefCell<ThreadRngInner>>,
    }

    impl fmt::Debug for ThreadRng {
        fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
            f.pad("ThreadRng { .. }")
        }
    }

    /// 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::<isize>()`.
    ///
    /// The RNG provided will reseed itself from the operating system
    /// after generating a certain amount of randomness.
    ///
    /// The internal RNG used is platform and architecture dependent, even
    /// if the operating system random number generator is rigged to give
    /// the same sequence always. If absolute consistency is required,
    /// explicitly select an RNG, e.g. `IsaacRng` or `Isaac64Rng`.
    pub fn thread_rng() -> ThreadRng {
        // used to make space in TLS for a random number generator
        thread_local!(static THREAD_RNG_KEY: Rc<RefCell<ThreadRngInner>> = {
            let r = match StdRng::new() {
                Ok(r) => r,
                Err(e) => panic!("could not initialize thread_rng: {}", e)
            };
            let rng = reseeding::ReseedingRng::new(r,
                                                   THREAD_RNG_RESEED_THRESHOLD,
                                                   ThreadRngReseeder);
            Rc::new(RefCell::new(rng))
        });

        ThreadRng { rng: THREAD_RNG_KEY.with(|t| t.clone()) }
    }

    impl Rng for ThreadRng {
        fn next_u32(&mut self) -> u32 {
            self.rng.borrow_mut().next_u32()
        }

        fn next_u64(&mut self) -> u64 {
            self.rng.borrow_mut().next_u64()
        }

        #[inline]
        fn fill_bytes(&mut self, bytes: &mut [u8]) {
            self.rng.borrow_mut().fill_bytes(bytes)
        }
    }

    /// A random number generator that retrieves randomness straight from
    /// the operating system. Platform sources:
    ///
    /// - Unix-like systems (Linux, Android, macOS): read directly from
    ///   `/dev/urandom`, or from `getrandom(2)` system call if available.
    /// - Windows: calls `CryptGenRandom`, using the default cryptographic
    ///   service provider with the `PROV_RSA_FULL` type.
    /// - iOS: calls SecRandomCopyBytes as /dev/(u)random is sandboxed.
    /// - OpenBSD: uses the `getentropy(2)` system call.
    ///
    /// This does not block.
    pub struct OsRng(sys::rand::OsRng);

    impl OsRng {
        /// Create a new `OsRng`.
        pub fn new() -> io::Result<OsRng> {
            sys::rand::OsRng::new().map(OsRng)
        }
    }

    impl Rng for OsRng {
        #[inline]
        fn next_u32(&mut self) -> u32 {
            self.0.next_u32()
        }

        #[inline]
        fn next_u64(&mut self) -> u64 {
            self.0.next_u64()
        }

        #[inline]
        fn fill_bytes(&mut self, bytes: &mut [u8]) {
            self.0.fill_bytes(bytes)
        }
    }

    #[cfg(test)]
    mod tests {
        use sync::mpsc::channel;
        use rand::Rng;
        use super::OsRng;
        use thread;

        #[test]
        fn test_os_rng() {
            let mut r = OsRng::new().unwrap();

            r.next_u32();
            r.next_u64();

            let mut v = [0; 1000];
            r.fill_bytes(&mut v);
        }

        #[test]
        #[cfg_attr(target_os = "emscripten", ignore)]
        fn test_os_rng_tasks() {

            let mut txs = vec![];
            for _ in 0..20 {
                let (tx, rx) = channel();
                txs.push(tx);

                thread::spawn(move|| {
                    // wait until all the threads are ready to go.
                    rx.recv().unwrap();

                    // deschedule to attempt to interleave things as much
                    // as possible (XXX: is this a good test?)
                    let mut r = OsRng::new().unwrap();
                    thread::yield_now();
                    let mut v = [0; 1000];

                    for _ in 0..100 {
                        r.next_u32();
                        thread::yield_now();
                        r.next_u64();
                        thread::yield_now();
                        r.fill_bytes(&mut v);
                        thread::yield_now();
                    }
                });
            }

            // start all the threads
            for tx in &txs {
                tx.send(()).unwrap();
            }
        }
    }

# Help

## Keyboard Shortcuts

?
  Show this help dialog
S
  Focus the search field
⇤
  Move up in search results
⇥
  Move down in search results
⏎
  Go to active search result
+
  Collapse/expand all sections

## Search Tricks

Prefix searches with a type followed by a colon (e.g. `fn:`) to restrict the search to a given type.

Accepted types are: `fn`, `mod`, `struct`, `enum`, `trait`, `type`, `macro`, and `const`.

Search functions by type signature (e.g. `vec -> usize` or `* -> vec`)