zero4rs 2.0.0

zero4rs is a powerful, pragmatic, and extremely fast web framework for Rust
Documentation
use lazy_static::lazy_static;

use std::sync::Mutex;

use harsh::Harsh;
use rand::Rng;

use base64::{alphabet, engine, Engine as _};

lazy_static! {
    // 在 Rust 中,lazy_static 可以用来初始化一个 mut 变量,但是该变量必须包裹在一个 Mutex 或 RwLock 中,以确保线程安全性。
    static ref SNOWFLAKE: Mutex<rustflake::Snowflake> = Mutex::new(rustflake::Snowflake::default());
}

// 生成一个有序的字符串id
pub fn string_id() -> String {
    format!("{}", mongodb::bson::oid::ObjectId::new())
}

pub fn random_id() -> String {
    Harsh::default().encode(&[long_id().try_into().unwrap()])
}

pub fn base64_uuid() -> String {
    let mut b: [u8; 16] = [0; 16];
    rand::rng().fill(&mut b);

    // Set the version (4 bits) and variant (2 bits)
    b[6] = (b[6] & 0x0F) | 0x40;
    b[8] = (b[8] & 0x3F) | 0x80;

    // remove: + and /
    engine::GeneralPurpose::new(&alphabet::URL_SAFE, engine::general_purpose::NO_PAD).encode(b)
}

pub fn long_id() -> i64 {
    let mut m = SNOWFLAKE.lock().unwrap();
    m.generate()
}

#[deprecated(since = "0.0.0")]
pub fn ytid() -> String {
    let v = alphaid::AlphaId::<u64>::new()
        .encode(long_id() as u64)
        .unwrap();

    unsafe { std::str::from_utf8_unchecked(&v).to_string() }
}