db-cores 0.1.0

Database core utilities
Documentation
use encoding_rs::{BIG5, GBK, UTF_8};
use rand::Rng;
pub fn decode_auto(bytes: &[u8]) -> String {
    let decoders = vec![UTF_8, GBK, BIG5]; // 定义要尝试的编码列表
    for encoding in decoders {
        let (decoded, _, _) = encoding.decode(bytes);
        if !decoded.contains("") {
            return decoded.into_owned();
        }
    }
    String::new() // 如果所有编码都尝试过了仍然无法成功解码,则返回空字符串
}

pub fn _utc_ms_option() -> Option<i64> {
    Some(chrono::Utc::now().timestamp_millis())
}

pub fn nanoid2(length: Option<usize>) -> String {
    fn get_random_lowercase_letter() -> char {
        let mut rng = rand::rng(); // 随机生成一个小写字母(ASCII码从 97 到 122)
        let ascii_value = rng.random_range(97..=122); // 包括范围中的所有值
        ascii_value as u8 as char
    }
    let first_letter = get_random_lowercase_letter();
    let len = length.unwrap_or(21) - 1;
    let id = nanoid::nanoid!(len);
    format!("{}{}", first_letter, id) // 拼接结果字符串
}