Skip to content

Commit

Permalink
Add skip_whitespace parameter to replace_chars_prob.
Browse files Browse the repository at this point in the history
  • Loading branch information
Absolucy committed Apr 15, 2024
1 parent 5474cd9 commit 630552e
Show file tree
Hide file tree
Showing 2 changed files with 6 additions and 2 deletions.
4 changes: 3 additions & 1 deletion crates/rand/src/global/string.rs
Original file line number Diff line number Diff line change
Expand Up @@ -18,17 +18,19 @@ pub fn replace_chars_prob(
input: String,
replacement: String,
prob: f32,
skip_whitespace: Option<bool>,
secure: Option<bool>,
) -> String {
if !prob.is_normal() || !prob.is_sign_positive() {
return input;
}
let skip_whitespace = skip_whitespace.unwrap_or(false);
let mut rng = global(secure);
let distro =
Bernoulli::new((prob as f64 / 100.0).clamp(0.0, 1.0)).expect("invalid probability, wtf???");
let mut output = String::with_capacity(input.len() * replacement.len()); // Allocate for worst case scenario.
input.chars().for_each(|c| {
if distro.sample(&mut rng) {
if (!skip_whitespace || !c.is_whitespace()) && distro.sample(&mut rng) {
output.push_str(&replacement);
} else {
output.push(c);
Expand Down
4 changes: 3 additions & 1 deletion crates/rand/src/instance/string.rs
Original file line number Diff line number Diff line change
Expand Up @@ -21,16 +21,18 @@ pub fn instnaced_replace_chars_prob(
input: String,
replacement: String,
prob: f32,
skip_whitespace: Option<bool>,
) -> Option<String> {
if !prob.is_normal() || !prob.is_sign_positive() {
return Some(input);
}
let skip_whitespace = skip_whitespace.unwrap_or(false);
INSTANCES.lock().get_mut(src).map(|rng| {
let distro = Bernoulli::new((prob as f64 / 100.0).clamp(0.0, 1.0))
.expect("invalid probability, wtf???");
let mut output = String::with_capacity(input.len() * replacement.len()); // Allocate for worst case scenario.
input.chars().for_each(|c| {
if distro.sample(rng) {
if (!skip_whitespace || !c.is_whitespace()) && distro.sample(rng) {
output.push_str(&replacement);
} else {
output.push(c);
Expand Down

0 comments on commit 630552e

Please sign in to comment.