| 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::{TryCryptoRng, TryRngCore}; |
| 12 |
|
| 13 |
/// An interface over the operating-system's random data source |
| 14 |
/// |
| 15 |
/// This is a zero-sized struct. It can be freely constructed with just `OsRng`. |
| 16 |
/// |
| 17 |
/// The implementation is provided by the [getrandom] crate. Refer to |
| 18 |
/// [getrandom] documentation for details. |
| 19 |
/// |
| 20 |
/// This struct is available as `rand_core::OsRng` and as `rand::rngs::OsRng`. |
| 21 |
/// In both cases, this requires the crate feature `os_rng` or `std` |
| 22 |
/// (enabled by default in `rand` but not in `rand_core`). |
| 23 |
/// |
| 24 |
/// # Blocking and error handling |
| 25 |
/// |
| 26 |
/// It is possible that when used during early boot the first call to `OsRng` |
| 27 |
/// will block until the system's RNG is initialised. It is also possible |
| 28 |
/// (though highly unlikely) for `OsRng` to fail on some platforms, most |
| 29 |
/// likely due to system mis-configuration. |
| 30 |
/// |
| 31 |
/// After the first successful call, it is highly unlikely that failures or |
| 32 |
/// significant delays will occur (although performance should be expected to |
| 33 |
/// be much slower than a user-space |
| 34 |
/// [PRNG](https://rust-random.github.io/book/guide-gen.html#pseudo-random-number-generators)). |
| 35 |
/// |
| 36 |
/// # Usage example |
| 37 |
/// ``` |
| 38 |
/// use rand_core::{TryRngCore, OsRng}; |
| 39 |
/// |
| 40 |
/// let mut key = [0u8; 16]; |
| 41 |
/// OsRng.try_fill_bytes(&mut key).unwrap(); |
| 42 |
/// let random_u64 = OsRng.try_next_u64().unwrap(); |
| 43 |
/// ``` |
| 44 |
/// |
| 45 |
/// [getrandom]: https://crates.io/crates/getrandom |
| 46 |
#[derive(Clone, Copy, Debug, Default)] |
| 47 |
pub struct OsRng; |
| 48 |
|
| 49 |
/// Error type of [`OsRng`] |
| 50 |
#[derive(Clone, Copy, Debug, PartialEq, Eq)] |
| 51 |
pub struct OsError(getrandom::Error); |
| 52 |
|
| 53 |
impl core::fmt::Display for OsError { |
| 54 |
#[inline] |
| 55 |
fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result { |
| 56 |
self.0.fmt(f) |
| 57 |
} |
| 58 |
} |
| 59 |
|
| 60 |
// NOTE: this can use core::error::Error from rustc 1.81.0 |
| 61 |
#[cfg(feature = "std")] |
| 62 |
impl std::error::Error for OsError { |
| 63 |
#[inline] |
| 64 |
fn source(&self) -> Option<&(dyn std::error::Error + 'static)> { |
| 65 |
std::error::Error::source(&self.0) |
| 66 |
} |
| 67 |
} |
| 68 |
|
| 69 |
impl OsError { |
| 70 |
/// Extract the raw OS error code (if this error came from the OS) |
| 71 |
/// |
| 72 |
/// This method is identical to [`std::io::Error::raw_os_error()`][1], except |
| 73 |
/// that it works in `no_std` contexts. If this method returns `None`, the |
| 74 |
/// error value can still be formatted via the `Display` implementation. |
| 75 |
/// |
| 76 |
/// [1]: https://doc.rust-lang.org/std/io/struct.Error.html#method.raw_os_error |
| 77 |
#[inline] |
| 78 |
pub fn raw_os_error(self) -> Option<i32> { |
| 79 |
self.0.raw_os_error() |
| 80 |
} |
| 81 |
} |
| 82 |
|
| 83 |
impl TryRngCore for OsRng { |
| 84 |
type Error = OsError; |
| 85 |
|
| 86 |
#[inline] |
| 87 |
fn try_next_u32(&mut self) -> Result<u32, Self::Error> { |
| 88 |
getrandom::u32().map_err(OsError) |
| 89 |
} |
| 90 |
|
| 91 |
#[inline] |
| 92 |
fn try_next_u64(&mut self) -> Result<u64, Self::Error> { |
| 93 |
getrandom::u64().map_err(OsError) |
| 94 |
} |
| 95 |
|
| 96 |
#[inline] |
| 97 |
fn try_fill_bytes(&mut self, dest: &mut [u8]) -> Result<(), Self::Error> { |
| 98 |
getrandom::fill(dest).map_err(OsError) |
| 99 |
} |
| 100 |
} |
| 101 |
|
| 102 |
impl TryCryptoRng for OsRng {} |
| 103 |
|
| 104 |
#[test] |
| 105 |
fn test_os_rng() { |
| 106 |
let x = OsRng.try_next_u64().unwrap(); |
| 107 |
let y = OsRng.try_next_u64().unwrap(); |
| 108 |
assert!(x != 0); |
| 109 |
assert!(x != y); |
| 110 |
} |
| 111 |
|
| 112 |
#[test] |
| 113 |
fn test_construction() { |
| 114 |
assert!(OsRng.try_next_u64().unwrap() != 0); |
| 115 |
} |