atomic_snowflake/uuidv7/impl.rs
1use super::*;
2
3/// Core accessors and zero-allocation hex codecs for [`UuidV7`].
4impl UuidV7 {
5 /// Wraps a raw 128-bit integer as a [`UuidV7`].
6 ///
7 /// # Arguments
8 ///
9 /// - `u128` - Raw 128-bit UUID value.
10 ///
11 /// # Returns
12 ///
13 /// - `Self` - Typed UUIDv7 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 value.
20 ///
21 /// # Returns
22 ///
23 /// - `u128` - Underlying 128-bit value.
24 #[inline(always)]
25 pub const fn as_u128(self) -> u128 {
26 let Self { raw } = self;
27 raw
28 }
29
30 /// Returns the 16-byte big-endian representation.
31 ///
32 /// # Returns
33 ///
34 /// - `[u8; 16]` - Big-endian UUID bytes.
35 #[inline(always)]
36 pub const fn to_bytes(self) -> [u8; 16] {
37 self.as_u128().to_be_bytes()
38 }
39
40 /// Reconstructs a [`UuidV7`] from a 16-byte big-endian byte array.
41 ///
42 /// # Arguments
43 ///
44 /// - `[u8; 16]` - Big-endian UUID bytes.
45 ///
46 /// # Returns
47 ///
48 /// - `Self` - Reconstructed UUIDv7.
49 #[inline(always)]
50 pub const fn from_bytes(bytes: [u8; 16]) -> Self {
51 Self {
52 raw: u128::from_be_bytes(bytes),
53 }
54 }
55
56 /// Returns the embedded 48-bit Unix timestamp in milliseconds.
57 ///
58 /// # Returns
59 ///
60 /// - `u64` - Unix timestamp in milliseconds.
61 #[inline(always)]
62 pub const fn timestamp_ms(self) -> u64 {
63 (self.as_u128() >> 80) as u64
64 }
65
66 /// Returns the 4-bit UUID version nibble (`7` for valid RFC 9562 UUIDv7).
67 ///
68 /// # Returns
69 ///
70 /// - `u8` - Version field (`0..=15`).
71 #[inline(always)]
72 pub const fn version(self) -> u8 {
73 ((self.as_u128() >> 76) & 0x0f) as u8
74 }
75
76 /// Returns the 12-bit monotonic `rand_a` sequence counter.
77 ///
78 /// # Returns
79 ///
80 /// - `u16` - 12-bit sub-millisecond counter (`0..=4095`).
81 #[inline(always)]
82 pub const fn sequence(self) -> u16 {
83 ((self.as_u128() >> 64) & 0x0fff) as u16
84 }
85
86 /// Encodes the UUIDv7 into a canonical 36-byte hyphenated lowercase ASCII stack buffer.
87 ///
88 /// # Returns
89 ///
90 /// - `[u8; UUID_STR_LEN]` - Canonical `xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx` bytes.
91 #[inline(always)]
92 pub const fn encode_stack(self) -> [u8; UUID_STR_LEN] {
93 let bytes: [u8; 16] = self.to_bytes();
94 let mut out: [u8; UUID_STR_LEN] = [b'-'; UUID_STR_LEN];
95 let mut src: usize = 0;
96 let mut dst: usize = 0;
97 while src < 16 {
98 if src == 4 || src == 6 || src == 8 || src == 10 {
99 dst += 1;
100 }
101 let b: u8 = bytes[src];
102 out[dst] = HEX_LOWER[(b >> 4) as usize];
103 out[dst + 1] = HEX_LOWER[(b & 0x0f) as usize];
104 dst += 2;
105 src += 1;
106 }
107 out
108 }
109
110 /// Parses either a 36-character hyphenated UUID or a 32-character compact hex UUID.
111 ///
112 /// # Arguments
113 ///
114 /// - `&str` - Input UUID text.
115 ///
116 /// # Returns
117 ///
118 /// - `Result<Self, IdError>` - Parsed UUIDv7 or format error.
119 pub fn parse(input: &str) -> Result<Self, IdError> {
120 let bytes: &[u8] = input.as_bytes();
121 let hyphenated: bool = match bytes.len() {
122 36 => true,
123 32 => false,
124 _ => return Err(IdError::InvalidUuidFormat),
125 };
126 if hyphenated
127 && (bytes[8] != b'-' || bytes[13] != b'-' || bytes[18] != b'-' || bytes[23] != b'-')
128 {
129 return Err(IdError::InvalidUuidFormat);
130 }
131 let mut acc: u128 = 0;
132 for (idx, &ch) in bytes.iter().enumerate() {
133 if hyphenated && (idx == 8 || idx == 13 || idx == 18 || idx == 23) {
134 continue;
135 }
136 let nibble: u8 = match ch {
137 b'0'..=b'9' => ch - b'0',
138 b'a'..=b'f' => ch - b'a' + 10,
139 b'A'..=b'F' => ch - b'A' + 10,
140 _ => return Err(IdError::InvalidUuidFormat),
141 };
142 acc = (acc << 4) | u128::from(nibble);
143 }
144 Ok(Self { raw: acc })
145 }
146}
147
148/// Formats [`UuidV7`] as canonical lowercase hyphenated text.
149impl fmt::Display for UuidV7 {
150 /// Writes the 36-character hyphenated UUIDv7 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; UUID_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 UUID string into [`UuidV7`].
167impl FromStr for UuidV7 {
168 type Err = IdError;
169
170 /// Parses a hyphenated or compact hex UUID string.
171 ///
172 /// # Arguments
173 ///
174 /// - `&str` - UUID string.
175 ///
176 /// # Returns
177 ///
178 /// - `Result<Self, Self::Err>` - Parsed UUIDv7 or error.
179 fn from_str(s: &str) -> Result<Self, Self::Err> {
180 Self::parse(s)
181 }
182}
183
184/// Default construction for [`UuidV7Generator`].
185impl Default for UuidV7Generator {
186 /// Creates a new [`UuidV7Generator`] seeded from wall-clock entropy.
187 ///
188 /// # Returns
189 ///
190 /// - `Self` - Ready UUIDv7 generator.
191 fn default() -> Self {
192 Self::new()
193 }
194}
195
196/// Lock-free monotonic RFC 9562 UUIDv7 generation methods.
197impl UuidV7Generator {
198 /// Creates a new [`UuidV7Generator`] seeded from wall-clock time and stack address.
199 ///
200 /// # Returns
201 ///
202 /// - `Self` - Ready lock-free UUIDv7 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(_) => 0x1319_8a2e_0370_7344,
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(23)))
210 }
211
212 /// Creates a [`UuidV7Generator`] with an explicit initial 64-bit entropy seed.
213 ///
214 /// # Arguments
215 ///
216 /// - `u64` - Initial entropy seed.
217 ///
218 /// # Returns
219 ///
220 /// - `Self` - Ready UUIDv7 generator.
221 pub fn with_seed(seed: u64) -> Self {
222 Self {
223 state: AtomicU64::new(0),
224 seed: AtomicU64::new(seed),
225 }
226 }
227
228 /// Generates the next strictly monotonic RFC 9562 [`UuidV7`] using wall-clock time.
229 ///
230 /// # Returns
231 ///
232 /// - `UuidV7` - A unique, time-ordered UUIDv7.
233 #[inline(always)]
234 pub fn next_uuid(&self) -> UuidV7 {
235 self.next_uuid_at(current_unix_ms())
236 }
237
238 /// Generates the next strictly monotonic RFC 9562 [`UuidV7`] at an explicit Unix timestamp.
239 ///
240 /// # Arguments
241 ///
242 /// - `u64` - Unix timestamp in milliseconds.
243 ///
244 /// # Returns
245 ///
246 /// - `UuidV7` - A unique, time-ordered UUIDv7.
247 #[inline(always)]
248 pub fn next_uuid_at(&self, now_unix_ms: u64) -> UuidV7 {
249 let Self { state, seed } = self;
250 let ts_48: u64 = now_unix_ms & ULID_TS_MASK_48;
251 let mut observed: u64 = state.load(Ordering::Relaxed);
252 let (final_ts, seq): (u64, u64) = loop {
253 let last_ts: u64 = observed >> 12;
254 let last_seq: u64 = observed & UUID_V7_SEQ_MASK;
255 let (next_ts, next_seq): (u64, u64) = if ts_48 > last_ts {
256 (ts_48, 0)
257 } else if last_seq < UUID_V7_SEQ_MASK {
258 (last_ts, last_seq + 1)
259 } else {
260 ((last_ts + 1) & ULID_TS_MASK_48, 0)
261 };
262 let packed: u64 = (next_ts << 12) | next_seq;
263 match state.compare_exchange_weak(observed, packed, Ordering::AcqRel, Ordering::Relaxed)
264 {
265 Ok(_) => break (next_ts, next_seq),
266 Err(actual) => observed = actual,
267 }
268 };
269 let hi: u64 = ((final_ts << 16) | UUID_V7_VERSION_NIBBLE) | seq;
270 let entropy: u64 =
271 splitmix64(seed.fetch_add(0x9e37_79b9_7f4a_7c15, Ordering::Relaxed) ^ hi);
272 let lo: u64 = UUID_VARIANT_RFC4122_HI | (entropy & UUID_RAND_B_MASK);
273 UuidV7::from_u128((u128::from(hi) << 64) | u128::from(lo))
274 }
275}