cfxstore/
random.rs

1// Copyright 2015-2019 Parity Technologies (UK) Ltd.
2// This file is part of Parity Ethereum.
3
4// Parity Ethereum is free software: you can redistribute it and/or modify
5// it under the terms of the GNU General Public License as published by
6// the Free Software Foundation, either version 3 of the License, or
7// (at your option) any later version.
8
9// Parity Ethereum is distributed in the hope that it will be useful,
10// but WITHOUT ANY WARRANTY; without even the implied warranty of
11// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
12// GNU General Public License for more details.
13
14// You should have received a copy of the GNU General Public License
15// along with Parity Ethereum.  If not, see <http://www.gnu.org/licenses/>.
16
17use rand::{distr::Alphanumeric, rngs::OsRng, Rng, TryRngCore};
18
19pub trait Random {
20    fn random() -> Self
21    where Self: Sized;
22}
23
24impl Random for [u8; 16] {
25    fn random() -> Self {
26        let mut result = [0u8; 16];
27        OsRng.try_fill_bytes(&mut result).unwrap();
28        result
29    }
30}
31
32impl Random for [u8; 32] {
33    fn random() -> Self {
34        let mut result = [0u8; 32];
35        OsRng.try_fill_bytes(&mut result).unwrap();
36        result
37    }
38}
39
40/// Generate a random string of given length.
41pub fn random_string(length: usize) -> String {
42    let mut rng = rand::rng();
43    (&mut rng)
44        .sample_iter(Alphanumeric)
45        .take(length)
46        .map(char::from)
47        .collect()
48}