Skip to content

Commit

Permalink
Add new method, replace_chars_prob.
Browse files Browse the repository at this point in the history
  • Loading branch information
Absolucy committed Apr 15, 2024
1 parent 0e78524 commit ef216c9
Show file tree
Hide file tree
Showing 2 changed files with 57 additions and 2 deletions.
29 changes: 28 additions & 1 deletion crates/rand/src/global/string.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,9 @@
// SPDX-License-Identifier: MPL-2.0
use super::global;
use rand::{distributions::Alphanumeric, Rng};
use rand::{
distributions::{Alphanumeric, Bernoulli, Distribution},
Rng,
};

#[byond_fn]
pub fn random_string_alphanumeric(length: usize, secure: Option<bool>) -> String {
Expand All @@ -9,3 +12,27 @@ pub fn random_string_alphanumeric(length: usize, secure: Option<bool>) -> String
.map(|_| rng.sample(Alphanumeric) as char)
.collect()
}

#[byond_fn]
pub fn replace_chars_prob(
input: String,
replacement: String,
prob: f32,
secure: Option<bool>,
) -> String {
if prob <= 0.0 {
return input;
}
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) {
output.push_str(&replacement);
} else {
output.push(c);
}
});
output
}
30 changes: 29 additions & 1 deletion crates/rand/src/instance/string.rs
Original file line number Diff line number Diff line change
@@ -1,7 +1,10 @@
// SPDX-License-Identifier: MPL-2.0
use super::INSTANCES;
use aneri_core::ByondSlotKey;
use rand::{distributions::Alphanumeric, Rng};
use rand::{
distributions::{Alphanumeric, Bernoulli, Distribution},
Rng,
};

#[byond_fn]
pub fn instanced_random_string_alphanumeric(src: ByondSlotKey, length: usize) -> Option<String> {
Expand All @@ -11,3 +14,28 @@ pub fn instanced_random_string_alphanumeric(src: ByondSlotKey, length: usize) ->
.collect()
})
}

#[byond_fn]
pub fn instnaced_replace_chars_prob(
src: ByondSlotKey,
input: String,
replacement: String,
prob: f32,
) -> Option<String> {
if prob <= 0.0 {
return Some(input);
}
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) {
output.push_str(&replacement);
} else {
output.push(c);
}
});
output
})
}

0 comments on commit ef216c9

Please sign in to comment.