1use std::sync::atomic::{AtomicU64, Ordering};
12
13pub trait IdSource: Send + Sync {
15 fn generate(&self) -> String;
17}
18
19#[derive(Debug, Clone, Copy, Default)]
21pub struct UuidIdSource;
22
23impl IdSource for UuidIdSource {
24 fn generate(&self) -> String {
25 uuid::Uuid::new_v4().to_string()
26 }
27}
28
29#[derive(Debug, Default)]
32pub struct SequentialIdSource {
33 counter: AtomicU64,
34}
35
36impl SequentialIdSource {
37 pub fn new() -> Self {
38 Self::default()
39 }
40}
41
42impl IdSource for SequentialIdSource {
43 fn generate(&self) -> String {
44 let n = self.counter.fetch_add(1, Ordering::Relaxed) + 1;
45 format!("00000000-0000-4000-8000-{n:012x}")
46 }
47}
48
49#[cfg(test)]
50mod tests {
51 use std::sync::Arc;
52
53 use super::*;
54
55 #[test]
56 fn sequential_ids_are_stable_and_shared() {
57 let ids: Arc<dyn IdSource> = Arc::new(SequentialIdSource::new());
58 assert_eq!(ids.generate(), "00000000-0000-4000-8000-000000000001");
59 let shared = Arc::clone(&ids);
60 assert_eq!(shared.generate(), "00000000-0000-4000-8000-000000000002");
61 assert_eq!(ids.generate(), "00000000-0000-4000-8000-000000000003");
62 }
63
64 #[test]
65 fn uuid_ids_are_unique() {
66 let ids = UuidIdSource;
67 assert_ne!(ids.generate(), ids.generate());
68 }
69}