From f1f3e5976d0991d5c3f4b7d228b03e4b4d58fa9a Mon Sep 17 00:00:00 2001 From: Namekuji Date: Sat, 27 May 2023 02:37:34 -0400 Subject: [PATCH] add random string generator --- .../native-utils/crates/util/Cargo.toml | 1 + .../native-utils/crates/util/src/lib.rs | 1 + .../native-utils/crates/util/src/random.rs | 25 +++++++++++++++++++ 3 files changed, 27 insertions(+) create mode 100644 packages/backend/native-utils/crates/util/src/random.rs diff --git a/packages/backend/native-utils/crates/util/Cargo.toml b/packages/backend/native-utils/crates/util/Cargo.toml index 3c28e248f9..ad5486b4b6 100644 --- a/packages/backend/native-utils/crates/util/Cargo.toml +++ b/packages/backend/native-utils/crates/util/Cargo.toml @@ -8,4 +8,5 @@ edition = "2021" [dependencies] cuid2 = "0.1.0" once_cell = "1.17.1" +rand = "0.8.5" thiserror = "1.0.40" diff --git a/packages/backend/native-utils/crates/util/src/lib.rs b/packages/backend/native-utils/crates/util/src/lib.rs index fd6bb6c432..1be5a7fd1f 100644 --- a/packages/backend/native-utils/crates/util/src/lib.rs +++ b/packages/backend/native-utils/crates/util/src/lib.rs @@ -1 +1,2 @@ pub mod id; +pub mod random; diff --git a/packages/backend/native-utils/crates/util/src/random.rs b/packages/backend/native-utils/crates/util/src/random.rs new file mode 100644 index 0000000000..fb2f021479 --- /dev/null +++ b/packages/backend/native-utils/crates/util/src/random.rs @@ -0,0 +1,25 @@ +use rand::{distributions::Alphanumeric, thread_rng, Rng}; + +pub fn gen_string(length: u16) -> String { + thread_rng() + .sample_iter(Alphanumeric) + .take(length.into()) + .map(char::from) + .collect() +} + +#[cfg(test)] +mod tests { + use std::thread; + + use super::gen_string; + + #[test] + fn can_generate_string() { + assert_eq!(gen_string(16).len(), 16); + assert_ne!(gen_string(16), gen_string(16)); + let s1 = thread::spawn(|| gen_string(16)); + let s2 = thread::spawn(|| gen_string(16)); + assert_ne!(s1.join().unwrap(), s2.join().unwrap()); + } +}