add random string generator
This commit is contained in:
parent
6bb8775b2e
commit
f1f3e5976d
3 changed files with 27 additions and 0 deletions
|
@ -8,4 +8,5 @@ edition = "2021"
|
||||||
[dependencies]
|
[dependencies]
|
||||||
cuid2 = "0.1.0"
|
cuid2 = "0.1.0"
|
||||||
once_cell = "1.17.1"
|
once_cell = "1.17.1"
|
||||||
|
rand = "0.8.5"
|
||||||
thiserror = "1.0.40"
|
thiserror = "1.0.40"
|
||||||
|
|
|
@ -1 +1,2 @@
|
||||||
pub mod id;
|
pub mod id;
|
||||||
|
pub mod random;
|
||||||
|
|
25
packages/backend/native-utils/crates/util/src/random.rs
Normal file
25
packages/backend/native-utils/crates/util/src/random.rs
Normal file
|
@ -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());
|
||||||
|
}
|
||||||
|
}
|
Loading…
Reference in a new issue