1 // Copyright 2019 Developers of the Rand project.
2 //
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.
8
9 //! Interface to the random number generator of the operating system.
10
11 use crate::{impls, CryptoRng, Error, RngCore};
12 use getrandom::getrandom;
13
14 /// A random number generator that retrieves randomness from the
15 /// operating system.
16 ///
17 /// This is a zero-sized struct. It can be freely constructed with `OsRng`.
18 ///
19 /// The implementation is provided by the [getrandom] crate. Refer to
20 /// [getrandom] documentation for details.
21 ///
22 /// This struct is only available when specifying the crate feature `getrandom`
23 /// or `std`. When using the `rand` lib, it is also available as `rand::rngs::OsRng`.
24 ///
25 /// # Blocking and error handling
26 ///
27 /// It is possible that when used during early boot the first call to `OsRng`
28 /// will block until the system's RNG is initialised. It is also possible
29 /// (though highly unlikely) for `OsRng` to fail on some platforms, most
30 /// likely due to system mis-configuration.
31 ///
32 /// After the first successful call, it is highly unlikely that failures or
33 /// significant delays will occur (although performance should be expected to
34 /// be much slower than a user-space PRNG).
35 ///
36 /// # Usage example
37 /// ```
38 /// use rand_core::{RngCore, OsRng};
39 ///
40 /// let mut key = [0u8; 16];
41 /// OsRng.fill_bytes(&mut key);
42 /// let random_u64 = OsRng.next_u64();
43 /// ```
44 ///
45 /// [getrandom]: https://crates.io/crates/getrandom
46 #[cfg_attr(doc_cfg, doc(cfg(feature = "getrandom")))]
47 #[derive(Clone, Copy, Debug, Default)]
48 pub struct OsRng;
49
50 impl CryptoRng for OsRng {}
51
52 impl RngCore for OsRng {
next_u32(&mut self) -> u3253 fn next_u32(&mut self) -> u32 {
54 impls::next_u32_via_fill(self)
55 }
56
next_u64(&mut self) -> u6457 fn next_u64(&mut self) -> u64 {
58 impls::next_u64_via_fill(self)
59 }
60
fill_bytes(&mut self, dest: &mut [u8])61 fn fill_bytes(&mut self, dest: &mut [u8]) {
62 if let Err(e) = self.try_fill_bytes(dest) {
63 panic!("Error: {}", e);
64 }
65 }
66
try_fill_bytes(&mut self, dest: &mut [u8]) -> Result<(), Error>67 fn try_fill_bytes(&mut self, dest: &mut [u8]) -> Result<(), Error> {
68 getrandom(dest)?;
69 Ok(())
70 }
71 }
72
73 #[test]
test_os_rng()74 fn test_os_rng() {
75 let x = OsRng.next_u64();
76 let y = OsRng.next_u64();
77 assert!(x != 0);
78 assert!(x != y);
79 }
80
81 #[test]
test_construction()82 fn test_construction() {
83 let mut rng = OsRng::default();
84 assert!(rng.next_u64() != 0);
85 }
86