2023-05-26 10:00:09 +02:00
|
|
|
//! ID generation utility based on [cuid2]
|
|
|
|
|
|
|
|
use cuid2::CuidConstructor;
|
|
|
|
use once_cell::sync::OnceCell;
|
|
|
|
|
|
|
|
#[derive(thiserror::Error, Debug, PartialEq, Eq)]
|
|
|
|
#[error("ID generator has not been initialized yet")]
|
|
|
|
pub struct ErrorUninitialized;
|
|
|
|
|
|
|
|
static GENERATOR: OnceCell<CuidConstructor> = OnceCell::new();
|
|
|
|
|
|
|
|
pub fn init_id(length: u16) {
|
|
|
|
GENERATOR.get_or_init(move || CuidConstructor::new().with_length(length));
|
|
|
|
}
|
|
|
|
|
|
|
|
pub fn create_id() -> Result<String, ErrorUninitialized> {
|
|
|
|
match GENERATOR.get() {
|
|
|
|
None => Err(ErrorUninitialized),
|
|
|
|
Some(gen) => Ok(gen.create_id()),
|
|
|
|
}
|
2023-05-25 18:11:59 +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-26 10:00:09 +02:00
|
|
|
use std::thread;
|
2023-05-25 18:11:59 +02:00
|
|
|
|
2023-05-26 10:00:09 +02:00
|
|
|
use crate::id;
|
2023-05-25 18:11:59 +02:00
|
|
|
|
|
|
|
#[test]
|
2023-05-27 12:52:15 +02:00
|
|
|
fn can_generate_unique_ids() {
|
2023-05-26 10:00:09 +02:00
|
|
|
assert_eq!(id::create_id(), Err(id::ErrorUninitialized));
|
|
|
|
id::init_id(12);
|
|
|
|
assert_eq!(id::create_id().unwrap().len(), 12);
|
|
|
|
assert_ne!(id::create_id().unwrap(), id::create_id().unwrap());
|
|
|
|
let id1 = thread::spawn(|| id::create_id().unwrap());
|
|
|
|
let id2 = thread::spawn(|| id::create_id().unwrap());
|
|
|
|
assert_ne!(id1.join().unwrap(), id2.join().unwrap())
|
2023-05-25 18:11:59 +02:00
|
|
|
}
|
|
|
|
}
|