      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
    287
    288

    // Copyright 2013-2015 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.

    pub use self::imp::OsRng;

    #[cfg(all(unix, not(target_os = "ios"), not(target_os = "openbsd")))]
    mod imp {
        use self::OsRngInner::*;

        use fs::File;
        use io;
        use libc;
        use mem;
        use rand::Rng;
        use rand::reader::ReaderRng;
        use sys::os::errno;

        #[cfg(all(target_os = "linux",
                  any(target_arch = "x86_64",
                      target_arch = "x86",
                      target_arch = "arm",
                      target_arch = "aarch64",
                      target_arch = "powerpc",
                      target_arch = "powerpc64")))]
        fn getrandom(buf: &mut [u8]) -> libc::c_long {
            #[cfg(target_arch = "x86_64")]
            const NR_GETRANDOM: libc::c_long = 318;
            #[cfg(target_arch = "x86")]
            const NR_GETRANDOM: libc::c_long = 355;
            #[cfg(target_arch = "arm")]
            const NR_GETRANDOM: libc::c_long = 384;
            #[cfg(any(target_arch = "powerpc", target_arch = "powerpc64"))]
            const NR_GETRANDOM: libc::c_long = 359;
            #[cfg(target_arch = "aarch64")]
            const NR_GETRANDOM: libc::c_long = 278;

            const GRND_NONBLOCK: libc::c_uint = 0x0001;

            unsafe {
                libc::syscall(NR_GETRANDOM, buf.as_mut_ptr(), buf.len(), GRND_NONBLOCK)
            }
        }

        #[cfg(not(all(target_os = "linux",
                      any(target_arch = "x86_64",
                          target_arch = "x86",
                          target_arch = "arm",
                          target_arch = "aarch64",
                          target_arch = "powerpc",
                          target_arch = "powerpc64"))))]
        fn getrandom(_buf: &mut [u8]) -> libc::c_long { -1 }

        fn getrandom_fill_bytes(v: &mut [u8]) {
            let mut read = 0;
            while read < v.len() {
                let result = getrandom(&mut v[read..]);
                if result == -1 {
                    let err = errno() as libc::c_int;
                    if err == libc::EINTR {
                        continue;
                    } else if err == libc::EAGAIN {
                        // if getrandom() returns EAGAIN it would have blocked
                        // because the non-blocking pool (urandom) has not
                        // initialized in the kernel yet due to a lack of entropy
                        // the fallback we do here is to avoid blocking applications
                        // which could depend on this call without ever knowing
                        // they do and don't have a work around. The PRNG of
                        // /dev/urandom will still be used but not over a completely
                        // full entropy pool
                        let reader = File::open("/dev/urandom").expect("Unable to open /dev/urandom");
                        let mut reader_rng = ReaderRng::new(reader);
                        reader_rng.fill_bytes(& mut v[read..]);
                        read += v.len() as usize;
                    } else {
                        panic!("unexpected getrandom error: {}", err);
                    }
                } else {
                    read += result as usize;
                }
            }
        }

        fn getrandom_next_u32() -> u32 {
            let mut buf: [u8; 4] = [0; 4];
            getrandom_fill_bytes(&mut buf);
            unsafe { mem::transmute::<[u8; 4], u32>(buf) }
        }

        fn getrandom_next_u64() -> u64 {
            let mut buf: [u8; 8] = [0; 8];
            getrandom_fill_bytes(&mut buf);
            unsafe { mem::transmute::<[u8; 8], u64>(buf) }
        }

        #[cfg(all(target_os = "linux",
                  any(target_arch = "x86_64",
                      target_arch = "x86",
                      target_arch = "arm",
                      target_arch = "aarch64",
                      target_arch = "powerpc",
                      target_arch = "powerpc64")))]
        fn is_getrandom_available() -> bool {
            use sync::atomic::{AtomicBool, Ordering};
            use sync::Once;

            static CHECKER: Once = Once::new();
            static AVAILABLE: AtomicBool = AtomicBool::new(false);

            CHECKER.call_once(|| {
                let mut buf: [u8; 0] = [];
                let result = getrandom(&mut buf);
                let available = if result == -1 {
                    let err = io::Error::last_os_error().raw_os_error();
                    err != Some(libc::ENOSYS)
                } else {
                    true
                };
                AVAILABLE.store(available, Ordering::Relaxed);
            });

            AVAILABLE.load(Ordering::Relaxed)
        }

        #[cfg(not(all(target_os = "linux",
                      any(target_arch = "x86_64",
                          target_arch = "x86",
                          target_arch = "arm",
                          target_arch = "aarch64",
                          target_arch = "powerpc",
                          target_arch = "powerpc64"))))]
        fn is_getrandom_available() -> bool { false }

        pub struct OsRng {
            inner: OsRngInner,
        }

        enum OsRngInner {
            OsGetrandomRng,
            OsReaderRng(ReaderRng<File>),
        }

        impl OsRng {
            /// Create a new `OsRng`.
            pub fn new() -> io::Result<OsRng> {
                if is_getrandom_available() {
                    return Ok(OsRng { inner: OsGetrandomRng });
                }

                let reader = File::open("/dev/urandom")?;
                let reader_rng = ReaderRng::new(reader);

                Ok(OsRng { inner: OsReaderRng(reader_rng) })
            }
        }

        impl Rng for OsRng {
            fn next_u32(&mut self) -> u32 {
                match self.inner {
                    OsGetrandomRng => getrandom_next_u32(),
                    OsReaderRng(ref mut rng) => rng.next_u32(),
                }
            }
            fn next_u64(&mut self) -> u64 {
                match self.inner {
                    OsGetrandomRng => getrandom_next_u64(),
                    OsReaderRng(ref mut rng) => rng.next_u64(),
                }
            }
            fn fill_bytes(&mut self, v: &mut [u8]) {
                match self.inner {
                    OsGetrandomRng => getrandom_fill_bytes(v),
                    OsReaderRng(ref mut rng) => rng.fill_bytes(v)
                }
            }
        }
    }

    #[cfg(target_os = "openbsd")]
    mod imp {
        use io;
        use libc;
        use mem;
        use sys::os::errno;
        use rand::Rng;

        pub struct OsRng {
            // dummy field to ensure that this struct cannot be constructed outside
            // of this module
            _dummy: (),
        }

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

        impl Rng for OsRng {
            fn next_u32(&mut self) -> u32 {
                let mut v = [0; 4];
                self.fill_bytes(&mut v);
                unsafe { mem::transmute(v) }
            }
            fn next_u64(&mut self) -> u64 {
                let mut v = [0; 8];
                self.fill_bytes(&mut v);
                unsafe { mem::transmute(v) }
            }
            fn fill_bytes(&mut self, v: &mut [u8]) {
                // getentropy(2) permits a maximum buffer size of 256 bytes
                for s in v.chunks_mut(256) {
                    let ret = unsafe {
                        libc::getentropy(s.as_mut_ptr() as *mut libc::c_void, s.len())
                    };
                    if ret == -1 {
                        panic!("unexpected getentropy error: {}", errno());
                    }
                }
            }
        }
    }

    #[cfg(target_os = "ios")]
    mod imp {
        use io;
        use mem;
        use ptr;
        use rand::Rng;
        use libc::{c_int, size_t};

        pub struct OsRng {
            // dummy field to ensure that this struct cannot be constructed outside
            // of this module
            _dummy: (),
        }

        enum SecRandom {}

        #[allow(non_upper_case_globals)]
        const kSecRandomDefault: *const SecRandom = ptr::null();

        #[link(name = "Security", kind = "framework")]
        #[cfg(not(cargobuild))]
        extern {}

        extern {
            fn SecRandomCopyBytes(rnd: *const SecRandom,
                                  count: size_t, bytes: *mut u8) -> c_int;
        }

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

        impl Rng for OsRng {
            fn next_u32(&mut self) -> u32 {
                let mut v = [0; 4];
                self.fill_bytes(&mut v);
                unsafe { mem::transmute(v) }
            }
            fn next_u64(&mut self) -> u64 {
                let mut v = [0; 8];
                self.fill_bytes(&mut v);
                unsafe { mem::transmute(v) }
            }
            fn fill_bytes(&mut self, v: &mut [u8]) {
                let ret = unsafe {
                    SecRandomCopyBytes(kSecRandomDefault, v.len() as size_t,
                                       v.as_mut_ptr())
                };
                if ret == -1 {
                    panic!("couldn't generate random bytes: {}",
                           io::Error::last_os_error());
                }
            }
        }
    }

# 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

## 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`)