|
| 1 | +// This file is Copyright its original authors, visible in version control |
| 2 | +// history. |
| 3 | +// |
| 4 | +// This file is licensed under the Apache License, Version 2.0 <LICENSE-APACHE |
| 5 | +// or http://www.apache.org/licenses/LICENSE-2.0> or the MIT license |
| 6 | +// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your option. |
| 7 | +// You may not use this file except in accordance with one or both of these |
| 8 | +// licenses. |
| 9 | + |
| 10 | +//! [`getrandom`] provides access to OS randomness, but will fail to compile on platforms which do |
| 11 | +//! not support fetching OS randomness. This is exactly what you want when you're doing |
| 12 | +//! cryptographic operations, but when you're just opportunistically randomizing, we're fine with |
| 13 | +//! compiling and simply disabling randomization. |
| 14 | +//! |
| 15 | +//! This crate does that, returning only possibly-random data. |
| 16 | +//! |
| 17 | +//! Note that this crate only enables getrandom on a subset of platforms it supports. As getrandom |
| 18 | +//! evolves this crate is unlikely to carefully track all getrandom-supported platforms, however |
| 19 | +//! will use random data on popular platforms. |
| 20 | +
|
| 21 | +#[cfg(feature = "getrandom")] |
| 22 | +extern crate getrandom; |
| 23 | + |
| 24 | +/// Possibly fills `dest` with random data. May fill it with zeros. |
| 25 | +#[cfg(feature = "getrandom")] |
| 26 | +#[inline] |
| 27 | +pub fn getpossiblyrandom(dest: &mut [u8]) { |
| 28 | + if getrandom::getrandom(dest).is_err() { |
| 29 | + dest.fill(0); |
| 30 | + } |
| 31 | +} |
| 32 | + |
| 33 | +/// Possibly fills `dest` with random data. May fill it with zeros. |
| 34 | +#[cfg(not(feature = "getrandom"))] |
| 35 | +#[inline] |
| 36 | +pub fn getpossiblyrandom(dest: &mut [u8]) { |
| 37 | + dest.fill(0); |
| 38 | +} |
0 commit comments