use rand::Rng;
use std::sync::Mutex;
use std::sync::OnceLock;
use std::time::{SystemTime, UNIX_EPOCH};
use crate::Crypto;
pub struct Sid;
#[derive(Debug)]
struct Snowflake {
epoch: u64,
worker_id: u64,
last_timestamp: u64,
sequence: u16,
}
impl Snowflake {
fn new(worker_id: u64) -> Self {
let epoch = 1704067200000u64; Self {
epoch,
worker_id,
last_timestamp: 0,
sequence: 0,
}
}
fn next_id(&mut self) -> u64 {
let mut ts = Self::now_ms();
if ts < self.last_timestamp {
for _ in 0..10 {
ts = Self::now_ms();
if ts >= self.last_timestamp {
break;
}
std::thread::sleep(std::time::Duration::from_millis(1));
}
if ts < self.last_timestamp {
ts = self.last_timestamp;
}
}
if ts == self.last_timestamp {
self.sequence += 1;
if self.sequence >= 4096 {
loop {
ts = Self::now_ms();
if ts != self.last_timestamp {
break;
}
std::thread::sleep(std::time::Duration::from_millis(1));
}
self.sequence = 0;
self.last_timestamp = ts;
}
} else {
self.sequence = 0;
self.last_timestamp = ts;
}
((ts - self.epoch) << 22) | (self.worker_id << 12) | self.sequence as u64
}
fn now_ms() -> u64 {
SystemTime::now()
.duration_since(UNIX_EPOCH)
.unwrap()
.as_millis() as u64
}
}
static SNOWFLAKE: OnceLock<Mutex<Snowflake>> = OnceLock::new();
impl Sid {
pub fn init_snowflake(worker_id: u64) {
assert!(worker_id < 1024, "worker_id must be less than 1024");
SNOWFLAKE
.set(Mutex::new(Snowflake::new(worker_id)))
.expect("Snowflake already initialized");
}
pub fn snowflake() -> u64 {
SNOWFLAKE
.get()
.expect("Snowflake not initialized — call Sid::init_snowflake(worker_id) first")
.lock()
.expect("Snowflake mutex poisoned")
.next_id()
}
fn uuid_v4_bytes() -> [u8; 16] {
let mut b = [0u8; 16];
rand::thread_rng().fill(&mut b);
b[6] = (b[6] & 0x0f) | 0x40; b[8] = (b[8] & 0x3f) | 0x80; b
}
pub fn uuid() -> String {
Crypto::encode_hex(&Self::uuid_v4_bytes())
}
pub fn short() -> String {
Crypto::encode_hex(&Self::uuid_v4_bytes()[..8])
}
pub fn tiny() -> String {
Crypto::encode_hex(&Self::uuid_v4_bytes()[..4])
}
pub fn tsid() -> String {
let ts = SystemTime::now()
.duration_since(UNIX_EPOCH)
.unwrap()
.as_millis();
let rand: u32 = rand::random();
format!("{:013x}{:07x}", ts, rand & 0x0FFFFFFF)
}
pub fn uuid7() -> String {
let mut b = [0u8; 16];
let ms = SystemTime::now()
.duration_since(UNIX_EPOCH)
.unwrap()
.as_millis();
b[..6].copy_from_slice(&ms.to_be_bytes()[10..16]); let mut r = [0u8; 9];
rand::thread_rng().fill(&mut r);
b[6] = 0x70 | (r[0] >> 4); b[7] = (r[0] << 4) | (r[1] >> 4);
b[8] = (r[1] & 0x0f) | 0x80; b[9..].copy_from_slice(&r[2..]);
Crypto::encode_hex(&b)
}
pub fn biz_id(prefix: &str) -> String {
format!("{}_{}", prefix, Self::uuid7())
}
}
#[cfg(test)]
mod tests {
use super::*;
use std::collections::HashSet;
#[test]
fn test_snowflake_monotonic() {
let mut sf = Snowflake::new(1);
let a = sf.next_id();
let b = sf.next_id();
assert!(b > a);
}
#[test]
fn test_snowflake_no_duplicates() {
let mut sf = Snowflake::new(42);
let mut set = HashSet::new();
for _ in 0..10_000 {
let id = sf.next_id();
assert!(set.insert(id), "Duplicate snowflake ID: {}", id);
}
}
#[test]
fn test_short() {
assert_eq!(Sid::short().len(), 16);
}
#[test]
fn test_tiny() {
assert_eq!(Sid::tiny().len(), 8);
}
#[test]
fn test_uuid() {
assert_eq!(Sid::uuid().len(), 32);
}
#[test]
fn test_uuid7() {
let id = Sid::uuid7();
assert_eq!(id.len(), 32);
assert_eq!(&id[12..13], "7");
}
#[test]
fn test_biz_id() {
let id = Sid::biz_id("ORD");
assert!(id.starts_with("ORD_"));
assert_eq!(id.len(), 4 + 32); }
}