snowflake_gen/generator/mod.rs
1use std::time::SystemTime;
2use crate::layout::BitLayout;
3
4pub mod components;
5pub mod creation;
6pub mod generation;
7pub mod decomposition;
8
9#[cfg(test)]
10pub mod tests;
11
12pub use components::SnowflakeComponents;
13
14/// A Snowflake ID generator with a configurable [`BitLayout`].
15///
16/// # Thread safety
17///
18/// `SnowflakeIdGenerator` is **not** `Send + Sync` by itself because its
19/// internal state is mutated on every call. Wrap it in a `Mutex` / `RwLock`
20/// when sharing across threads.
21///
22/// # Example — default layout
23///
24/// ```rust
25/// use snowflake_gen::SnowflakeIdGenerator;
26///
27/// let mut idgen = SnowflakeIdGenerator::new(1, 1).unwrap();
28/// let id = idgen.generate().unwrap();
29/// assert!(id > 0);
30/// ```
31#[derive(Copy, Clone, Debug)]
32pub struct SnowflakeIdGenerator {
33 /// Epoch used for timestamp calculations.
34 pub(crate) epoch: SystemTime,
35 /// Timestamp of the last generated ID (millis since epoch).
36 pub(crate) last_time_millis: i64,
37 /// The machine identifier baked into every ID.
38 pub(crate) machine_id: i64,
39 /// The node (worker) identifier baked into every ID.
40 pub(crate) node_id: i64,
41 /// Per-millisecond auto-increment counter.
42 pub(crate) idx: u32,
43 /// Bit layout governing field widths and shifts.
44 pub(crate) layout: BitLayout,
45}
46
47impl SnowflakeIdGenerator {
48 /// Returns a reference to the [`BitLayout`] in use.
49 #[inline]
50 pub fn layout(&self) -> &BitLayout {
51 &self.layout
52 }
53
54 /// Returns the epoch this generator was constructed with.
55 #[inline]
56 pub fn epoch(&self) -> SystemTime {
57 self.epoch
58 }
59
60 /// Returns the machine identifier.
61 #[inline]
62 pub fn machine_id(&self) -> i64 {
63 self.machine_id
64 }
65
66 /// Returns the node (worker) identifier.
67 #[inline]
68 pub fn node_id(&self) -> i64 {
69 self.node_id
70 }
71}