use std::sync::atomic::{AtomicU64, Ordering};
pub trait IdGenerator: Send + Sync {
fn next_id(&self) -> String;
}
pub struct AtomicIdGenerator {
prefix: String,
counter: AtomicU64,
}
impl AtomicIdGenerator {
pub fn new() -> Self {
Self::with_prefix("id")
}
pub fn with_prefix(prefix: impl Into<String>) -> Self {
Self {
prefix: prefix.into(),
counter: AtomicU64::new(0),
}
}
}
impl Default for AtomicIdGenerator {
fn default() -> Self {
Self::new()
}
}
impl IdGenerator for AtomicIdGenerator {
fn next_id(&self) -> String {
let sequence = self.counter.fetch_add(1, Ordering::SeqCst) + 1;
format!("{}-{sequence}", self.prefix)
}
}
#[derive(Default)]
pub struct UuidIdGenerator;
impl IdGenerator for UuidIdGenerator {
fn next_id(&self) -> String {
uuid::Uuid::new_v4().to_string()
}
}