1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
pub mod async_generator {
use crate::common::SnowflakeState as Snowflake;
use crate::common::Result;
/// An asynchronous Snowflake ID generator using Tokio's Mutex for thread safety.
pub struct SnowflakeGenerator {
inner: std::sync::Arc<tokio::sync::Mutex<Snowflake>>,
}
impl SnowflakeGenerator {
/// Create a new asynchronous Snowflake ID generator.
///
/// # Arguments
/// * `epoch` - The custom epoch timestamp in milliseconds.
/// * `worker_id` - The worker ID (0-1023).
/// # Errors
/// Returns `SnowflakeError::WorkerIdOutOfRange` if the worker_id is out of range.
///
/// # Panics
/// Panics if the epoch is set in the future relative to the current system time.
pub fn new(epoch: i64, worker_id: u16) -> Result<Self> {
Ok(Self {
inner: std::sync::Arc::new(tokio::sync::Mutex::new(Snowflake::new(epoch, worker_id)?)),
})
}
/// Asynchronously generate a new Snowflake ID.
pub async fn generate_id(&self) -> i64 {
let mut guard = self.inner.lock().await;
guard.generate_id()
}
/// Decompose a Snowflake ID into its components.
pub async fn decompose(&self, id: i64) -> crate::common::SnowflakeDecomposed {
let guard = self.inner.lock().await;
guard.decompose(id)
}
}
impl Clone for SnowflakeGenerator {
fn clone(&self) -> Self {
Self {
inner: self.inner.clone(),
}
}
}
}
pub mod sync_generator {
use crate::common::SnowflakeState as Snowflake;
use crate::common::Result;
pub struct SnowflakeGenerator {
inner: std::sync::Arc<std::sync::Mutex<Snowflake>>,
}
impl SnowflakeGenerator {
/// Create a new synchronous Snowflake ID generator.
///
/// # Arguments
/// * `epoch` - The custom epoch timestamp in milliseconds.
/// * `worker_id` - The worker ID (0-1023).
/// # Errors
/// Returns `SnowflakeError::WorkerIdOutOfRange` if the worker_id is out of range.
///
/// # Panics
/// Panics if the epoch is set in the future relative to the current system time.
pub fn new(epoch: i64, worker_id: u16) -> Result<Self> {
Ok(Self {
inner: std::sync::Arc::new(std::sync::Mutex::new(Snowflake::new(epoch, worker_id)?)),
})
}
/// Generate a new Snowflake ID.
///
/// # Panics
/// Panics if the internal Mutex is poisoned.
pub fn generate_id(&self) -> i64 {
let mut guard = self.inner.lock();
match guard {
Ok(ref mut g) => g.generate_id(),
Err(e) => {
panic!("Mutex poisoned: {}", e);
},
}
}
/// Decompose a Snowflake ID into its components.
pub fn decompose(&self, id: i64) -> crate::common::SnowflakeDecomposed {
let guard = self.inner.lock();
match guard {
Ok(ref g) => g.decompose(id),
Err(e) => {
panic!("Mutex poisoned: {}", e);
},
}
}
}
impl Clone for SnowflakeGenerator {
fn clone(&self) -> Self {
Self {
inner: self.inner.clone(),
}
}
}
}