Skip to main content

atomic_snowflake/snowflake/
impl.rs

1use super::*;
2
3/// Accessors and codecs for [`SnowflakeId`].
4impl SnowflakeId {
5    /// Wraps a raw 64-bit integer as a [`SnowflakeId`].
6    ///
7    /// # Arguments
8    ///
9    /// - `u64` - The raw 64-bit Snowflake integer.
10    ///
11    /// # Returns
12    ///
13    /// - `Self` - The typed Snowflake ID wrapper.
14    #[inline(always)]
15    pub const fn from_u64(raw: u64) -> Self {
16        Self { raw }
17    }
18
19    /// Extracts the raw 64-bit integer value.
20    ///
21    /// # Returns
22    ///
23    /// - `u64` - The underlying 64-bit value.
24    #[inline(always)]
25    pub const fn as_u64(self) -> u64 {
26        let Self { raw } = self;
27        raw
28    }
29
30    /// Composes a [`SnowflakeId`] directly from its fields.
31    ///
32    /// # Arguments
33    ///
34    /// - `u64` - Milliseconds elapsed since the generator's custom epoch (masked to 41 bits).
35    /// - `u16` - 10-bit node identifier (`0..=1023`).
36    /// - `u16` - 12-bit sequence counter (`0..=4095`).
37    ///
38    /// # Returns
39    ///
40    /// - `Self` - The composed Snowflake identifier.
41    #[inline(always)]
42    pub const fn from_parts(relative_ms: u64, node_id: u16, sequence: u16) -> Self {
43        let raw: u64 = ((relative_ms & TIMESTAMP_MASK) << TIMESTAMP_SHIFT)
44            | ((node_id as u64 & NODE_MASK) << SEQUENCE_BITS)
45            | (sequence as u64 & SEQUENCE_MASK);
46        Self { raw }
47    }
48
49    /// Returns the 41-bit timestamp offset in milliseconds relative to the custom epoch.
50    ///
51    /// # Returns
52    ///
53    /// - `u64` - Elapsed milliseconds since custom epoch.
54    #[inline(always)]
55    pub const fn timestamp_offset_ms(self) -> u64 {
56        (self.as_u64() >> TIMESTAMP_SHIFT) & TIMESTAMP_MASK
57    }
58
59    /// Returns the Unix timestamp in milliseconds given the custom epoch.
60    ///
61    /// # Arguments
62    ///
63    /// - `u64` - The custom epoch in Unix milliseconds.
64    ///
65    /// # Returns
66    ///
67    /// - `u64` - The absolute Unix timestamp in milliseconds.
68    #[inline(always)]
69    pub const fn timestamp_ms(self, epoch_ms: u64) -> u64 {
70        epoch_ms.saturating_add(self.timestamp_offset_ms())
71    }
72
73    /// Returns the 10-bit node identifier embedded in the Snowflake ID.
74    ///
75    /// # Returns
76    ///
77    /// - `u16` - Node identifier in `0..=1023`.
78    #[inline(always)]
79    pub const fn node_id(self) -> u16 {
80        ((self.as_u64() >> SEQUENCE_BITS) & NODE_MASK) as u16
81    }
82
83    /// Returns the 12-bit sequence counter embedded in the Snowflake ID.
84    ///
85    /// # Returns
86    ///
87    /// - `u16` - Sequence number in `0..=4095`.
88    #[inline(always)]
89    pub const fn sequence(self) -> u16 {
90        (self.as_u64() & SEQUENCE_MASK) as u16
91    }
92
93    /// Encodes the Snowflake ID into a compact Base62 string.
94    ///
95    /// # Returns
96    ///
97    /// - `String` - Base62 textual encoding (1 to 11 ASCII characters).
98    pub fn to_base62(self) -> String {
99        let mut value: u64 = self.as_u64();
100        if value == 0 {
101            return String::from("0");
102        }
103        let mut buf: [u8; BASE62_STACK_CAP] = [0u8; BASE62_STACK_CAP];
104        let mut idx: usize = BASE62_STACK_CAP;
105        while value > 0 {
106            idx -= 1;
107            let rem: usize = (value % 62) as usize;
108            buf[idx] = BASE62_ALPHABET[rem];
109            value /= 62;
110        }
111        String::from_utf8_lossy(&buf[idx..]).into_owned()
112    }
113
114    /// Decodes a Base62 string back into a [`SnowflakeId`].
115    ///
116    /// # Arguments
117    ///
118    /// - `&str` - The Base62 encoded string.
119    ///
120    /// # Returns
121    ///
122    /// - `Result<Self, IdError>` - The decoded Snowflake ID or parse error.
123    pub fn from_base62(input: &str) -> Result<Self, IdError> {
124        if input.is_empty() || input.len() > BASE62_STACK_CAP {
125            return Err(IdError::InvalidSnowflakeString);
126        }
127        let mut acc: u64 = 0;
128        for &byte in input.as_bytes() {
129            let digit: u64 = match byte {
130                b'0'..=b'9' => u64::from(byte - b'0'),
131                b'A'..=b'Z' => u64::from(byte - b'A') + 10,
132                b'a'..=b'z' => u64::from(byte - b'a') + 36,
133                _ => return Err(IdError::InvalidSnowflakeString),
134            };
135            acc = acc
136                .checked_mul(62)
137                .and_then(|v: u64| v.checked_add(digit))
138                .ok_or(IdError::InvalidSnowflakeString)?;
139        }
140        Ok(Self::from_u64(acc))
141    }
142}
143
144/// Converts [`SnowflakeId`] into `u64`.
145impl From<SnowflakeId> for u64 {
146    /// Extracts the underlying 64-bit value.
147    ///
148    /// # Arguments
149    ///
150    /// - `SnowflakeId` - Source Snowflake identifier.
151    ///
152    /// # Returns
153    ///
154    /// - `u64` - Underlying 64-bit integer.
155    #[inline(always)]
156    fn from(id: SnowflakeId) -> Self {
157        id.as_u64()
158    }
159}
160
161/// Converts `u64` into [`SnowflakeId`].
162impl From<u64> for SnowflakeId {
163    /// Wraps a raw 64-bit integer.
164    ///
165    /// # Arguments
166    ///
167    /// - `u64` - Raw 64-bit integer.
168    ///
169    /// # Returns
170    ///
171    /// - `Self` - Typed Snowflake identifier.
172    #[inline(always)]
173    fn from(raw: u64) -> Self {
174        Self::from_u64(raw)
175    }
176}
177
178/// Formats [`SnowflakeId`] as a base-10 integer string.
179impl fmt::Display for SnowflakeId {
180    /// Writes the decimal representation of the Snowflake ID.
181    ///
182    /// # Arguments
183    ///
184    /// - `&mut fmt::Formatter<'_>` - Destination formatter.
185    ///
186    /// # Returns
187    ///
188    /// - `fmt::Result` - Formatting outcome.
189    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
190        write!(f, "{}", self.as_u64())
191    }
192}
193
194/// Parses a base-10 string into a [`SnowflakeId`].
195impl FromStr for SnowflakeId {
196    type Err = IdError;
197
198    /// Parses a decimal string into a [`SnowflakeId`].
199    ///
200    /// # Arguments
201    ///
202    /// - `&str` - Decimal string representation.
203    ///
204    /// # Returns
205    ///
206    /// - `Result<Self, Self::Err>` - Parsed Snowflake ID or error.
207    fn from_str(s: &str) -> Result<Self, Self::Err> {
208        let raw: u64 = s
209            .parse::<u64>()
210            .map_err(|_| IdError::InvalidSnowflakeString)?;
211        Ok(Self::from_u64(raw))
212    }
213}
214
215/// Lock-free ID generation methods for [`SnowflakeGenerator`].
216impl SnowflakeGenerator {
217    /// Creates a new generator with the default custom epoch (`2020-01-01T00:00:00Z`).
218    ///
219    /// # Arguments
220    ///
221    /// - `u16` - Unique node identifier in `0..=1023`.
222    ///
223    /// # Returns
224    ///
225    /// - `Result<Self, IdError>` - The ready generator or `IdError::NodeIdOutOfRange`.
226    pub fn new(node_id: u16) -> Result<Self, IdError> {
227        Self::with_epoch(node_id, DEFAULT_SNOWFLAKE_EPOCH_MS)
228    }
229
230    /// Creates a new generator with an explicit custom epoch in Unix milliseconds.
231    ///
232    /// # Arguments
233    ///
234    /// - `u16` - Unique node identifier in `0..=1023`.
235    /// - `u64` - Custom epoch in Unix milliseconds.
236    ///
237    /// # Returns
238    ///
239    /// - `Result<Self, IdError>` - The ready generator or `IdError::NodeIdOutOfRange`.
240    pub fn with_epoch(node_id: u16, epoch_ms: u64) -> Result<Self, IdError> {
241        if node_id > MAX_NODE_ID {
242            return Err(IdError::NodeIdOutOfRange);
243        }
244        Ok(Self {
245            epoch_ms,
246            node_id,
247            state: AtomicU64::new(0),
248        })
249    }
250
251    /// Returns the configured custom epoch in Unix milliseconds.
252    ///
253    /// # Returns
254    ///
255    /// - `u64` - Custom epoch timestamp in milliseconds.
256    #[inline(always)]
257    pub fn get_epoch_ms(&self) -> u64 {
258        let Self { epoch_ms, .. } = self;
259        *epoch_ms
260    }
261
262    /// Returns the configured 10-bit node identifier.
263    ///
264    /// # Returns
265    ///
266    /// - `u16` - Node identifier (`0..=1023`).
267    #[inline(always)]
268    pub fn get_node_id(&self) -> u16 {
269        let Self { node_id, .. } = self;
270        *node_id
271    }
272
273    /// Generates the next strictly monotonic 64-bit Snowflake ID using wall-clock time.
274    ///
275    /// Uses a single lock-free `AtomicU64` compare-exchange loop; clock rollbacks or
276    /// intra-millisecond sequence exhaustion advance the logical millisecond monotonically
277    /// without blocking or panicking.
278    ///
279    /// # Returns
280    ///
281    /// - `SnowflakeId` - A unique, strictly increasing Snowflake identifier.
282    #[inline(always)]
283    pub fn next_id(&self) -> SnowflakeId {
284        self.next_id_at(current_unix_ms())
285    }
286
287    /// Generates the next strictly monotonic 64-bit Snowflake ID at an explicit Unix timestamp.
288    ///
289    /// # Arguments
290    ///
291    /// - `u64` - Current Unix timestamp in milliseconds.
292    ///
293    /// # Returns
294    ///
295    /// - `SnowflakeId` - A unique, strictly increasing Snowflake identifier.
296    #[inline(always)]
297    pub fn next_id_at(&self, now_unix_ms: u64) -> SnowflakeId {
298        let Self {
299            epoch_ms,
300            node_id,
301            state,
302        } = self;
303        let rel_now: u64 = now_unix_ms.saturating_sub(*epoch_ms) & TIMESTAMP_MASK;
304        let mut observed: u64 = state.load(Ordering::Relaxed);
305        loop {
306            let last_ts: u64 = observed >> SEQUENCE_BITS;
307            let last_seq: u64 = observed & SEQUENCE_MASK;
308            let (next_ts, next_seq): (u64, u64) = if rel_now > last_ts {
309                (rel_now, 0)
310            } else if last_seq < SEQUENCE_MASK {
311                (last_ts, last_seq + 1)
312            } else {
313                ((last_ts + 1) & TIMESTAMP_MASK, 0)
314            };
315            let packed: u64 = (next_ts << SEQUENCE_BITS) | next_seq;
316            match state.compare_exchange_weak(observed, packed, Ordering::AcqRel, Ordering::Relaxed)
317            {
318                Ok(_) => {
319                    return SnowflakeId::from_parts(next_ts, *node_id, next_seq as u16);
320                }
321                Err(actual) => observed = actual,
322            }
323        }
324    }
325}