rand_os/lib.rs
1// Copyright 2018 Developers of the Rand project.
2// Copyright 2013-2015 The Rust Project Developers.
3//
4// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
5// https://www.apache.org/licenses/LICENSE-2.0> or the MIT license
6// <LICENSE-MIT or https://opensource.org/licenses/MIT>, at your
7// option. This file may not be copied, modified, or distributed
8// except according to those terms.
9
10//! Interface to the random number generator of the operating system.
11// Note: keep this code in sync with the rand::rngs::os module!
12
13#![doc(html_logo_url = "https://www.rust-lang.org/logos/rust-logo-128x128-blk.png",
14 html_favicon_url = "https://www.rust-lang.org/favicon.ico",
15 html_root_url = "https://rust-random.github.io/rand/")]
16#![deny(missing_docs)]
17#![deny(missing_debug_implementations)]
18#![doc(test(attr(allow(unused_variables), deny(warnings))))]
19
20#![no_std] // but see getrandom crate
21
22#![deprecated(since="0.2.2", note="OsRng is now provided by rand_core and rand")]
23
24pub use rand_core; // re-export
25
26use getrandom::getrandom;
27use rand_core::{CryptoRng, RngCore, Error, impls};
28
29/// A random number generator that retrieves randomness from from the
30/// operating system.
31///
32/// This is a zero-sized struct. It can be freely constructed with `OsRng`.
33///
34/// The implementation is provided by the [getrandom] crate. Refer to
35/// [getrandom] documentation for details.
36///
37/// # Blocking and error handling
38///
39/// It is possible that when used during early boot the first call to `OsRng`
40/// will block until the system's RNG is initialised. It is also possible
41/// (though highly unlikely) for `OsRng` to fail on some platforms, most
42/// likely due to system mis-configuration.
43///
44/// After the first successful call, it is highly unlikely that failures or
45/// significant delays will occur (although performance should be expected to
46/// be much slower than a user-space PRNG).
47///
48/// # Usage example
49/// ```
50/// #![allow(deprecated)]
51/// use rand_os::rand_core::RngCore;
52/// use rand_os::OsRng;
53///
54/// let mut key = [0u8; 16];
55/// OsRng.fill_bytes(&mut key);
56/// let random_u64 = OsRng.next_u64();
57/// ```
58///
59/// [getrandom]: https://crates.io/crates/getrandom
60#[derive(Clone, Copy, Debug, Default)]
61pub struct OsRng;
62
63impl OsRng {
64 /// Create a new `OsRng`.
65 #[deprecated(since="0.2.0", note="replace OsRng::new().unwrap() with just OsRng")]
66 pub fn new() -> Result<OsRng, Error> {
67 Ok(OsRng)
68 }
69}
70
71impl CryptoRng for OsRng {}
72
73impl RngCore for OsRng {
74 fn next_u32(&mut self) -> u32 {
75 impls::next_u32_via_fill(self)
76 }
77
78 fn next_u64(&mut self) -> u64 {
79 impls::next_u64_via_fill(self)
80 }
81
82 fn fill_bytes(&mut self, dest: &mut [u8]) {
83 if let Err(e) = self.try_fill_bytes(dest) {
84 panic!("Error: {}", e);
85 }
86 }
87
88 fn try_fill_bytes(&mut self, dest: &mut [u8]) -> Result<(), Error> {
89 getrandom(dest)?;
90 Ok(())
91 }
92}
93
94#[test]
95fn test_os_rng() {
96 let x = OsRng.next_u64();
97 let y = OsRng.next_u64();
98 assert!(x != 0);
99 assert!(x != y);
100}
101
102#[test]
103fn test_construction() {
104 let mut rng = OsRng::default();
105 assert!(rng.next_u64() != 0);
106}