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;
|
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 {
|
pub fn generate_from_pattern(pattern: &str) -> String {
|
||||||
let mut rng = rand::rng();
|
let mut rng = rand::rng();
|
||||||
let mut output = String::new();
|
let mut output = String::with_capacity(pattern.len());
|
||||||
|
|
||||||
for c in pattern.chars() {
|
for c in pattern.chars() {
|
||||||
match c {
|
let pool = match c {
|
||||||
'n' => output.push(rng.random_range('0'..='9')),
|
'n' => Some(DIGITS),
|
||||||
'l' => {
|
'l' => Some(LETTERS_LOWER),
|
||||||
let letter = rng.random_range('a'..='z');
|
'L' => Some(LETTERS_UPPER),
|
||||||
output.push(letter);
|
'a' => Some(ALNUM_LOWER),
|
||||||
}
|
'A' => Some(ALNUM_UPPER),
|
||||||
'L' => {
|
_ => None,
|
||||||
let letter = rng.random_range('A'..='Z');
|
};
|
||||||
output.push(letter);
|
|
||||||
}
|
output.push(match pool {
|
||||||
'a' => {
|
Some(p) => pick(&mut rng, p),
|
||||||
let pool = "0123456789abcdefghijklmnopqrstuvwxyz";
|
None => c,
|
||||||
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),
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
output
|
output
|
||||||
}
|
}
|
||||||
|
|
|
||||||
Loading…
Add table
Add a link
Reference in a new issue