1 // Copyright 2019 Developers of the Rand project.
3 // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
4 // https://www.apache.org/licenses/LICENSE-2.0> or the MIT license
5 // <LICENSE-MIT or https://opensource.org/licenses/MIT>, at your
6 // option. This file may not be copied, modified, or distributed
7 // except according to those terms.
9 //! Interface to the random number generator of the operating system.
10 // Note: keep this code in sync with the rand_os crate!
12 use getrandom
::getrandom
;
13 use crate::{CryptoRng, RngCore, Error, impls}
;
15 /// A random number generator that retrieves randomness from from the
18 /// This is a zero-sized struct. It can be freely constructed with `OsRng`.
20 /// The implementation is provided by the [getrandom] crate. Refer to
21 /// [getrandom] documentation for details.
23 /// This struct is only available when specifying the crate feature `getrandom`
24 /// or `std`. When using the `rand` lib, it is also available as `rand::rngs::OsRng`.
26 /// # Blocking and error handling
28 /// It is possible that when used during early boot the first call to `OsRng`
29 /// will block until the system's RNG is initialised. It is also possible
30 /// (though highly unlikely) for `OsRng` to fail on some platforms, most
31 /// likely due to system mis-configuration.
33 /// After the first successful call, it is highly unlikely that failures or
34 /// significant delays will occur (although performance should be expected to
35 /// be much slower than a user-space PRNG).
39 /// use rand_core::{RngCore, OsRng};
41 /// let mut key = [0u8; 16];
42 /// OsRng.fill_bytes(&mut key);
43 /// let random_u64 = OsRng.next_u64();
46 /// [getrandom]: https://crates.io/crates/getrandom
47 #[derive(Clone, Copy, Debug, Default)]
50 impl CryptoRng
for OsRng {}
52 impl RngCore
for OsRng
{
53 fn next_u32(&mut self) -> u32 {
54 impls
::next_u32_via_fill(self)
57 fn next_u64(&mut self) -> u64 {
58 impls
::next_u64_via_fill(self)
61 fn fill_bytes(&mut self, dest
: &mut [u8]) {
62 if let Err(e
) = self.try_fill_bytes(dest
) {
63 panic
!("Error: {}", e
);
67 fn try_fill_bytes(&mut self, dest
: &mut [u8]) -> Result
<(), Error
> {
75 let x
= OsRng
.next_u64();
76 let y
= OsRng
.next_u64();
82 fn test_construction() {
83 let mut rng
= OsRng
::default();
84 assert
!(rng
.next_u64() != 0);