easy_utils/random.rs
1use rand::{Rng};
2use rand::distributions::Alphanumeric;
3
4/// Generate random String with given charset of len length
5///
6/// # Example
7///
8/// ```
9/// const CHARSET: &[u8] = b"ABCDEFGHIJKLMNOPQRSTUVWXYZ\
10/// abcdefghijklmnopqrstuvwxyz\
11/// 0123456789)(*&^%$#@!~";
12/// const PASSWORD_LEN: usize = 30;
13/// let password = rust_utils::random::get_random_charset_string(PASSWORD_LEN, CHARSET);
14/// assert_eq!(password.len(), PASSWORD_LEN);
15/// for x in password.bytes() {
16/// assert!(CHARSET.contains(&x));
17/// }
18/// ```
19pub fn get_random_charset_string(len: usize, charset: &[u8]) -> String {
20 (0..len)
21 .map(|_| {
22 let idx = rand::thread_rng().gen_range(0..charset.len());
23 // It's safe, because `idx` is in `CHARSET`'s range.
24 char::from(unsafe { *charset.get_unchecked(idx) })
25 })
26 .collect()
27}
28
29/// Generate random String with alphanumeric(uppercase, lowercase & number) charset of len length
30///
31/// # Example
32///
33/// ```
34///const GEN_ASCII_STR_CHARSET: &[u8] = b"ABCDEFGHIJKLMNOPQRSTUVWXYZ\
35/// abcdefghijklmnopqrstuvwxyz\
36/// 0123456789";
37/// const PASSWORD_LEN: usize = 30;
38/// let password = rust_utils::random::get_random_alphanumeric_string(PASSWORD_LEN);
39/// assert_eq!(password.len(), PASSWORD_LEN);
40/// for x in password.bytes() {
41/// assert!(GEN_ASCII_STR_CHARSET.contains(&x));
42/// }
43/// ```
44pub fn get_random_alphanumeric_string(len: usize) -> String {
45 rand::thread_rng()
46 .sample_iter(&Alphanumeric)
47 .take(len)
48 .map(char::from)
49 .collect()
50}
51
52#[cfg(test)]
53mod tests {
54 use super::*;
55
56 #[test]
57 fn get_random_charset_string_test() {
58 const CHARSET: &[u8] = b"ABCDEFGHIJKLMNOPQRSTUVWXYZ\
59 abcdefghijklmnopqrstuvwxyz\
60 0123456789)(*&^%$#@!~";
61 const PASSWORD_LEN: usize = 30;
62
63 let password = get_random_charset_string(PASSWORD_LEN, CHARSET);
64
65 assert_eq!(password.len(), PASSWORD_LEN);
66 for x in password.bytes() {
67 assert!(CHARSET.contains(&x));
68 }
69 }
70
71 #[test]
72 fn get_random_alphanumeric_string_test() {
73 const GEN_ASCII_STR_CHARSET: &[u8] = b"ABCDEFGHIJKLMNOPQRSTUVWXYZ\
74 abcdefghijklmnopqrstuvwxyz\
75 0123456789";
76 const PASSWORD_LEN: usize = 30;
77
78 let password = get_random_alphanumeric_string(PASSWORD_LEN);
79 assert_eq!(password.len(), PASSWORD_LEN);
80 for x in password.bytes() {
81 assert!(GEN_ASCII_STR_CHARSET.contains(&x));
82 }
83 }
84}