hippofish/packages/backend/native-utils/crates/util/src/id.rs

40 lines
1.1 KiB
Rust
Raw Normal View History

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)]
mod tests {
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-26 10:00:09 +02:00
fn can_generate() {
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
}
}