optimized pattern generation code
This commit is contained in:
parent
0d9519c0db
commit
e0d66a31f0
1 changed files with 24 additions and 23 deletions
|
|
@ -1,32 +1,33 @@
|
|||
use rand::RngExt;
|
||||
|
||||
const DIGITS: &[u8] = b"0123456789";
|
||||
const LETTERS_LOWER: &[u8] = b"abcdefghijklmnopqrstuvwxyz";
|
||||
const LETTERS_UPPER: &[u8] = b"ABCDEFGHIJKLMNOPQRSTUVWXYZ";
|
||||
const ALNUM_LOWER: &[u8] = b"0123456789abcdefghijklmnopqrstuvwxyz";
|
||||
const ALNUM_UPPER: &[u8] = b"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ";
|
||||
|
||||
fn pick(rng: &mut impl rand::Rng, pool: &[u8]) -> char {
|
||||
pool[rng.random_range(0..pool.len())] as char
|
||||
}
|
||||
|
||||
pub fn generate_from_pattern(pattern: &str) -> String {
|
||||
let mut rng = rand::rng();
|
||||
let mut output = String::new();
|
||||
let mut output = String::with_capacity(pattern.len());
|
||||
|
||||
for c in pattern.chars() {
|
||||
match c {
|
||||
'n' => output.push(rng.random_range('0'..='9')),
|
||||
'l' => {
|
||||
let letter = rng.random_range('a'..='z');
|
||||
output.push(letter);
|
||||
}
|
||||
'L' => {
|
||||
let letter = rng.random_range('A'..='Z');
|
||||
output.push(letter);
|
||||
}
|
||||
'a' => {
|
||||
let pool = "0123456789abcdefghijklmnopqrstuvwxyz";
|
||||
let idx = rng.random_range(0..pool.len());
|
||||
output.push(pool.chars().nth(idx).unwrap());
|
||||
}
|
||||
'A' => {
|
||||
let pool = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ";
|
||||
let idx = rng.random_range(0..pool.len());
|
||||
output.push(pool.chars().nth(idx).unwrap());
|
||||
}
|
||||
_ => output.push(c),
|
||||
}
|
||||
let pool = match c {
|
||||
'n' => Some(DIGITS),
|
||||
'l' => Some(LETTERS_LOWER),
|
||||
'L' => Some(LETTERS_UPPER),
|
||||
'a' => Some(ALNUM_LOWER),
|
||||
'A' => Some(ALNUM_UPPER),
|
||||
_ => None,
|
||||
};
|
||||
|
||||
output.push(match pool {
|
||||
Some(p) => pick(&mut rng, p),
|
||||
None => c,
|
||||
});
|
||||
}
|
||||
output
|
||||
}
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue