30 lines
985 B
Rust
30 lines
985 B
Rust
use std::time::{SystemTime, UNIX_EPOCH, Duration};
|
|
use rand::Rng;
|
|
|
|
// Base-62 encoding characters
|
|
const BASE62: &[u8] = b"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";
|
|
|
|
// Convert a number to Base-62
|
|
fn to_base62(mut num: u64) -> String {
|
|
let mut result = String::new();
|
|
while num > 0 {
|
|
result.insert(0, BASE62[(num % 62) as usize] as char);
|
|
num /= 62;
|
|
}
|
|
result
|
|
}
|
|
|
|
// Generate an 8-character unique ID
|
|
fn generate_id() -> String {
|
|
let epoch_start = UNIX_EPOCH + Duration::from_secs(1577836800); // 2020-01-01
|
|
let now = SystemTime::now().duration_since(epoch_start).unwrap().as_millis();
|
|
let random: u64 = rand::thread_rng().gen_range(0..1000); // 3-digit random number
|
|
let id = now * 1000 + random; // Combine timestamp + randomness
|
|
let base62_id = to_base62(id);
|
|
format!("{:0>8}", base62_id)[..8].to_string() // Ensure 8 chars
|
|
}
|
|
|
|
fn main() {
|
|
println!("{}", generate_id()); // Example output: "9XcF7Bv2"
|
|
}
|