1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
use std::error::Error;
extern crate rand;
use rand::prelude::*;
static NUMBERS:&'static str = "0123456789";
static LETTERS:&'static str = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";
static SPECIALS:&'static str = "~!@#$%^*()_+-=[]{}|;:,./<>?";
pub fn random(mut length: i32, options: Options) -> Result<String, Box<dyn Error>> {
if length == 0 {
length = 8;
}
let mut chars = String::from("");
let mut result = String::from("");
match options.rand {
RandWay::NUMBER => {
chars.push_str(&options.numbers.unwrap_or(NUMBERS.to_string()));
}
RandWay::LETTER => {
chars.push_str(&options.letters.unwrap_or(LETTERS.to_string()));
}
RandWay::SPECIAL => {
chars.push_str(&options.specials.unwrap_or(SPECIALS.to_string()));
}
_ => {
chars.push_str(&options.numbers.unwrap_or(NUMBERS.to_string()));
chars.push_str(&options.letters.unwrap_or(LETTERS.to_string()));
}
}
let mut rng = thread_rng();
while length > 0 {
length = length-1;
let num = rng.gen_range(0f64, 1.0f64);
let num = num * chars.len() as f64;
let index_begin = num as usize - 1;
let x = &chars[index_begin..num as usize];
result.push_str(x);
}
Ok(result)
}
pub struct Options {
pub rand: RandWay,
pub numbers: Option<String>,
pub letters: Option<String>,
pub specials: Option<String>,
}
pub enum RandWay {
NORMAL,
NUMBER,
LETTER,
SPECIAL
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn string_random() {
let options = Options {
rand: RandWay::NORMAL,
numbers: None,
letters: None,
specials: None
};
let res = random(5,options);
let string = res.unwrap();
println!("{}",string);
}
}