1use uuid::Uuid;
2use base62::encode;
3
4pub struct IdGenerator;
5
6impl IdGenerator {
7 pub fn get_id() -> Box<str> {
8 let uuid = Uuid::new_v4();
9 let num = u128::from_be_bytes(*uuid.as_bytes());
10 encode(num).into_boxed_str()
11 }
12}
13
14#[cfg(test)]
15mod tests {
16 use super::*;
17 use std::time::Instant;
18 #[test]
19 fn test_id_generation() {
20 let _id = IdGenerator::get_id();
21 println!("生成新ID: {_id:?}");
22 }
23 #[test]
24 fn test_id_generation_performance() {
25 const ITERATIONS: usize = 1_000_000;
26
27 let start = Instant::now();
29 for _ in 0..ITERATIONS {
30 let _id = IdGenerator::get_id();
31 }
32 let new_duration = start.elapsed();
33
34 println!("生成 {ITERATIONS} 个新ID耗时: {new_duration:?}");
35 println!("平均每个ID生成时间: {:?}", new_duration / ITERATIONS as u32);
36 }
37
38 #[test]
39 fn test_id_uniqueness() {
40 const ITERATIONS: usize = 1_000_000;
41 let mut ids = std::collections::HashSet::with_capacity(ITERATIONS);
42
43 for _ in 0..ITERATIONS {
45 let id = IdGenerator::get_id();
46 assert!(ids.insert(id), "发现重复ID!");
47 }
48
49 println!("成功生成 {ITERATIONS} 个唯一ID");
50
51 let total_possible = 32u64.pow(12);
53 let collision_probability =
54 1.0 - (1.0 - 1.0 / (total_possible as f64)).powi(ITERATIONS as i32);
55 println!("理论碰撞概率: {:.10}%", collision_probability * 100.0);
56 }
57}