Skip to main content

logicaffeine_base/
uuid.rs

1//! UUID — a 128-bit universally-unique identifier (RFC 9562, superseding RFC 4122).
2//!
3//! Rolled in-house rather than wrapping a crate: the campaign builds first-class types, and owning the
4//! implementation is what lets us be byte-exact across every tier and benchmark it head-to-head. The
5//! value is a fixed `[u8; 16]` in network (big-endian) byte order, so it is `Copy`, `Ord` by bytes
6//! (which makes v6/v7 time-ordered ids sort chronologically), and hashes cheaply.
7//!
8//! Every standard version is here:
9//! - **nil** (all-zero) and **max** (all-one) — the two special ids.
10//! - **v1** (gregorian time + node) and **v6** (the same fields reordered to sort by time).
11//! - **v3** (MD5 of namespace ‖ name) and **v5** (SHA-1 of namespace ‖ name) — name-based, stable.
12//! - **v4** (random) and **v7** (Unix-millis time-ordered + random) — the two you reach for today.
13//! - **v8** (free-form / vendor-defined) — arbitrary bytes with the version+variant bits stamped.
14//!
15//! Generation takes the entropy/time as parameters (no ambient clock or RNG here) so it is pure and
16//! deterministic — the higher tiers seed it for byte-identical cross-tier output. Validated against
17//! the `uuid` crate (the name-based and random/time builders, parse, and display) in the tests.
18
19use core::fmt;
20
21use crate::hash::{md5, sha1};
22
23/// A 128-bit UUID, stored big-endian (RFC 9562 byte order).
24#[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
25pub struct Uuid([u8; 16]);
26
27/// Build `namespace ‖ name` and hand the slice to `f`, WITHOUT a heap allocation for any real name.
28/// A 240-byte inline stack buffer covers every practical v3/v5 input (DNS names, URLs, OIDs are far
29/// shorter); only a pathologically long name falls back to a `Vec`. The 16 namespace bytes always fit.
30#[inline]
31fn with_namespaced_input<R>(namespace: Uuid, name: &[u8], f: impl FnOnce(&[u8]) -> R) -> R {
32    const INLINE: usize = 256;
33    let total = 16 + name.len();
34    if total <= INLINE {
35        let mut buf = [0u8; INLINE];
36        buf[..16].copy_from_slice(&namespace.0);
37        buf[16..total].copy_from_slice(name);
38        f(&buf[..total])
39    } else {
40        let mut input = Vec::with_capacity(total);
41        input.extend_from_slice(&namespace.0);
42        input.extend_from_slice(name);
43        f(&input)
44    }
45}
46
47/// The RFC-defined variant of a UUID — which layout the variant/version bits follow.
48#[derive(Clone, Copy, PartialEq, Eq, Debug)]
49pub enum Variant {
50    /// Reserved, NCS backward compatibility (`0xx`).
51    Ncs,
52    /// The standard RFC 9562 / RFC 4122 layout (`10x`) — every version we generate.
53    Rfc4122,
54    /// Reserved, Microsoft GUID (`110`).
55    Microsoft,
56    /// Reserved for future definition (`111`).
57    Future,
58}
59
60impl Uuid {
61    /// The nil UUID — all 128 bits zero (`00000000-0000-0000-0000-000000000000`).
62    pub const NIL: Uuid = Uuid([0u8; 16]);
63    /// The max UUID — all 128 bits one (`ffffffff-ffff-ffff-ffff-ffffffffffff`), RFC 9562 §5.10.
64    pub const MAX: Uuid = Uuid([0xFFu8; 16]);
65
66    /// Namespace ID for fully-qualified domain names (RFC 9562 Appendix A).
67    pub const NAMESPACE_DNS: Uuid = Uuid([
68        0x6b, 0xa7, 0xb8, 0x10, 0x9d, 0xad, 0x11, 0xd1, 0x80, 0xb4, 0x00, 0xc0, 0x4f, 0xd4, 0x30,
69        0xc8,
70    ]);
71    /// Namespace ID for URLs.
72    pub const NAMESPACE_URL: Uuid = Uuid([
73        0x6b, 0xa7, 0xb8, 0x11, 0x9d, 0xad, 0x11, 0xd1, 0x80, 0xb4, 0x00, 0xc0, 0x4f, 0xd4, 0x30,
74        0xc8,
75    ]);
76    /// Namespace ID for ISO OIDs.
77    pub const NAMESPACE_OID: Uuid = Uuid([
78        0x6b, 0xa7, 0xb8, 0x12, 0x9d, 0xad, 0x11, 0xd1, 0x80, 0xb4, 0x00, 0xc0, 0x4f, 0xd4, 0x30,
79        0xc8,
80    ]);
81    /// Namespace ID for X.500 DNs.
82    pub const NAMESPACE_X500: Uuid = Uuid([
83        0x6b, 0xa7, 0xb8, 0x14, 0x9d, 0xad, 0x11, 0xd1, 0x80, 0xb4, 0x00, 0xc0, 0x4f, 0xd4, 0x30,
84        0xc8,
85    ]);
86
87    /// Wrap raw big-endian bytes verbatim (no version/variant stamping).
88    pub const fn from_bytes(bytes: [u8; 16]) -> Uuid {
89        Uuid(bytes)
90    }
91
92    /// The raw 16 big-endian bytes.
93    pub const fn to_bytes(self) -> [u8; 16] {
94        self.0
95    }
96
97    /// Borrow the raw 16 big-endian bytes.
98    pub const fn as_bytes(&self) -> &[u8; 16] {
99        &self.0
100    }
101
102    /// True for the all-zero nil UUID.
103    pub fn is_nil(&self) -> bool {
104        self.0 == [0u8; 16]
105    }
106
107    /// True for the all-one max UUID.
108    pub fn is_max(&self) -> bool {
109        self.0 == [0xFFu8; 16]
110    }
111
112    /// The version number (the high nibble of byte 6): 1–8 for the defined versions, 0 for nil,
113    /// 0xF for max. A pure read of the field — it does not assert the id was generated correctly.
114    pub fn version(&self) -> u8 {
115        self.0[6] >> 4
116    }
117
118    /// The variant (the high bits of byte 8). Everything we generate is [`Variant::Rfc4122`].
119    pub fn variant(&self) -> Variant {
120        let b = self.0[8];
121        if b & 0x80 == 0x00 {
122            Variant::Ncs
123        } else if b & 0xC0 == 0x80 {
124            Variant::Rfc4122
125        } else if b & 0xE0 == 0xC0 {
126            Variant::Microsoft
127        } else {
128            Variant::Future
129        }
130    }
131
132    /// Stamp the version nibble (byte 6) and the RFC-4122 variant bits (byte 8). Done as one `u128`
133    /// (register-resident) rather than two byte-indexed writes, so the value never spills to the stack:
134    /// byte 6's high nibble is bits `[76..80)` big-endian, byte 8's top two bits are `[62..64)`.
135    #[inline]
136    fn stamp(bytes: [u8; 16], version: u8) -> Uuid {
137        let mut v = u128::from_be_bytes(bytes);
138        v = (v & !(0xFu128 << 76)) | ((version as u128) << 76);
139        v = (v & !(0b11u128 << 62)) | (0b10u128 << 62);
140        Uuid(v.to_be_bytes())
141    }
142
143    /// Version 1: a 60-bit gregorian timestamp (100-ns ticks since 1582-10-15), a 14-bit clock
144    /// sequence, and a 48-bit node id. Layout is little-end-first on time (not time-sortable; that is
145    /// what v6 fixes).
146    pub fn new_v1(timestamp_100ns: u64, clock_seq: u16, node: [u8; 6]) -> Uuid {
147        let ts = timestamp_100ns & 0x0FFF_FFFF_FFFF_FFFF;
148        let time_low = (ts & 0xFFFF_FFFF) as u32;
149        let time_mid = ((ts >> 32) & 0xFFFF) as u16;
150        let time_hi = ((ts >> 48) & 0x0FFF) as u16;
151        let mut b = [0u8; 16];
152        b[0..4].copy_from_slice(&time_low.to_be_bytes());
153        b[4..6].copy_from_slice(&time_mid.to_be_bytes());
154        b[6..8].copy_from_slice(&time_hi.to_be_bytes());
155        b[8] = (clock_seq >> 8) as u8;
156        b[9] = (clock_seq & 0xFF) as u8;
157        b[10..16].copy_from_slice(&node);
158        Uuid::stamp(b, 1)
159    }
160
161    /// Version 6: the v1 fields with the timestamp reordered most-significant-first, so byte order
162    /// sorts chronologically (RFC 9562 §5.6) — a drop-in, sortable replacement for v1.
163    pub fn new_v6(timestamp_100ns: u64, clock_seq: u16, node: [u8; 6]) -> Uuid {
164        let ts = timestamp_100ns & 0x0FFF_FFFF_FFFF_FFFF;
165        let time_high = ((ts >> 28) & 0xFFFF_FFFF) as u32;
166        let time_mid = ((ts >> 12) & 0xFFFF) as u16;
167        let time_low = (ts & 0x0FFF) as u16;
168        let mut b = [0u8; 16];
169        b[0..4].copy_from_slice(&time_high.to_be_bytes());
170        b[4..6].copy_from_slice(&time_mid.to_be_bytes());
171        b[6..8].copy_from_slice(&time_low.to_be_bytes());
172        b[8] = (clock_seq >> 8) as u8;
173        b[9] = (clock_seq & 0xFF) as u8;
174        b[10..16].copy_from_slice(&node);
175        Uuid::stamp(b, 6)
176    }
177
178    /// Version 3: MD5 of `namespace` bytes followed by `name` (RFC 9562 §5.3). Name-based and stable —
179    /// the same namespace+name always yields the same id. This is the native REFERENCE ORACLE: the
180    /// language's `uuid_v3` is written in Logos (`assets/std/uuid.lg`, over the Logos `md5Digest`) and is
181    /// proven byte-exact against this and the `uuid`/`md-5` crates — it is not on any language path.
182    pub fn new_v3(namespace: Uuid, name: &[u8]) -> Uuid {
183        with_namespaced_input(namespace, name, |input| Uuid::stamp(md5(input), 3))
184    }
185
186    /// Version 5: SHA-1 of `namespace` bytes followed by `name`, truncated to 16 bytes (RFC 9562
187    /// §5.5). Name-based and stable; preferred over v3. The native REFERENCE ORACLE for the Logos
188    /// `uuid_v5` (uuid.lg, over `sha1Digest`) — see [`Uuid::new_v3`].
189    pub fn new_v5(namespace: Uuid, name: &[u8]) -> Uuid {
190        with_namespaced_input(namespace, name, |input| {
191            let digest = sha1(input);
192            let mut b = [0u8; 16];
193            b.copy_from_slice(&digest[..16]);
194            Uuid::stamp(b, 5)
195        })
196    }
197
198    /// Version 4: 122 bits of supplied randomness (RFC 9562 §5.4). The 6 version/variant bits are
199    /// overwritten, so all 16 bytes of entropy may be passed.
200    #[inline]
201    pub fn new_v4(random: [u8; 16]) -> Uuid {
202        Uuid::stamp(random, 4)
203    }
204
205    /// Version 7: a 48-bit big-endian Unix-millisecond timestamp followed by 74 bits of randomness
206    /// (RFC 9562 §5.7). Time-ordered (byte order sorts by creation time) — the modern default.
207    #[inline]
208    pub fn new_v7(unix_ms: u64, random: [u8; 10]) -> Uuid {
209        let mut b = [0u8; 16];
210        let ms = unix_ms & 0xFFFF_FFFF_FFFF;
211        b[0..6].copy_from_slice(&ms.to_be_bytes()[2..8]);
212        b[6..16].copy_from_slice(&random);
213        Uuid::stamp(b, 7)
214    }
215
216    /// Version 8: vendor/experimental — the 16 bytes are taken as given, with only the version and
217    /// variant bits stamped (RFC 9562 §5.8).
218    pub fn new_v8(bytes: [u8; 16]) -> Uuid {
219        Uuid::stamp(bytes, 8)
220    }
221
222    /// Parse a UUID from text. Accepts the canonical hyphenated form, the 32-hex simple form, the
223    /// braced `{…}` form, and the `urn:uuid:…` form; case-insensitive. Returns `None` on any other
224    /// shape, a bad length, or a non-hex digit — never panics.
225    pub fn parse(input: &str) -> Option<Uuid> {
226        let s = input.trim();
227        // Fast path: the canonical 36-char hyphenated form — the overwhelmingly common case. A
228        // byte-table hex decode with no per-char branching; any invalid digit poisons `bad` to ≥16.
229        if s.len() == 36 {
230            // Fast path: the canonical 36-char hyphenated form — the overwhelmingly common case.
231            return Self::parse_canonical(s.as_bytes().try_into().unwrap());
232        }
233        // Strip an optional `urn:uuid:` prefix (case-insensitive) and `{…}` braces.
234        let s = s
235            .strip_prefix("urn:uuid:")
236            .or_else(|| s.strip_prefix("URN:UUID:"))
237            .unwrap_or(s);
238        let s = s
239            .strip_prefix('{')
240            .and_then(|t| t.strip_suffix('}'))
241            .unwrap_or(s);
242
243        // Collect exactly the hex digits, rejecting any non-hyphen, non-hex character, and require the
244        // hyphens (when present) to sit at the canonical 8-4-4-4-12 positions.
245        let bytes = s.as_bytes();
246        let mut hex = [0u8; 32];
247        let mut n = 0usize;
248        match bytes.len() {
249            36 => {
250                // Canonical: hyphens at indices 8, 13, 18, 23.
251                for (i, &c) in bytes.iter().enumerate() {
252                    if matches!(i, 8 | 13 | 18 | 23) {
253                        if c != b'-' {
254                            return None;
255                        }
256                    } else {
257                        if n >= 32 {
258                            return None;
259                        }
260                        hex[n] = c;
261                        n += 1;
262                    }
263                }
264            }
265            32 => hex.copy_from_slice(bytes),
266            _ => return None,
267        }
268        if n != 0 && n != 32 {
269            return None;
270        }
271
272        let mut out = [0u8; 16];
273        for i in 0..16 {
274            let hi = hex_val(hex[2 * i])?;
275            let lo = hex_val(hex[2 * i + 1])?;
276            out[i] = (hi << 4) | lo;
277        }
278        Some(Uuid(out))
279    }
280
281    /// Decode one canonical 36-byte hyphenated record — the shared fast path behind [`Uuid::parse`] and
282    /// [`Uuid::parse_many`]. Checks the four hyphens, then the SIMD `pshufb` decode (statically dispatched
283    /// under `target-cpu=native`, runtime-detected otherwise, scalar-table fallback). `None` if malformed.
284    #[inline]
285    fn parse_canonical(arr: &[u8; 36]) -> Option<Uuid> {
286        if arr[8] != b'-' || arr[13] != b'-' || arr[18] != b'-' || arr[23] != b'-' {
287            return None;
288        }
289        #[cfg(all(target_arch = "x86_64", target_feature = "ssse3"))]
290        {
291            return unsafe { x86_hex::parse_hyphenated(arr) }.map(Uuid);
292        }
293        #[cfg(all(target_arch = "x86_64", not(target_feature = "ssse3")))]
294        {
295            if x86_hex::available() {
296                return unsafe { x86_hex::parse_hyphenated(arr) }.map(Uuid);
297            }
298        }
299        #[cfg(not(all(target_arch = "x86_64", target_feature = "ssse3")))]
300        {
301            let mut out = [0u8; 16];
302            let mut bad = 0u8;
303            // The 16 byte positions: pairs of hex indices, skipping the four hyphens.
304            const PAIRS: [usize; 16] = [0, 2, 4, 6, 9, 11, 14, 16, 19, 21, 24, 26, 28, 30, 32, 34];
305            for (i, &p) in PAIRS.iter().enumerate() {
306                let hi = HEX_DECODE[arr[p] as usize];
307                let lo = HEX_DECODE[arr[p + 1] as usize];
308                bad |= hi | lo;
309                out[i] = (hi << 4) | (lo & 0x0f);
310            }
311            if bad < 16 {
312                Some(Uuid(out))
313            } else {
314                None
315            }
316        }
317    }
318
319    /// Parse many canonical 36-char UUIDs packed back-to-back (`36·n` bytes) into a `Vec<Uuid>` — the
320    /// bulk read path (a DB column / log-ingest stream). Loops the SIMD decode core directly with no
321    /// per-id `trim`/dispatch overhead, into a single pre-sized allocation. `None` if the length isn't a
322    /// multiple of 36 or any record is malformed. Pairs with [`encode_many`](encode_many) (the bulk write path).
323    pub fn parse_many(packed: &[u8]) -> Option<Vec<Uuid>> {
324        if packed.is_empty() || packed.len() % 36 != 0 {
325            return None;
326        }
327        #[cfg(all(target_arch = "x86_64", target_feature = "ssse3"))]
328        {
329            return unsafe { x86_hex::parse_batch(packed) };
330        }
331        #[cfg(all(target_arch = "x86_64", not(target_feature = "ssse3")))]
332        {
333            if x86_hex::available() {
334                return unsafe { x86_hex::parse_batch(packed) };
335            }
336        }
337        #[cfg(not(all(target_arch = "x86_64", target_feature = "ssse3")))]
338        {
339            let n = packed.len() / 36;
340            let mut out = Vec::with_capacity(n);
341            for chunk in packed.chunks_exact(36) {
342                let rec: &[u8; 36] = chunk.try_into().unwrap();
343                out.push(Self::parse_canonical(rec)?);
344            }
345            Some(out)
346        }
347    }
348}
349
350/// `HEX_DECODE[c]` is the nibble value (0–15) of ASCII hex char `c`, or `0xFF` (≥16) for any
351/// non-hex byte — so a single `|`-accumulation over a run detects an invalid digit branch-free.
352const HEX_DECODE: [u8; 256] = {
353    let mut t = [0xFFu8; 256];
354    let mut i = 0u8;
355    while i < 10 {
356        t[(b'0' + i) as usize] = i;
357        i += 1;
358    }
359    let mut i = 0u8;
360    while i < 6 {
361        t[(b'a' + i) as usize] = 10 + i;
362        t[(b'A' + i) as usize] = 10 + i;
363        i += 1;
364    }
365    t
366};
367
368fn hex_val(c: u8) -> Option<u8> {
369    match c {
370        b'0'..=b'9' => Some(c - b'0'),
371        b'a'..=b'f' => Some(c - b'a' + 10),
372        b'A'..=b'F' => Some(c - b'A' + 10),
373        _ => None,
374    }
375}
376
377/// `HEX_PAIRS[b]` is the two lowercase ASCII hex chars of byte `b`, packed — one table lookup per
378/// byte instead of two nibble lookups.
379const HEX_PAIRS: [[u8; 2]; 256] = {
380    const HEX: &[u8; 16] = b"0123456789abcdef";
381    let mut t = [[0u8; 2]; 256];
382    let mut i = 0;
383    while i < 256 {
384        t[i] = [HEX[i >> 4], HEX[i & 0xf]];
385        i += 1;
386    }
387    t
388};
389
390/// Write a UUID's canonical 36-byte text into a caller buffer (no allocation) — the alloc-free hot
391/// path for `Display` and for BULK formatting (fill one big buffer, zero per-id allocations). Uses an
392/// SSSE3 `pshufb` nibble→hex encode when available, else the byte-pair table.
393#[inline]
394pub fn encode_canonical(bytes: &[u8; 16], buf: &mut [u8; 36]) {
395    // Under `target-cpu=native` the SSSE3 detect is compiled away and this is a direct SIMD call.
396    #[cfg(all(target_arch = "x86_64", target_feature = "ssse3"))]
397    {
398        // SAFETY: ssse3 is statically enabled for this build.
399        return unsafe { x86_hex::encode_canonical(bytes, buf) };
400    }
401    #[cfg(all(target_arch = "x86_64", not(target_feature = "ssse3")))]
402    {
403        if x86_hex::available() {
404            // SAFETY: guarded by the ssse3 feature detection.
405            unsafe { x86_hex::encode_canonical(bytes, buf) };
406            return;
407        }
408    }
409    #[cfg(not(all(target_arch = "x86_64", target_feature = "ssse3")))]
410    encode_canonical_scalar(bytes, buf);
411}
412
413/// Portable byte-pair-table encode (the fallback / non-x86 path).
414#[inline]
415fn encode_canonical_scalar(bytes: &[u8; 16], buf: &mut [u8; 36]) {
416    let mut j = 0;
417    let write = |buf: &mut [u8; 36], range: std::ops::Range<usize>, j: &mut usize| {
418        for &byte in &bytes[range] {
419            let pair = HEX_PAIRS[byte as usize];
420            buf[*j] = pair[0];
421            buf[*j + 1] = pair[1];
422            *j += 2;
423        }
424    };
425    write(buf, 0..4, &mut j);
426    buf[j] = b'-';
427    j += 1;
428    write(buf, 4..6, &mut j);
429    buf[j] = b'-';
430    j += 1;
431    write(buf, 6..8, &mut j);
432    buf[j] = b'-';
433    j += 1;
434    write(buf, 8..10, &mut j);
435    buf[j] = b'-';
436    j += 1;
437    write(buf, 10..16, &mut j);
438}
439
440/// SSSE3 hex encode for a UUID: one `pshufb` turns 16 nibbles into 16 hex chars, done twice
441/// (high/low), interleaved with `punpck`, then scattered into the `8-4-4-4-12` layout.
442#[cfg(target_arch = "x86_64")]
443mod x86_hex {
444    /// The SSSE3 (`pshufb`) instruction this encode needs; cached by std after the first call.
445    #[inline]
446    pub fn available() -> bool {
447        std::is_x86_feature_detected!("ssse3")
448    }
449
450    #[target_feature(enable = "ssse3,sse2")]
451    pub unsafe fn encode_canonical(bytes: &[u8; 16], buf: &mut [u8; 36]) {
452        use core::arch::x86_64::*;
453        let v = _mm_loadu_si128(bytes.as_ptr() as *const __m128i);
454        let mask0f = _mm_set1_epi8(0x0f);
455        // Per byte: high nibble = (byte >> 4) & 0x0f, low nibble = byte & 0x0f.
456        let hi = _mm_and_si128(_mm_srli_epi16(v, 4), mask0f);
457        let lo = _mm_and_si128(v, mask0f);
458        let lut = _mm_setr_epi8(
459            b'0' as i8, b'1' as i8, b'2' as i8, b'3' as i8, b'4' as i8, b'5' as i8, b'6' as i8,
460            b'7' as i8, b'8' as i8, b'9' as i8, b'a' as i8, b'b' as i8, b'c' as i8, b'd' as i8,
461            b'e' as i8, b'f' as i8,
462        );
463        let hi_hex = _mm_shuffle_epi8(lut, hi);
464        let lo_hex = _mm_shuffle_epi8(lut, lo);
465        // Interleave to (hi0,lo0,hi1,lo1,…): chars 0–15 in `h0`, 16–31 in `h1`.
466        let h0 = _mm_unpacklo_epi8(hi_hex, lo_hex);
467        let h1 = _mm_unpackhi_epi8(hi_hex, lo_hex);
468        // SIMD scatter into the 8-4-4-4-12 layout — `pshufb` places the hex + zeros the dash slots,
469        // `palignr` bridges the c14/c15 that straddle h0/h1 so out[16..32] is one shuffle, dashes OR'd
470        // in. Two 16-byte stores + a 4-byte tail; measured ~1.23× the per-range `copy_from_slice`.
471        let mask_lo = _mm_setr_epi8(0, 1, 2, 3, 4, 5, 6, 7, -128, 8, 9, 10, 11, -128, 12, 13);
472        let dash_lo = _mm_setr_epi8(0, 0, 0, 0, 0, 0, 0, 0, 0x2d, 0, 0, 0, 0, 0x2d, 0, 0);
473        let out_lo = _mm_or_si128(_mm_shuffle_epi8(h0, mask_lo), dash_lo);
474        let mid = _mm_alignr_epi8(h1, h0, 14); // [c14, c15, c16..c29]
475        let mask_mid = _mm_setr_epi8(0, 1, -128, 2, 3, 4, 5, -128, 6, 7, 8, 9, 10, 11, 12, 13);
476        let dash_mid = _mm_setr_epi8(0, 0, 0x2d, 0, 0, 0, 0, 0x2d, 0, 0, 0, 0, 0, 0, 0, 0);
477        let out_mid = _mm_or_si128(_mm_shuffle_epi8(mid, mask_mid), dash_mid);
478        _mm_storeu_si128(buf.as_mut_ptr() as *mut __m128i, out_lo);
479        _mm_storeu_si128(buf.as_mut_ptr().add(16) as *mut __m128i, out_mid);
480        let mut t = [0u8; 16];
481        _mm_storeu_si128(t.as_mut_ptr() as *mut __m128i, h1);
482        buf[32..36].copy_from_slice(&t[12..16]); // c28-31
483    }
484
485    /// ASCII hex chars → nibble values (0–15), one lane each: `(c & 0x0f) + 9·((c & 0x40) >> 6)`.
486    #[inline]
487    #[target_feature(enable = "ssse3,sse2")]
488    unsafe fn nibbles(chars: core::arch::x86_64::__m128i) -> core::arch::x86_64::__m128i {
489        use core::arch::x86_64::*;
490        let lo = _mm_and_si128(chars, _mm_set1_epi8(0x0f));
491        let hi = _mm_srli_epi16(_mm_and_si128(chars, _mm_set1_epi8(0x40)), 6); // per byte {0,1}
492        let hi8 = _mm_slli_epi16(hi, 3); // per byte {0,8}
493        _mm_add_epi8(_mm_add_epi8(lo, hi8), hi) // lo + 9·hi
494    }
495
496    /// Per-lane hex-validity MASK (`0xFF` where the lane is `0-9A-Fa-f`, else `0x00`), case-folded — the
497    /// value form of a boolean range check, so a batch can `&`-accumulate one mask across many records
498    /// and pay the single `movemask`+branch once per column instead of once per record.
499    #[inline]
500    #[target_feature(enable = "ssse3,sse2")]
501    unsafe fn hex_ok(chars: core::arch::x86_64::__m128i) -> core::arch::x86_64::__m128i {
502        use core::arch::x86_64::*;
503        let cf = _mm_or_si128(chars, _mm_set1_epi8(0x20)); // fold 'A'-'F' → 'a'-'f'
504        let clamp = |lo: i8, hi: i8| {
505            _mm_cmpeq_epi8(
506                _mm_min_epu8(_mm_max_epu8(cf, _mm_set1_epi8(lo)), _mm_set1_epi8(hi)),
507                cf,
508            )
509        };
510        _mm_or_si128(clamp(0x30, 0x39), clamp(0x61, 0x66))
511    }
512
513    /// The branch-free decode core shared by the single and bulk parsers. Two `pshufb` gathers strip the
514    /// four hyphens; `pmaddubsw` with weights `[16, 1, …]` fuses each nibble pair and `packuswb` narrows
515    /// to the first 14 bytes; the last two bytes (`string[32..36]`, hyphen-free) decode with the same
516    /// branchless `(c & 0xf) + 9·(c >> 6)` nibble. Writes all 16 bytes UNCONDITIONALLY (garbage for
517    /// non-hex input, which the caller rejects) and RETURNS the per-lane hex-validity mask of the gather.
518    #[inline]
519    #[target_feature(enable = "ssse3,sse2")]
520    unsafe fn decode_core(b: &[u8; 36], out: &mut [u8; 16]) -> core::arch::x86_64::__m128i {
521        use core::arch::x86_64::*;
522        let l0 = _mm_loadu_si128(b.as_ptr() as *const __m128i); // string[0..16]
523        let l1 = _mm_loadu_si128(b.as_ptr().add(16) as *const __m128i); // string[16..32]
524                                                                        // Gather each half's hex chars, dropping the hyphens. The two padding lanes reuse index 0 (a
525                                                                        // real hex char), so validity never trips on them and their (discarded) output byte is safe.
526        let mask_a = _mm_setr_epi8(0, 1, 2, 3, 4, 5, 6, 7, 9, 10, 11, 12, 14, 15, 0, 0);
527        let mask_b = _mm_setr_epi8(0, 1, 3, 4, 5, 6, 8, 9, 10, 11, 12, 13, 14, 15, 0, 0);
528        let ra = _mm_shuffle_epi8(l0, mask_a);
529        let rb = _mm_shuffle_epi8(l1, mask_b);
530        // Bytes `[16, 1, 16, 1, …]` as little-endian 16-bit lanes `0x0110`.
531        let weights = _mm_set1_epi16(0x0110);
532        let ba = _mm_packus_epi16(_mm_maddubs_epi16(nibbles(ra), weights), _mm_setzero_si128());
533        let bb = _mm_packus_epi16(_mm_maddubs_epi16(nibbles(rb), weights), _mm_setzero_si128());
534        _mm_storel_epi64(out.as_mut_ptr() as *mut __m128i, ba); // out[0..8] (byte 7 discarded)
535        _mm_storel_epi64(out.as_mut_ptr().add(7) as *mut __m128i, bb); // out[7..15] (byte 14 discarded)
536                                                                       // Tail — string[32..36], no hyphen. The `& 0x0f` keeps the nibble in range for garbage input so
537                                                                       // the unconditional `<< 4` cannot debug-overflow (valid nibbles are unaffected); rejection is
538                                                                       // the caller's job via the returned mask + the scalar-tail table check.
539        let nib = |c: u8| ((c & 0x0f) + 9 * (c >> 6)) & 0x0f;
540        out[14] = (nib(b[32]) << 4) | nib(b[33]);
541        out[15] = (nib(b[34]) << 4) | nib(b[35]);
542        _mm_and_si128(hex_ok(ra), hex_ok(rb))
543    }
544
545    /// SSSE3 hex DECODE for one canonical 36-char UUID. The caller guarantees `'-'` at 8/13/18/23.
546    /// Returns `None` on any non-hex digit — one `movemask` over the [`decode_core`] mask plus a table
547    /// check of the two scalar-tail bytes.
548    #[target_feature(enable = "ssse3,sse2")]
549    pub unsafe fn parse_hyphenated(b: &[u8; 36]) -> Option<[u8; 16]> {
550        use core::arch::x86_64::*;
551        let mut out = [0u8; 16];
552        let mask = decode_core(b, &mut out);
553        let tail = super::HEX_DECODE[b[32] as usize]
554            | super::HEX_DECODE[b[33] as usize]
555            | super::HEX_DECODE[b[34] as usize]
556            | super::HEX_DECODE[b[35] as usize];
557        if _mm_movemask_epi8(mask) == 0xffff && tail < 16 {
558            Some(out)
559        } else {
560            None
561        }
562    }
563
564    /// Bulk parse of packed 36-char records — the batch-validated fast path. Every record decodes through
565    /// the branch-free [`decode_core`], and the three validity channels accumulate WITHOUT branching (`&`
566    /// the hex-lane masks, `|` the scalar-tail nibbles, `|` the XORed hyphen slots), so the single
567    /// `movemask`+branch is paid once for the whole column instead of once per record — that per-record
568    /// `movemask`+branch is exactly what serialized the loop (measured ~3× the decode itself). A valid
569    /// column (the overwhelming common case) returns at trusted-decode speed; a single bad byte anywhere
570    /// sinks the batch to `None`, byte-for-byte matching the per-record parser. `packed.len()` is a
571    /// nonzero multiple of 36 (the caller checks).
572    #[target_feature(enable = "ssse3,sse2")]
573    pub unsafe fn parse_batch(packed: &[u8]) -> Option<Vec<super::Uuid>> {
574        use core::arch::x86_64::*;
575        let n = packed.len() / 36;
576        let mut out: Vec<super::Uuid> = Vec::with_capacity(n);
577        let mut acc = _mm_set1_epi8(-1i8); // all lanes 0xFF
578        let mut tail_bad = 0u8;
579        let mut dash_bad = 0u8;
580        for chunk in packed.chunks_exact(36) {
581            let b: &[u8; 36] = chunk.try_into().unwrap();
582            dash_bad |= (b[8] ^ b'-') | (b[13] ^ b'-') | (b[18] ^ b'-') | (b[23] ^ b'-');
583            tail_bad |= super::HEX_DECODE[b[32] as usize]
584                | super::HEX_DECODE[b[33] as usize]
585                | super::HEX_DECODE[b[34] as usize]
586                | super::HEX_DECODE[b[35] as usize];
587            let mut rec = [0u8; 16];
588            acc = _mm_and_si128(acc, decode_core(b, &mut rec));
589            out.push(super::Uuid(rec));
590        }
591        if dash_bad == 0 && tail_bad < 16 && _mm_movemask_epi8(acc) == 0xffff {
592            Some(out)
593        } else {
594            None
595        }
596    }
597}
598
599/// Format many UUIDs into ONE contiguous buffer (each 36 bytes, `\n`-free), zero per-id allocation —
600/// the bulk path a database column / log stream wants. Returns the packed `36·n`-byte buffer.
601pub fn encode_many(ids: &[Uuid]) -> Vec<u8> {
602    // Per-id SSSE3 encode, whose scatter is now SIMD (`pshufb`/`palignr`) — that's where bulk format
603    // spends its time. Controlled interleaved A/B (contention-matched): the SIMD scatter beat the
604    // per-range `copy_from_slice` by median 1.23× (whole distribution above 1.0). An AVX2 2-wide *encode*
605    // was separately a wash — the encode was never the bottleneck; the scatter was.
606    let mut out = vec![0u8; ids.len() * 36];
607    for (i, id) in ids.iter().enumerate() {
608        let slot: &mut [u8; 36] = (&mut out[i * 36..i * 36 + 36]).try_into().unwrap();
609        encode_canonical(&id.0, slot);
610    }
611    out
612}
613
614impl fmt::Display for Uuid {
615    /// Canonical lowercase hyphenated form, `8-4-4-4-12` (RFC 9562 §4).
616    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
617        let mut buf = [0u8; 36];
618        encode_canonical(&self.0, &mut buf);
619        // SAFETY: every byte written is ASCII (`0-9a-f` or `-`), so the buffer is valid UTF-8.
620        f.write_str(unsafe { core::str::from_utf8_unchecked(&buf) })
621    }
622}
623
624impl fmt::Debug for Uuid {
625    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
626        write!(f, "Uuid({self})")
627    }
628}
629
630#[cfg(test)]
631#[path = "../../logicaffeine_tests/unit/logicaffeine_base/uuid/tests.rs"]
632mod tests;