atomic_snowflake/ulid/impl.rs
1use super::*;
2
3/// Core constructors and zero-allocation Crockford Base32 codecs for [`Ulid`].
4impl Ulid {
5 /// Wraps a raw 128-bit integer as a [`Ulid`].
6 ///
7 /// # Arguments
8 ///
9 /// - `u128` - Raw 128-bit ULID integer.
10 ///
11 /// # Returns
12 ///
13 /// - `Self` - The typed ULID wrapper.
14 #[inline(always)]
15 pub const fn from_u128(raw: u128) -> Self {
16 Self { raw }
17 }
18
19 /// Returns the raw 128-bit integer representation.
20 ///
21 /// # Returns
22 ///
23 /// - `u128` - Underlying 128-bit ULID integer.
24 #[inline(always)]
25 pub const fn as_u128(self) -> u128 {
26 let Self { raw } = self;
27 raw
28 }
29
30 /// Constructs a [`Ulid`] from a 48-bit Unix millisecond timestamp and 80-bit random payload.
31 ///
32 /// # Arguments
33 ///
34 /// - `u64` - Unix timestamp in milliseconds (masked to 48 bits).
35 /// - `u128` - 80-bit randomness payload (masked to lower 80 bits).
36 ///
37 /// # Returns
38 ///
39 /// - `Self` - Composed ULID.
40 #[inline(always)]
41 pub const fn from_parts(timestamp_ms: u64, random_80: u128) -> Self {
42 let ts: u128 = (timestamp_ms & ULID_TS_MASK_48) as u128;
43 let rnd: u128 = random_80 & ((1u128 << 80) - 1);
44 Self {
45 raw: (ts << 80) | rnd,
46 }
47 }
48
49 /// Returns the 48-bit Unix millisecond timestamp component.
50 ///
51 /// # Returns
52 ///
53 /// - `u64` - Unix timestamp in milliseconds.
54 #[inline(always)]
55 pub const fn timestamp_ms(self) -> u64 {
56 (self.as_u128() >> 80) as u64
57 }
58
59 /// Returns the 80-bit random/monotonic payload component.
60 ///
61 /// # Returns
62 ///
63 /// - `u128` - Lower 80 bits of the ULID.
64 #[inline(always)]
65 pub const fn random(self) -> u128 {
66 self.as_u128() & ((1u128 << 80) - 1)
67 }
68
69 /// Returns the 16-byte big-endian byte array of the ULID.
70 ///
71 /// # Returns
72 ///
73 /// - `[u8; 16]` - Big-endian ULID bytes.
74 #[inline(always)]
75 pub const fn to_bytes(self) -> [u8; 16] {
76 self.as_u128().to_be_bytes()
77 }
78
79 /// Reconstructs a [`Ulid`] from a 16-byte big-endian array.
80 ///
81 /// # Arguments
82 ///
83 /// - `[u8; 16]` - Big-endian ULID bytes.
84 ///
85 /// # Returns
86 ///
87 /// - `Self` - Reconstructed ULID.
88 #[inline(always)]
89 pub const fn from_bytes(bytes: [u8; 16]) -> Self {
90 Self {
91 raw: u128::from_be_bytes(bytes),
92 }
93 }
94
95 /// Encodes the ULID into a 26-byte ASCII Crockford Base32 stack array with zero heap allocation.
96 ///
97 /// # Returns
98 ///
99 /// - `[u8; ULID_STR_LEN]` - Canonical uppercase 26-byte Crockford Base32 array.
100 #[inline(always)]
101 pub const fn encode_stack(self) -> [u8; ULID_STR_LEN] {
102 let mut out: [u8; ULID_STR_LEN] = [b'0'; ULID_STR_LEN];
103 let mut val: u128 = self.as_u128();
104 let mut idx: usize = ULID_STR_LEN;
105 while idx > 0 {
106 idx -= 1;
107 out[idx] = CROCKFORD_ENCODE[(val & 0x1f) as usize];
108 val >>= 5;
109 }
110 out
111 }
112
113 /// Parses a 26-character Crockford Base32 ULID string (case-insensitive, `I`/`L`/`O` tolerant).
114 ///
115 /// # Arguments
116 ///
117 /// - `&str` - The 26-character ULID string.
118 ///
119 /// # Returns
120 ///
121 /// - `Result<Self, IdError>` - The parsed ULID or an error on invalid length, character, or overflow.
122 pub fn parse(input: &str) -> Result<Self, IdError> {
123 let bytes: &[u8] = input.as_bytes();
124 if bytes.len() != ULID_STR_LEN {
125 return Err(IdError::InvalidUlidLength);
126 }
127 let first: u8 = CROCKFORD_DECODE[bytes[0] as usize];
128 if first == 0xff {
129 return Err(IdError::InvalidUlidCharacter);
130 }
131 if first > 7 {
132 return Err(IdError::UlidOverflow);
133 }
134 let mut acc: u128 = u128::from(first);
135 let mut idx: usize = 1;
136 while idx < ULID_STR_LEN {
137 let digit: u8 = CROCKFORD_DECODE[bytes[idx] as usize];
138 if digit == 0xff {
139 return Err(IdError::InvalidUlidCharacter);
140 }
141 acc = (acc << 5) | u128::from(digit);
142 idx += 1;
143 }
144 Ok(Self { raw: acc })
145 }
146}
147
148/// Formats [`Ulid`] as a 26-character uppercase Crockford Base32 string.
149impl fmt::Display for Ulid {
150 /// Writes the canonical 26-character ULID string into `f`.
151 ///
152 /// # Arguments
153 ///
154 /// - `&mut fmt::Formatter<'_>` - Destination formatter.
155 ///
156 /// # Returns
157 ///
158 /// - `fmt::Result` - Formatting outcome.
159 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
160 let buf: [u8; ULID_STR_LEN] = self.encode_stack();
161 let text: &str = from_utf8(&buf).unwrap_or_default();
162 f.write_str(text)
163 }
164}
165
166/// Parses a Crockford Base32 string into a [`Ulid`].
167impl FromStr for Ulid {
168 type Err = IdError;
169
170 /// Parses a 26-character ULID string.
171 ///
172 /// # Arguments
173 ///
174 /// - `&str` - Input ULID text.
175 ///
176 /// # Returns
177 ///
178 /// - `Result<Self, Self::Err>` - Parsed ULID or error.
179 fn from_str(s: &str) -> Result<Self, Self::Err> {
180 Self::parse(s)
181 }
182}
183
184/// Default construction for [`UlidGenerator`].
185impl Default for UlidGenerator {
186 /// Creates a new [`UlidGenerator`] seeded from wall-clock entropy and stack address.
187 ///
188 /// # Returns
189 ///
190 /// - `Self` - Ready lock-free ULID generator.
191 fn default() -> Self {
192 Self::new()
193 }
194}
195
196/// Lock-free monotonic generation methods for [`UlidGenerator`].
197impl UlidGenerator {
198 /// Creates a new lock-free [`UlidGenerator`] seeded from system time and instance address.
199 ///
200 /// # Returns
201 ///
202 /// - `Self` - Ready lock-free ULID generator.
203 pub fn new() -> Self {
204 let now_nanos: u64 = match SystemTime::now().duration_since(UNIX_EPOCH) {
205 Ok(d) => d.as_nanos() as u64,
206 Err(_) => 0x243f_6a88_85a3_08d3,
207 };
208 let stack_addr: u64 = (&now_nanos as *const u64) as usize as u64;
209 Self::with_seed(splitmix64(now_nanos ^ stack_addr.rotate_left(17)))
210 }
211
212 /// Creates a deterministic [`UlidGenerator`] with an explicit 64-bit initial entropy seed.
213 ///
214 /// # Arguments
215 ///
216 /// - `u64` - Initial 64-bit PRNG seed.
217 ///
218 /// # Returns
219 ///
220 /// - `Self` - Ready ULID generator.
221 pub fn with_seed(seed: u64) -> Self {
222 Self {
223 hi_state: AtomicU64::new(0),
224 lo_state: AtomicU64::new(0),
225 seed: AtomicU64::new(seed),
226 }
227 }
228
229 /// Generates the next strictly monotonic [`Ulid`] using the current system clock.
230 ///
231 /// # Returns
232 ///
233 /// - `Ulid` - A unique, monotonically increasing ULID.
234 #[inline(always)]
235 pub fn next_ulid(&self) -> Ulid {
236 self.next_ulid_at(current_unix_ms())
237 }
238
239 /// Generates the next strictly monotonic [`Ulid`] at an explicit Unix millisecond timestamp.
240 ///
241 /// # Arguments
242 ///
243 /// - `u64` - Unix timestamp in milliseconds.
244 ///
245 /// # Returns
246 ///
247 /// - `Ulid` - A unique, monotonically increasing ULID.
248 #[inline(always)]
249 pub fn next_ulid_at(&self, now_unix_ms: u64) -> Ulid {
250 let Self {
251 hi_state,
252 lo_state,
253 seed,
254 } = self;
255 let ts_48: u64 = now_unix_ms & ULID_TS_MASK_48;
256 let mut observed_hi: u64 = hi_state.load(Ordering::Relaxed);
257 loop {
258 let last_ts: u64 = observed_hi >> 16;
259 if ts_48 > last_ts {
260 let s1: u64 = seed.fetch_add(0x9e37_79b9_7f4a_7c15, Ordering::Relaxed);
261 let r_lo: u64 = splitmix64(s1 ^ ts_48);
262 let r_hi: u64 = splitmix64(r_lo) & 0x7fff;
263 let new_hi: u64 = (ts_48 << 16) | r_hi;
264 match hi_state.compare_exchange_weak(
265 observed_hi,
266 new_hi,
267 Ordering::AcqRel,
268 Ordering::Relaxed,
269 ) {
270 Ok(_) => {
271 lo_state.store(r_lo, Ordering::Release);
272 let raw: u128 = (u128::from(new_hi) << 64) | u128::from(r_lo);
273 return Ulid::from_u128(raw);
274 }
275 Err(actual) => observed_hi = actual,
276 }
277 } else {
278 let prev_lo: u64 = lo_state.fetch_add(1, Ordering::AcqRel);
279 let next_lo: u64 = prev_lo.wrapping_add(1);
280 if next_lo != 0 {
281 let current_hi: u64 = hi_state.load(Ordering::Acquire);
282 let raw: u128 = (u128::from(current_hi) << 64) | u128::from(next_lo);
283 return Ulid::from_u128(raw);
284 }
285 let next_hi_val: u64 = observed_hi.wrapping_add(1);
286 let next_ts: u64 = (next_hi_val >> 16) & ULID_TS_MASK_48;
287 let next_r_hi: u64 = next_hi_val & ULID_RAND_HI_MASK_16;
288 let packed: u64 = (next_ts << 16) | next_r_hi;
289 match hi_state.compare_exchange_weak(
290 observed_hi,
291 packed,
292 Ordering::AcqRel,
293 Ordering::Relaxed,
294 ) {
295 Ok(_) => {
296 let raw: u128 = (u128::from(packed) << 64) | u128::from(next_lo);
297 return Ulid::from_u128(raw);
298 }
299 Err(actual) => observed_hi = actual,
300 }
301 }
302 }
303 }
304}