self_encryption/
test_helpers.rs

1// Copyright 2021 MaidSafe.net limited.
2//
3// This SAFE Network Software is licensed to you under The General Public License (GPL), version 3.
4// Unless required by applicable law or agreed to in writing, the SAFE Network Software distributed
5// under the GPL Licence is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
6// KIND, either express or implied. Please review the Licences for the specific language governing
7// permissions and limitations relating to use of the SAFE Network Software.
8
9#![doc(hidden)]
10
11use crate::{ChunkInfo, DataMap, Error};
12
13use bytes::Bytes;
14use rand::{self, rngs::OsRng, Rng, SeedableRng};
15use rand_chacha::ChaChaRng;
16use rayon::current_num_threads;
17use serde::{de::DeserializeOwned, Serialize};
18use std::env;
19
20pub type TestRng = ChaChaRng;
21
22// Create new random number generator suitable for tests. To provide repeatable results, the seed
23// can be overridden using the "SEED" env variable. If this variable is not provided, a random one
24// is used (to support soak testing). The current seed is printed to stdout.
25pub fn new_test_rng() -> Result<TestRng, Error> {
26    let seed = if let Ok(seed) = env::var("SEED") {
27        seed.parse()?
28    } else {
29        rand::thread_rng().gen()
30    };
31
32    Ok(TestRng::seed_from_u64(seed))
33}
34
35pub fn from_rng(rng: &mut TestRng) -> Result<TestRng, Error> {
36    Ok(TestRng::from_rng(rng)?)
37}
38
39pub fn serialise<T: Serialize>(data: &T) -> Result<Vec<u8>, Error> {
40    Ok(bincode::serialize(data)?)
41}
42
43pub fn deserialise<T>(data: &[u8]) -> Result<T, Error>
44where
45    T: Serialize + DeserializeOwned,
46{
47    match bincode::deserialize(data) {
48        Ok(data) => Ok(data),
49        Err(_) => Err(Error::Deserialise),
50    }
51}
52
53/// Generates random bytes using provided `size`.
54pub fn random_bytes(size: usize) -> Bytes {
55    use rayon::prelude::*;
56    let threads = current_num_threads();
57
58    if threads > size {
59        let mut rng = OsRng;
60        return ::std::iter::repeat(())
61            .map(|()| rng.gen::<u8>())
62            .take(size)
63            .collect();
64    }
65
66    let per_thread = size / threads;
67    let remainder = size % threads;
68
69    let mut bytes: Vec<u8> = (0..threads)
70        .par_bridge()
71        .map(|_| vec![0u8; per_thread])
72        .map(|mut bytes| {
73            let bytes = bytes.as_mut_slice();
74            rand::thread_rng().fill(bytes);
75            bytes.to_owned()
76        })
77        .flatten()
78        .collect();
79
80    bytes.extend(vec![0u8; remainder]);
81
82    Bytes::from(bytes)
83}
84
85pub fn create_test_data_map(chunks: Vec<ChunkInfo>) -> DataMap {
86    DataMap::new(chunks)
87}
88
89pub fn create_test_data_map_with_child(chunks: Vec<ChunkInfo>, child: usize) -> DataMap {
90    DataMap::with_child(chunks, child)
91}