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] [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"

View File

@ -1 +1,2 @@
pub mod id; 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());
}
}