add random string generator

This commit is contained in:
Namekuji 2023-05-27 02:37:34 -04:00
parent 6bb8775b2e
commit f1f3e5976d
No known key found for this signature in database
GPG key ID: B541BD6E646CABC7
3 changed files with 27 additions and 0 deletions

View file

@ -8,4 +8,5 @@ edition = "2021"
[dependencies]
cuid2 = "0.1.0"
once_cell = "1.17.1"
rand = "0.8.5"
thiserror = "1.0.40"

View file

@ -1 +1,2 @@
pub mod id;
pub mod random;

View 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());
}
}