Skip to main content

alun_utils/
sid.rs

1//! 短 ID 生成器:基于 UUID v4/v7 或雪花算法
2
3use uuid::Uuid;
4use std::time::{SystemTime, UNIX_EPOCH};
5
6/// 短 ID 生成器
7///
8/// 提供 UUID v4/v7、雪花风格 TSID、短 ID、微型 ID 等分布式唯一标识生成。
9pub struct Sid;
10
11impl Sid {
12    /// 32 位 UUID(无连字符)
13    pub fn uuid() -> String { Uuid::new_v4().simple().to_string() }
14
15    /// 短 ID(16 位 hex)
16    pub fn short() -> String {
17        let u = Uuid::new_v4();
18        u.simple().to_string()[..16].to_string()
19    }
20
21    /// 极短 ID(8 位 hex)——用于临时标识
22    pub fn tiny() -> String {
23        let u = Uuid::new_v4();
24        u.simple().to_string()[..8].to_string()
25    }
26
27    /// 基于时间戳的 20 位短 ID(毫秒级唯一)
28    pub fn tsid() -> String {
29        let ts = SystemTime::now()
30            .duration_since(UNIX_EPOCH)
31            .unwrap()
32            .as_millis();
33        let rand: u32 = rand::random();
34        format!("{:013x}{:07x}", ts, rand & 0x0FFFFFFF)
35    }
36
37    /// UUID v7(时间有序,更适合数据库主键)
38    pub fn uuid7() -> String {
39        Uuid::now_v7().simple().to_string()
40    }
41}
42
43#[cfg(test)]
44mod tests {
45    use super::*;
46    #[test]
47    fn test_short() { assert_eq!(Sid::short().len(), 16); }
48    #[test]
49    fn test_tiny() { assert_eq!(Sid::tiny().len(), 8); }
50    #[test]
51    fn test_uuid() { assert_eq!(Sid::uuid().len(), 32); }
52}