implemented count for pattern generation tokens
This commit is contained in:
parent
a38fb7aa9d
commit
2c11db2d28
1 changed files with 41 additions and 10 deletions
|
|
@ -29,15 +29,12 @@ Pattern Tokens:
|
||||||
X hex mixed (0-9, a-f, A-F)
|
X hex mixed (0-9, a-f, A-F)
|
||||||
* any other character is used literally";
|
* any other character is used literally";
|
||||||
|
|
||||||
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::with_capacity(pattern.len());
|
let tokens = parse_pattern(pattern);
|
||||||
|
let mut output = String::with_capacity(tokens.iter().map(|(_, n)| n).sum());
|
||||||
|
|
||||||
for c in pattern.chars() {
|
for (c, count) in tokens {
|
||||||
let pool = match c {
|
let pool = match c {
|
||||||
'n' => Some(DIGITS),
|
'n' => Some(DIGITS),
|
||||||
'l' => Some(LETTERS_LOWER),
|
'l' => Some(LETTERS_LOWER),
|
||||||
|
|
@ -54,10 +51,44 @@ pub fn generate_from_pattern(pattern: &str) -> String {
|
||||||
_ => None,
|
_ => None,
|
||||||
};
|
};
|
||||||
|
|
||||||
|
for _ in 0..count {
|
||||||
output.push(match pool {
|
output.push(match pool {
|
||||||
Some(p) => pick(&mut rng, p),
|
Some(p) => pick(&mut rng, p),
|
||||||
None => c,
|
None => c,
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
}
|
||||||
output
|
output
|
||||||
}
|
}
|
||||||
|
|
||||||
|
fn pick(rng: &mut impl rand::Rng, pool: &[u8]) -> char {
|
||||||
|
pool[rng.random_range(0..pool.len())] as char
|
||||||
|
}
|
||||||
|
|
||||||
|
fn parse_pattern(pattern: &str) -> Vec<(char, usize)> {
|
||||||
|
let mut tokens = Vec::new();
|
||||||
|
let mut chars = pattern.chars().peekable();
|
||||||
|
|
||||||
|
while let Some(c) = chars.next() {
|
||||||
|
if chars.peek() == Some(&'{') {
|
||||||
|
chars.next();
|
||||||
|
|
||||||
|
let digits: String = chars.by_ref().take_while(|&x| x != '}').collect();
|
||||||
|
|
||||||
|
match digits.parse::<usize>() {
|
||||||
|
Ok(n) if n > 0 => tokens.push((c, n)),
|
||||||
|
_ => {
|
||||||
|
tokens.push((c, 1));
|
||||||
|
|
||||||
|
for d in digits.chars() {
|
||||||
|
tokens.push((d, 1));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
tokens.push((c, 1));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
tokens
|
||||||
|
}
|
||||||
|
|
|
||||||
Loading…
Add table
Add a link
Reference in a new issue