Modern-Apps.git
Publicgit clone https://git.maproj.org/Modern-Apps.gitModern-Apps.git / third_party / betocore / rand_ext / src / lib.rs
lib.rs61 lines · 2.2 KiBRaw
| 1 | // Copyright 2022 Google LLC |
| 2 | // |
| 3 | // Licensed under the Apache License, Version 2.0 (the "License"); |
| 4 | // you may not use this file except in compliance with the License. |
| 5 | // You may obtain a copy of the License at |
| 6 | // |
| 7 | // http://www.apache.org/licenses/LICENSE-2.0 |
| 8 | // |
| 9 | // Unless required by applicable law or agreed to in writing, software |
| 10 | // distributed under the License is distributed on an "AS IS" BASIS, |
| 11 | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 12 | // See the License for the specific language governing permissions and |
| 13 | // limitations under the License. |
| 14 | |
| 15 | //! Helper functions around `rand`'s offerings for convenient test usage. |
| 16 | #![no_std] |
| 17 | |
| 18 | extern crate alloc; |
| 19 | |
| 20 | use alloc::vec::Vec; |
| 21 | use crypto_provider::{CryptoProvider, CryptoRng}; |
| 22 | use log::info; |
| 23 | use rand::{Rng, RngExt, SeedableRng}; |
| 24 | pub use {rand, rand_pcg}; |
| 25 | |
| 26 | /// Returns a random Vec with the provided length. |
| 27 | pub fn random_vec<C: CryptoProvider>(rng: &mut C::CryptoRng, len: usize) -> Vec<u8> { |
| 28 | let mut bytes = Vec::<u8>::new(); |
| 29 | bytes.extend((0..len).map(|_| rng.gen::<u8>())); |
| 30 | bytes |
| 31 | } |
| 32 | |
| 33 | /// Returns a random array with the provided length. |
| 34 | pub fn random_bytes<const B: usize, C: CryptoProvider>(rng: &mut C::CryptoRng) -> [u8; B] { |
| 35 | let mut bytes = [0; B]; |
| 36 | rng.fill(bytes.as_mut_slice()); |
| 37 | bytes |
| 38 | } |
| 39 | |
| 40 | /// Uses a RustCrypto Rng to return a random Vec with the provided length |
| 41 | pub fn random_vec_rc<R: rand::Rng>(rng: &mut R, len: usize) -> Vec<u8> { |
| 42 | let mut bytes = Vec::<u8>::new(); |
| 43 | bytes.extend((0..len).map(|_| rng.random::<u8>())); |
| 44 | bytes |
| 45 | } |
| 46 | |
| 47 | /// Uses a RustCrypto Rng to return random bytes with the provided length |
| 48 | pub fn random_bytes_rc<const B: usize, R: rand::Rng>(rng: &mut R) -> [u8; B] { |
| 49 | let mut bytes = [0; B]; |
| 50 | rng.fill_bytes(bytes.as_mut_slice()); |
| 51 | bytes |
| 52 | } |
| 53 | |
| 54 | /// Returns a fast rng seeded with the thread rng (which is itself seeded from the OS). |
| 55 | pub fn seeded_rng() -> rand_pcg::Pcg64 { |
| 56 | let mut seed: <rand_pcg::Pcg64 as rand::SeedableRng>::Seed = Default::default(); |
| 57 | rand::rng().fill_bytes(&mut seed); |
| 58 | // print it out so if a test fails, the seed will be visible for further investigation |
| 59 | info!("seed: {seed:?}"); |
| 60 | rand_pcg::Pcg64::from_seed(seed) |
| 61 | } |