]> git.proxmox.com Git - rustc.git/blob - vendor/rand_core/src/os.rs
New upstream version 1.51.0+dfsg1
[rustc.git] / vendor / rand_core / src / os.rs
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 // Note: keep this code in sync with the rand_os crate!
11
12 use getrandom::getrandom;
13 use crate::{CryptoRng, RngCore, Error, impls};
14
15 /// A random number generator that retrieves randomness from from the
16 /// operating system.
17 ///
18 /// This is a zero-sized struct. It can be freely constructed with `OsRng`.
19 ///
20 /// The implementation is provided by the [getrandom] crate. Refer to
21 /// [getrandom] documentation for details.
22 ///
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`.
25 ///
26 /// # Blocking and error handling
27 ///
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.
32 ///
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).
36 ///
37 /// # Usage example
38 /// ```
39 /// use rand_core::{RngCore, OsRng};
40 ///
41 /// let mut key = [0u8; 16];
42 /// OsRng.fill_bytes(&mut key);
43 /// let random_u64 = OsRng.next_u64();
44 /// ```
45 ///
46 /// [getrandom]: https://crates.io/crates/getrandom
47 #[derive(Clone, Copy, Debug, Default)]
48 pub struct OsRng;
49
50 impl CryptoRng for OsRng {}
51
52 impl RngCore for OsRng {
53 fn next_u32(&mut self) -> u32 {
54 impls::next_u32_via_fill(self)
55 }
56
57 fn next_u64(&mut self) -> u64 {
58 impls::next_u64_via_fill(self)
59 }
60
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
67 fn try_fill_bytes(&mut self, dest: &mut [u8]) -> Result<(), Error> {
68 getrandom(dest)?;
69 Ok(())
70 }
71 }
72
73 #[test]
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]
82 fn test_construction() {
83 let mut rng = OsRng::default();
84 assert!(rng.next_u64() != 0);
85 }