Merge pull request #3111 from tnull/2024-06-rustfmt-fuzz-the-easy-part
[rust-lightning] / possiblyrandom / src / lib.rs
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 that 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 #![no_std]
22
23 #[cfg(feature = "getrandom")]
24 extern crate getrandom;
25
26 /// Possibly fills `dest` with random data. May fill it with zeros.
27 #[inline]
28 pub fn getpossiblyrandom(dest: &mut [u8]) {
29         #[cfg(feature = "getrandom")]
30         if getrandom::getrandom(dest).is_err() {
31                 dest.fill(0);
32         }
33         #[cfg(not(feature = "getrandom"))]
34         dest.fill(0);
35 }