rust_cutil/cutil/
generator.rs

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
use async_trait::async_trait;
use idgenerator_thin::{IdGeneratorOptions, YitIdHelper};
use once_cell::sync::Lazy;
use rand::distributions::Alphanumeric;
use rand::{thread_rng, Rng};
use crate::cutil::meta::R;

#[async_trait]
pub trait Generator: Send + Sync {
  async fn next_id(&self) -> R<i64>;
}

pub struct GeneratorImpl {}

impl GeneratorImpl {
  pub fn new() -> Self {
    Self {}
  }
}

impl GeneratorImpl {
  fn configure(&self) {
    let mut options = IdGeneratorOptions::new(1);
    options.worker_id_bit_length = 1;
    options.base_time = 1710034500000;
    YitIdHelper::set_id_generator(options);
  }
}

#[async_trait]
impl Generator for GeneratorImpl {
  async fn next_id(&self) -> R<i64> {
    Ok(YitIdHelper::next_id())
  }
}

static SHARED: Lazy<GeneratorImpl> = Lazy::new(|| {
  let gen = GeneratorImpl::new();
  gen.configure();
  gen
});

pub async fn next_id() -> R<i64> {
  SHARED.next_id().await
}

pub fn rand_string(length: usize) -> String {
  let rand_string: String = thread_rng().sample_iter(&Alphanumeric).take(length).map(char::from).collect();
  rand_string
}