change aid to cuid2
This commit is contained in:
parent
eda1e7ab3b
commit
6bb8775b2e
@ -6,6 +6,6 @@ edition = "2021"
|
|||||||
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
|
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
|
||||||
|
|
||||||
[dependencies]
|
[dependencies]
|
||||||
chrono = "0.4.24"
|
cuid2 = "0.1.0"
|
||||||
radix_fmt = "1.0.0"
|
once_cell = "1.17.1"
|
||||||
rand = "0.8.5"
|
thiserror = "1.0.40"
|
||||||
|
@ -1,31 +1,39 @@
|
|||||||
use chrono::{DateTime, Utc};
|
//! ID generation utility based on [cuid2]
|
||||||
use radix_fmt::radix_36;
|
|
||||||
|
|
||||||
const TIME_2000: i64 = 946_684_800_000;
|
use cuid2::CuidConstructor;
|
||||||
|
use once_cell::sync::OnceCell;
|
||||||
|
|
||||||
/// FIXME: Should we continue aid, or use other (more secure and scalable) guids
|
#[derive(thiserror::Error, Debug, PartialEq, Eq)]
|
||||||
/// such as [Cuid2](https://github.com/paralleldrive/cuid2)?
|
#[error("ID generator has not been initialized yet")]
|
||||||
pub fn create_aid(date: DateTime<Utc>) -> String {
|
pub struct ErrorUninitialized;
|
||||||
let time = date.timestamp_millis() - TIME_2000;
|
|
||||||
let time = if time < 0 { 0 } else { time };
|
static GENERATOR: OnceCell<CuidConstructor> = OnceCell::new();
|
||||||
let num: i16 = rand::random();
|
|
||||||
let mut noise = format!("{:0>2}", radix_36(num).to_string());
|
pub fn init_id(length: u16) {
|
||||||
let noise = noise.split_off(noise.len() - 2);
|
GENERATOR.get_or_init(move || CuidConstructor::new().with_length(length));
|
||||||
format!("{:0>8}{}", radix_36(time).to_string(), noise,)
|
}
|
||||||
|
|
||||||
|
pub fn create_id() -> Result<String, ErrorUninitialized> {
|
||||||
|
match GENERATOR.get() {
|
||||||
|
None => Err(ErrorUninitialized),
|
||||||
|
Some(gen) => Ok(gen.create_id()),
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
#[cfg(test)]
|
#[cfg(test)]
|
||||||
mod tests {
|
mod tests {
|
||||||
use chrono::{TimeZone, Utc};
|
use std::thread;
|
||||||
|
|
||||||
use super::create_aid;
|
use crate::id;
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
fn generate_aid() {
|
fn can_generate() {
|
||||||
let date = Utc.with_ymd_and_hms(2023, 5, 25, 11, 49, 37).unwrap();
|
assert_eq!(id::create_id(), Err(id::ErrorUninitialized));
|
||||||
let aid = create_aid(date);
|
id::init_id(12);
|
||||||
assert_eq!(aid.len(), 10);
|
assert_eq!(id::create_id().unwrap().len(), 12);
|
||||||
assert!(aid.starts_with("9f6mynag"));
|
assert_ne!(id::create_id().unwrap(), id::create_id().unwrap());
|
||||||
assert_ne!(create_aid(Utc::now()), create_aid(Utc::now()));
|
let id1 = thread::spawn(|| id::create_id().unwrap());
|
||||||
|
let id2 = thread::spawn(|| id::create_id().unwrap());
|
||||||
|
assert_ne!(id1.join().unwrap(), id2.join().unwrap())
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
Loading…
Reference in New Issue
Block a user