use std::sync::atomic::{AtomicU64, Ordering};
pub trait IdSource: Send + Sync {
fn generate(&self) -> String;
}
#[derive(Debug, Clone, Copy, Default)]
pub struct UuidIdSource;
impl IdSource for UuidIdSource {
fn generate(&self) -> String {
uuid::Uuid::new_v4().to_string()
}
}
#[derive(Debug, Default)]
pub struct SequentialIdSource {
counter: AtomicU64,
}
impl SequentialIdSource {
pub fn new() -> Self {
Self::default()
}
}
impl IdSource for SequentialIdSource {
fn generate(&self) -> String {
let n = self.counter.fetch_add(1, Ordering::Relaxed) + 1;
format!("00000000-0000-4000-8000-{n:012x}")
}
}
#[cfg(test)]
mod tests {
use std::sync::Arc;
use super::*;
#[test]
fn sequential_ids_are_stable_and_shared() {
let ids: Arc<dyn IdSource> = Arc::new(SequentialIdSource::new());
assert_eq!(ids.generate(), "00000000-0000-4000-8000-000000000001");
let shared = Arc::clone(&ids);
assert_eq!(shared.generate(), "00000000-0000-4000-8000-000000000002");
assert_eq!(ids.generate(), "00000000-0000-4000-8000-000000000003");
}
#[test]
fn uuid_ids_are_unique() {
let ids = UuidIdSource;
assert_ne!(ids.generate(), ids.generate());
}
}