hippofish/packages/backend-rs/src/util/random.rs

37 lines
1 KiB
Rust
Raw Normal View History

2023-05-27 08:37:34 +02:00
use rand::{distributions::Alphanumeric, thread_rng, Rng};
2023-06-02 17:55:14 +02:00
/// Generate random string based on [thread_rng] and [Alphanumeric].
#[crate::export]
pub fn generate_secure_random_string(length: u16) -> String {
2023-05-27 08:37:34 +02:00
thread_rng()
.sample_iter(Alphanumeric)
.take(length.into())
.map(char::from)
.collect()
}
#[crate::export]
pub fn generate_user_token() -> String {
generate_secure_random_string(16)
2023-06-02 17:55:14 +02:00
}
2023-05-27 08:37:34 +02:00
#[cfg(test)]
2023-05-27 12:52:15 +02:00
mod unit_test {
2023-06-02 13:08:58 +02:00
use pretty_assertions::{assert_eq, assert_ne};
2023-05-27 08:37:34 +02:00
use std::thread;
use super::generate_secure_random_string;
2023-05-27 08:37:34 +02:00
#[test]
2023-05-27 12:52:15 +02:00
fn can_generate_unique_strings() {
assert_eq!(generate_secure_random_string(16).len(), 16);
assert_ne!(
generate_secure_random_string(16),
generate_secure_random_string(16)
);
let s1 = thread::spawn(|| generate_secure_random_string(16));
let s2 = thread::spawn(|| generate_secure_random_string(16));
2023-05-27 08:37:34 +02:00
assert_ne!(s1.join().unwrap(), s2.join().unwrap());
}
}