• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
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 #![forbid(unsafe_code)]
18 #![deny(missing_docs)]
19 
20 extern crate alloc;
21 
22 use alloc::vec::Vec;
23 use crypto_provider::{CryptoProvider, CryptoRng};
24 use log::info;
25 pub use rand;
26 use rand::{Rng as _, SeedableRng};
27 
28 /// Returns a random Vec with the provided length.
random_vec<C: CryptoProvider>(rng: &mut C::CryptoRng, len: usize) -> Vec<u8>29 pub fn random_vec<C: CryptoProvider>(rng: &mut C::CryptoRng, len: usize) -> Vec<u8> {
30     let mut bytes = Vec::<u8>::new();
31     bytes.extend((0..len).map(|_| rng.gen::<u8>()));
32     bytes
33 }
34 
35 /// Returns a random array with the provided length.
random_bytes<const B: usize, C: CryptoProvider>(rng: &mut C::CryptoRng) -> [u8; B]36 pub fn random_bytes<const B: usize, C: CryptoProvider>(rng: &mut C::CryptoRng) -> [u8; B] {
37     let mut bytes = [0; B];
38     rng.fill(bytes.as_mut_slice());
39     bytes
40 }
41 
42 /// Uses a RustCrypto Rng to return a random Vec with the provided length
random_vec_rc<R: rand::Rng>(rng: &mut R, len: usize) -> Vec<u8>43 pub fn random_vec_rc<R: rand::Rng>(rng: &mut R, len: usize) -> Vec<u8> {
44     let mut bytes = Vec::<u8>::new();
45     bytes.extend((0..len).map(|_| rng.gen::<u8>()));
46     bytes
47 }
48 
49 /// Uses a RustCrypto Rng to return random bytes with the provided length
random_bytes_rc<const B: usize, R: rand::Rng>(rng: &mut R) -> [u8; B]50 pub fn random_bytes_rc<const B: usize, R: rand::Rng>(rng: &mut R) -> [u8; B] {
51     let mut bytes = [0; B];
52     rng.fill(bytes.as_mut_slice());
53     bytes
54 }
55 
56 /// Returns a fast rng seeded with the thread rng (which is itself seeded from the OS).
seeded_rng() -> impl rand::Rng57 pub fn seeded_rng() -> impl rand::Rng {
58     let mut seed: <rand_pcg::Pcg64 as rand::SeedableRng>::Seed = Default::default();
59     rand::thread_rng().fill(&mut seed);
60     // print it out so if a test fails, the seed will be visible for further investigation
61     info!("seed: {:?}", seed);
62     rand_pcg::Pcg64::from_seed(seed)
63 }
64