rust_cutil/cutil/
generator.rs

1use crate::cutil::meta::R;
2use async_trait::async_trait;
3use idgenerator_thin::{IdGeneratorOptions, YitIdHelper};
4use once_cell::sync::Lazy;
5use rand::distr::Alphanumeric;
6use rand::{Rng, thread_rng};
7use ulid::Ulid;
8use uuid::Uuid;
9
10#[async_trait]
11pub trait Generator: Send + Sync {
12  async fn next_id(&self) -> R<i64>;
13}
14
15pub struct GeneratorImpl {}
16
17impl GeneratorImpl {
18  pub fn new() -> Self {
19    Self {}
20  }
21}
22
23impl GeneratorImpl {
24  fn configure(&self) {
25    let mut options = IdGeneratorOptions::new(1);
26    options.worker_id_bit_length = 1;
27    options.base_time = 1710034500000;
28    YitIdHelper::set_id_generator(options);
29  }
30}
31
32#[async_trait]
33impl Generator for GeneratorImpl {
34  async fn next_id(&self) -> R<i64> {
35    Ok(YitIdHelper::next_id())
36  }
37}
38
39static SHARED: Lazy<GeneratorImpl> = Lazy::new(|| {
40  let generator = GeneratorImpl::new();
41  generator.configure();
42  generator
43});
44
45pub async fn gen_id() -> R<i64> {
46  SHARED.next_id().await
47}
48
49pub fn gen_string(length: usize) -> String {
50  let rand_string: String = thread_rng().sample_iter(&Alphanumeric).take(length).map(char::from).collect();
51  rand_string
52}
53
54pub fn gen_ulid() -> String {
55  Ulid::new().to_string().to_lowercase()
56}
57
58pub fn gen_uuid() -> Uuid {
59  let ulid = Ulid::new();
60  ulid.into()
61}