Skip to main content

logicaffeine_base/
hash.rs

1//! Cryptographic hash primitives — MD5 (RFC 1321) and SHA-1 (RFC 3174), rolled in pure Rust.
2//!
3//! The REFERENCE ORACLE. MD5 and SHA-1 (the hashes RFC 9562 defines UUID v3/v5 on) are written in the
4//! LOGOS language (`crates/logicaffeine_compile/assets/std/uuid.lg`: `md5Digest`/`sha1Digest`, which the
5//! `md5`/`sha1`/`uuid_v3`/`uuid_v5` stdlib functions call) and compile to native through the Futamura
6//! pipeline — that is the language's implementation. These pure-Rust versions are the independent oracle
7//! the Logos ones are proven byte-exact against (here and cross-tier), NOT on any language path.
8//! (SHA-3/Keccak is the modern hash and lives in `logicaffeine_system`.)
9//!
10//! Both are block functions over 64-byte chunks with the standard Merkle–Damgård padding. They are NOT
11//! for security (MD5 and SHA-1 are both broken against collision attacks). Validated bit-exact against
12//! the `md-5`/`sha1` reference crates (known RFC vectors + differential fuzz) in the tests.
13
14/// MD5 digest of `data` (RFC 1321) — 16 bytes.
15pub fn md5(data: &[u8]) -> [u8; 16] {
16    // Per-round left-rotation amounts (RFC 1321 §3.4).
17    const S: [u32; 64] = [
18        7, 12, 17, 22, 7, 12, 17, 22, 7, 12, 17, 22, 7, 12, 17, 22, 5, 9, 14, 20, 5, 9, 14, 20, 5,
19        9, 14, 20, 5, 9, 14, 20, 4, 11, 16, 23, 4, 11, 16, 23, 4, 11, 16, 23, 4, 11, 16, 23, 6, 10,
20        15, 21, 6, 10, 15, 21, 6, 10, 15, 21, 6, 10, 15, 21,
21    ];
22    // K[i] = floor(2^32 · |sin(i+1)|) — the additive constants (RFC 1321 §3.4).
23    const K: [u32; 64] = [
24        0xd76aa478, 0xe8c7b756, 0x242070db, 0xc1bdceee, 0xf57c0faf, 0x4787c62a, 0xa8304613,
25        0xfd469501, 0x698098d8, 0x8b44f7af, 0xffff5bb1, 0x895cd7be, 0x6b901122, 0xfd987193,
26        0xa679438e, 0x49b40821, 0xf61e2562, 0xc040b340, 0x265e5a51, 0xe9b6c7aa, 0xd62f105d,
27        0x02441453, 0xd8a1e681, 0xe7d3fbc8, 0x21e1cde6, 0xc33707d6, 0xf4d50d87, 0x455a14ed,
28        0xa9e3e905, 0xfcefa3f8, 0x676f02d9, 0x8d2a4c8a, 0xfffa3942, 0x8771f681, 0x6d9d6122,
29        0xfde5380c, 0xa4beea44, 0x4bdecfa9, 0xf6bb4b60, 0xbebfbc70, 0x289b7ec6, 0xeaa127fa,
30        0xd4ef3085, 0x04881d05, 0xd9d4d039, 0xe6db99e5, 0x1fa27cf8, 0xc4ac5665, 0xf4292244,
31        0x432aff97, 0xab9423a7, 0xfc93a039, 0x655b59c3, 0x8f0ccc92, 0xffeff47d, 0x85845dd1,
32        0x6fa87e4f, 0xfe2ce6e0, 0xa3014314, 0x4e0811a1, 0xf7537e82, 0xbd3af235, 0x2ad7d2bb,
33        0xeb86d391,
34    ];
35
36    // The rotation amounts are baked into the unrolled steps below as literals; the linear `S` table
37    // is unused by this form.
38    let _ = S;
39
40    let mut state: [u32; 4] = [0x67452301, 0xefcdab89, 0x98badcfe, 0x10325476];
41
42    #[inline(always)]
43    fn compress(state: &mut [u32; 4], block: &[u8; 64]) {
44        let mut m = [0u32; 16];
45        for (i, w) in m.iter_mut().enumerate() {
46            *w = u32::from_le_bytes([
47                block[4 * i],
48                block[4 * i + 1],
49                block[4 * i + 2],
50                block[4 * i + 3],
51            ]);
52        }
53        let (mut a, mut b, mut c, mut d) = (state[0], state[1], state[2], state[3]);
54        // Fully-unrolled rotating-variable form (RFC 1321): instead of moving a=d;d=c;c=b each step,
55        // the OUTPUT variable cycles a→d→c→b, so the 192 register-shuffle moves vanish and every
56        // g/s/K is a compile-time constant. `op(a,b,c,d,x,s,t): a = b + rotl(a + f(b,c,d) + x + t, s)`.
57        macro_rules! ff {
58            ($a:ident,$b:ident,$c:ident,$d:ident,$g:expr,$s:expr,$t:expr) => {
59                $a = $b.wrapping_add(
60                    ($a.wrapping_add(($b & $c) | (!$b & $d))
61                        .wrapping_add(m[$g])
62                        .wrapping_add($t))
63                    .rotate_left($s),
64                );
65            };
66        }
67        macro_rules! gg {
68            ($a:ident,$b:ident,$c:ident,$d:ident,$g:expr,$s:expr,$t:expr) => {
69                $a = $b.wrapping_add(
70                    ($a.wrapping_add(($b & $d) | ($c & !$d))
71                        .wrapping_add(m[$g])
72                        .wrapping_add($t))
73                    .rotate_left($s),
74                );
75            };
76        }
77        macro_rules! hh {
78            ($a:ident,$b:ident,$c:ident,$d:ident,$g:expr,$s:expr,$t:expr) => {
79                $a = $b.wrapping_add(
80                    ($a.wrapping_add($b ^ $c ^ $d)
81                        .wrapping_add(m[$g])
82                        .wrapping_add($t))
83                    .rotate_left($s),
84                );
85            };
86        }
87        macro_rules! ii {
88            ($a:ident,$b:ident,$c:ident,$d:ident,$g:expr,$s:expr,$t:expr) => {
89                $a = $b.wrapping_add(
90                    ($a.wrapping_add($c ^ ($b | !$d))
91                        .wrapping_add(m[$g])
92                        .wrapping_add($t))
93                    .rotate_left($s),
94                );
95            };
96        }
97        // Round 1 — g = i.
98        ff!(a, b, c, d, 0, 7, K[0]);
99        ff!(d, a, b, c, 1, 12, K[1]);
100        ff!(c, d, a, b, 2, 17, K[2]);
101        ff!(b, c, d, a, 3, 22, K[3]);
102        ff!(a, b, c, d, 4, 7, K[4]);
103        ff!(d, a, b, c, 5, 12, K[5]);
104        ff!(c, d, a, b, 6, 17, K[6]);
105        ff!(b, c, d, a, 7, 22, K[7]);
106        ff!(a, b, c, d, 8, 7, K[8]);
107        ff!(d, a, b, c, 9, 12, K[9]);
108        ff!(c, d, a, b, 10, 17, K[10]);
109        ff!(b, c, d, a, 11, 22, K[11]);
110        ff!(a, b, c, d, 12, 7, K[12]);
111        ff!(d, a, b, c, 13, 12, K[13]);
112        ff!(c, d, a, b, 14, 17, K[14]);
113        ff!(b, c, d, a, 15, 22, K[15]);
114        // Round 2 — g = (5i+1) mod 16.
115        gg!(a, b, c, d, 1, 5, K[16]);
116        gg!(d, a, b, c, 6, 9, K[17]);
117        gg!(c, d, a, b, 11, 14, K[18]);
118        gg!(b, c, d, a, 0, 20, K[19]);
119        gg!(a, b, c, d, 5, 5, K[20]);
120        gg!(d, a, b, c, 10, 9, K[21]);
121        gg!(c, d, a, b, 15, 14, K[22]);
122        gg!(b, c, d, a, 4, 20, K[23]);
123        gg!(a, b, c, d, 9, 5, K[24]);
124        gg!(d, a, b, c, 14, 9, K[25]);
125        gg!(c, d, a, b, 3, 14, K[26]);
126        gg!(b, c, d, a, 8, 20, K[27]);
127        gg!(a, b, c, d, 13, 5, K[28]);
128        gg!(d, a, b, c, 2, 9, K[29]);
129        gg!(c, d, a, b, 7, 14, K[30]);
130        gg!(b, c, d, a, 12, 20, K[31]);
131        // Round 3 — g = (3i+5) mod 16.
132        hh!(a, b, c, d, 5, 4, K[32]);
133        hh!(d, a, b, c, 8, 11, K[33]);
134        hh!(c, d, a, b, 11, 16, K[34]);
135        hh!(b, c, d, a, 14, 23, K[35]);
136        hh!(a, b, c, d, 1, 4, K[36]);
137        hh!(d, a, b, c, 4, 11, K[37]);
138        hh!(c, d, a, b, 7, 16, K[38]);
139        hh!(b, c, d, a, 10, 23, K[39]);
140        hh!(a, b, c, d, 13, 4, K[40]);
141        hh!(d, a, b, c, 0, 11, K[41]);
142        hh!(c, d, a, b, 3, 16, K[42]);
143        hh!(b, c, d, a, 6, 23, K[43]);
144        hh!(a, b, c, d, 9, 4, K[44]);
145        hh!(d, a, b, c, 12, 11, K[45]);
146        hh!(c, d, a, b, 15, 16, K[46]);
147        hh!(b, c, d, a, 2, 23, K[47]);
148        // Round 4 — g = 7i mod 16.
149        ii!(a, b, c, d, 0, 6, K[48]);
150        ii!(d, a, b, c, 7, 10, K[49]);
151        ii!(c, d, a, b, 14, 15, K[50]);
152        ii!(b, c, d, a, 5, 21, K[51]);
153        ii!(a, b, c, d, 12, 6, K[52]);
154        ii!(d, a, b, c, 3, 10, K[53]);
155        ii!(c, d, a, b, 10, 15, K[54]);
156        ii!(b, c, d, a, 1, 21, K[55]);
157        ii!(a, b, c, d, 8, 6, K[56]);
158        ii!(d, a, b, c, 15, 10, K[57]);
159        ii!(c, d, a, b, 6, 15, K[58]);
160        ii!(b, c, d, a, 13, 21, K[59]);
161        ii!(a, b, c, d, 4, 6, K[60]);
162        ii!(d, a, b, c, 11, 10, K[61]);
163        ii!(c, d, a, b, 2, 15, K[62]);
164        ii!(b, c, d, a, 9, 21, K[63]);
165        state[0] = state[0].wrapping_add(a);
166        state[1] = state[1].wrapping_add(b);
167        state[2] = state[2].wrapping_add(c);
168        state[3] = state[3].wrapping_add(d);
169    }
170
171    each_padded_block(data, Endian::Little, |block| compress(&mut state, block));
172
173    let mut out = [0u8; 16];
174    out[0..4].copy_from_slice(&state[0].to_le_bytes());
175    out[4..8].copy_from_slice(&state[1].to_le_bytes());
176    out[8..12].copy_from_slice(&state[2].to_le_bytes());
177    out[12..16].copy_from_slice(&state[3].to_le_bytes());
178    out
179}
180
181/// The 64 MD5 additive constants `floor(2^32·|sin(i+1)|)` and per-round rotation amounts (RFC 1321).
182const MD5_K: [u32; 64] = [
183    0xd76aa478, 0xe8c7b756, 0x242070db, 0xc1bdceee, 0xf57c0faf, 0x4787c62a, 0xa8304613, 0xfd469501,
184    0x698098d8, 0x8b44f7af, 0xffff5bb1, 0x895cd7be, 0x6b901122, 0xfd987193, 0xa679438e, 0x49b40821,
185    0xf61e2562, 0xc040b340, 0x265e5a51, 0xe9b6c7aa, 0xd62f105d, 0x02441453, 0xd8a1e681, 0xe7d3fbc8,
186    0x21e1cde6, 0xc33707d6, 0xf4d50d87, 0x455a14ed, 0xa9e3e905, 0xfcefa3f8, 0x676f02d9, 0x8d2a4c8a,
187    0xfffa3942, 0x8771f681, 0x6d9d6122, 0xfde5380c, 0xa4beea44, 0x4bdecfa9, 0xf6bb4b60, 0xbebfbc70,
188    0x289b7ec6, 0xeaa127fa, 0xd4ef3085, 0x04881d05, 0xd9d4d039, 0xe6db99e5, 0x1fa27cf8, 0xc4ac5665,
189    0xf4292244, 0x432aff97, 0xab9423a7, 0xfc93a039, 0x655b59c3, 0x8f0ccc92, 0xffeff47d, 0x85845dd1,
190    0x6fa87e4f, 0xfe2ce6e0, 0xa3014314, 0x4e0811a1, 0xf7537e82, 0xbd3af235, 0x2ad7d2bb, 0xeb86d391,
191];
192const MD5_S: [u32; 64] = [
193    7, 12, 17, 22, 7, 12, 17, 22, 7, 12, 17, 22, 7, 12, 17, 22, 5, 9, 14, 20, 5, 9, 14, 20, 5, 9,
194    14, 20, 5, 9, 14, 20, 4, 11, 16, 23, 4, 11, 16, 23, 4, 11, 16, 23, 4, 11, 16, 23, 6, 10, 15,
195    21, 6, 10, 15, 21, 6, 10, 15, 21, 6, 10, 15, 21,
196];
197
198/// MD5 of FOUR equal-length messages at once — 4-way SSE2 multi-buffer, the high-throughput path for
199/// hashing many same-size records (bulk name-based ids, dedup keys, content addresses). All four ABCD
200/// states advance in one `__m128i` (lane j = message j), so ~4× a scalar MD5 per message. The four
201/// inputs MUST share a length; returns the four 16-byte digests, byte-identical to [`md5`] per lane.
202#[cfg(target_arch = "x86_64")]
203pub fn md5_x4(msgs: [&[u8]; 4]) -> [[u8; 16]; 4] {
204    let len = msgs[0].len();
205    assert!(
206        msgs.iter().all(|m| m.len() == len),
207        "md5_x4 requires equal-length inputs"
208    );
209    if std::is_x86_feature_detected!("sse2") {
210        // SAFETY: guarded by the sse2 feature detection just above.
211        unsafe { md5_x4_sse2(msgs, len) }
212    } else {
213        md5_x4_scalar(msgs)
214    }
215}
216
217/// The portable 4-lane MD5 fallback (four scalar hashes). `pub(crate)` so tests exercise it even
218/// where `md5_x4` dispatches to SSE2.
219pub(crate) fn md5_x4_scalar(msgs: [&[u8]; 4]) -> [[u8; 16]; 4] {
220    [md5(msgs[0]), md5(msgs[1]), md5(msgs[2]), md5(msgs[3])]
221}
222
223#[cfg(target_arch = "x86_64")]
224#[target_feature(enable = "sse2")]
225unsafe fn md5_x4_sse2(msgs: [&[u8]; 4], len: usize) -> [[u8; 16]; 4] {
226    // Identical length ⇒ identical Merkle–Damgård padding (0x80, zero fill, 64-bit LE bit length) and
227    // block count for all four lanes. A 256-byte inline buffer per lane keeps the common case (records
228    // up to 247 bytes) entirely on the stack — no per-call heap; longer inputs fall back to a Vec.
229    let total = (len + 8) / 64 * 64 + 64;
230    let nb = total / 64;
231    let bitlen = (len as u64).wrapping_mul(8);
232    const CAP: usize = 256;
233    if total <= CAP {
234        let mut pad = [[0u8; CAP]; 4];
235        for (j, p) in pad.iter_mut().enumerate() {
236            p[..len].copy_from_slice(msgs[j]);
237            p[len] = 0x80;
238            p[total - 8..total].copy_from_slice(&bitlen.to_le_bytes());
239        }
240        md5_x4_run([&pad[0][..], &pad[1][..], &pad[2][..], &pad[3][..]], nb)
241    } else {
242        let mut pad = [
243            vec![0u8; total],
244            vec![0u8; total],
245            vec![0u8; total],
246            vec![0u8; total],
247        ];
248        for (j, p) in pad.iter_mut().enumerate() {
249            p[..len].copy_from_slice(msgs[j]);
250            p[len] = 0x80;
251            p[total - 8..].copy_from_slice(&bitlen.to_le_bytes());
252        }
253        md5_x4_run([&pad[0][..], &pad[1][..], &pad[2][..], &pad[3][..]], nb)
254    }
255}
256
257/// The 4-way SSE2 MD5 compress + transpose over the four (already padded) lane buffers — the alloc-free
258/// core shared by both the stack and heap staging paths of [`md5_x4_sse2`].
259#[cfg(target_arch = "x86_64")]
260#[target_feature(enable = "sse2")]
261unsafe fn md5_x4_run(pad: [&[u8]; 4], nb: usize) -> [[u8; 16]; 4] {
262    use core::arch::x86_64::*;
263
264    let rotl = |x: __m128i, s: u32| -> __m128i {
265        _mm_or_si128(
266            _mm_sll_epi32(x, _mm_cvtsi32_si128(s as i32)),
267            _mm_srl_epi32(x, _mm_cvtsi32_si128((32 - s) as i32)),
268        )
269    };
270    let ones = _mm_set1_epi32(-1);
271
272    let mut sa = _mm_set1_epi32(0x67452301u32 as i32);
273    let mut sb = _mm_set1_epi32(0xefcdab89u32 as i32);
274    let mut sc = _mm_set1_epi32(0x98badcfeu32 as i32);
275    let mut sd = _mm_set1_epi32(0x10325476u32 as i32);
276
277    for bi in 0..nb {
278        // Transpose the four lanes' 16 message words: mw[g] = (msg0[g], msg1[g], msg2[g], msg3[g]).
279        let mut mw = [_mm_setzero_si128(); 16];
280        for (g, slot) in mw.iter_mut().enumerate() {
281            let o = bi * 64 + g * 4;
282            let w = |p: &[u8]| u32::from_le_bytes([p[o], p[o + 1], p[o + 2], p[o + 3]]) as i32;
283            *slot = _mm_setr_epi32(w(&pad[0]), w(&pad[1]), w(&pad[2]), w(&pad[3]));
284        }
285        let (mut a, mut b, mut c, mut d) = (sa, sb, sc, sd);
286        for i in 0..64 {
287            let (f, g) = match i / 16 {
288                0 => (_mm_or_si128(_mm_and_si128(b, c), _mm_andnot_si128(b, d)), i),
289                1 => (
290                    _mm_or_si128(_mm_and_si128(b, d), _mm_andnot_si128(d, c)),
291                    (5 * i + 1) % 16,
292                ),
293                2 => (_mm_xor_si128(_mm_xor_si128(b, c), d), (3 * i + 5) % 16),
294                _ => (
295                    _mm_xor_si128(c, _mm_or_si128(b, _mm_xor_si128(d, ones))),
296                    (7 * i) % 16,
297                ),
298            };
299            let t = _mm_add_epi32(
300                _mm_add_epi32(a, f),
301                _mm_add_epi32(mw[g], _mm_set1_epi32(MD5_K[i] as i32)),
302            );
303            a = d;
304            d = c;
305            c = b;
306            b = _mm_add_epi32(b, rotl(t, MD5_S[i]));
307        }
308        sa = _mm_add_epi32(sa, a);
309        sb = _mm_add_epi32(sb, b);
310        sc = _mm_add_epi32(sc, c);
311        sd = _mm_add_epi32(sd, d);
312    }
313
314    let mut a4 = [0u32; 4];
315    let mut b4 = [0u32; 4];
316    let mut c4 = [0u32; 4];
317    let mut d4 = [0u32; 4];
318    _mm_storeu_si128(a4.as_mut_ptr() as *mut __m128i, sa);
319    _mm_storeu_si128(b4.as_mut_ptr() as *mut __m128i, sb);
320    _mm_storeu_si128(c4.as_mut_ptr() as *mut __m128i, sc);
321    _mm_storeu_si128(d4.as_mut_ptr() as *mut __m128i, sd);
322    let mut out = [[0u8; 16]; 4];
323    for (j, o) in out.iter_mut().enumerate() {
324        o[0..4].copy_from_slice(&a4[j].to_le_bytes());
325        o[4..8].copy_from_slice(&b4[j].to_le_bytes());
326        o[8..12].copy_from_slice(&c4[j].to_le_bytes());
327        o[12..16].copy_from_slice(&d4[j].to_le_bytes());
328    }
329    out
330}
331
332/// MD5 of EIGHT equal-length messages at once — AVX2 8-way multi-buffer, twice the width of [`md5_x4`].
333/// All eight ABCD states advance in one `__m256i` (lane j = message j). Falls back to two `md5_x4`
334/// passes without AVX2. Byte-identical to [`md5`] per lane; the high-throughput path for hashing many
335/// same-size records (bulk name-based ids, dedup/content keys).
336#[cfg(target_arch = "x86_64")]
337pub fn md5_x8(msgs: [&[u8]; 8]) -> [[u8; 16]; 8] {
338    let len = msgs[0].len();
339    assert!(
340        msgs.iter().all(|m| m.len() == len),
341        "md5_x8 requires equal-length inputs"
342    );
343    if std::is_x86_feature_detected!("avx2") {
344        // SAFETY: guarded by the avx2 feature detection just above.
345        unsafe { md5_x8_avx2(msgs, len) }
346    } else {
347        md5_x8_scalar(msgs)
348    }
349}
350
351/// The portable 8-lane MD5 fallback (two scalar 4-lane hashes). `pub(crate)` so tests exercise it
352/// even where `md5_x8` dispatches to AVX2.
353pub(crate) fn md5_x8_scalar(msgs: [&[u8]; 8]) -> [[u8; 16]; 8] {
354    let a = md5_x4_scalar([msgs[0], msgs[1], msgs[2], msgs[3]]);
355    let b = md5_x4_scalar([msgs[4], msgs[5], msgs[6], msgs[7]]);
356    [a[0], a[1], a[2], a[3], b[0], b[1], b[2], b[3]]
357}
358
359#[cfg(target_arch = "x86_64")]
360#[target_feature(enable = "avx2")]
361unsafe fn md5_x8_avx2(msgs: [&[u8]; 8], len: usize) -> [[u8; 16]; 8] {
362    let total = (len + 8) / 64 * 64 + 64;
363    let nb = total / 64;
364    let bitlen = (len as u64).wrapping_mul(8);
365    const CAP: usize = 256;
366    if total <= CAP {
367        let mut pad = [[0u8; CAP]; 8];
368        for (j, p) in pad.iter_mut().enumerate() {
369            p[..len].copy_from_slice(msgs[j]);
370            p[len] = 0x80;
371            p[total - 8..total].copy_from_slice(&bitlen.to_le_bytes());
372        }
373        let s: [&[u8]; 8] = [
374            &pad[0], &pad[1], &pad[2], &pad[3], &pad[4], &pad[5], &pad[6], &pad[7],
375        ];
376        md5_x8_run(s, nb)
377    } else {
378        let mut pad: Vec<Vec<u8>> = (0..8).map(|_| vec![0u8; total]).collect();
379        for (j, p) in pad.iter_mut().enumerate() {
380            p[..len].copy_from_slice(msgs[j]);
381            p[len] = 0x80;
382            p[total - 8..].copy_from_slice(&bitlen.to_le_bytes());
383        }
384        let s: [&[u8]; 8] = [
385            &pad[0], &pad[1], &pad[2], &pad[3], &pad[4], &pad[5], &pad[6], &pad[7],
386        ];
387        md5_x8_run(s, nb)
388    }
389}
390
391/// Transpose eight `__m256i` rows (8 lanes each) — the textbook AVX2 8×8 32-bit transpose (unpack
392/// `epi32` → unpack `epi64` → `permute2x128`). `out[k]` is column `k` = `(r0[k], r1[k], …, r7[k])`.
393#[cfg(target_arch = "x86_64")]
394#[target_feature(enable = "avx2")]
395unsafe fn transpose8x8(r: [core::arch::x86_64::__m256i; 8]) -> [core::arch::x86_64::__m256i; 8] {
396    use core::arch::x86_64::*;
397    let t0 = _mm256_unpacklo_epi32(r[0], r[1]);
398    let t1 = _mm256_unpackhi_epi32(r[0], r[1]);
399    let t2 = _mm256_unpacklo_epi32(r[2], r[3]);
400    let t3 = _mm256_unpackhi_epi32(r[2], r[3]);
401    let t4 = _mm256_unpacklo_epi32(r[4], r[5]);
402    let t5 = _mm256_unpackhi_epi32(r[4], r[5]);
403    let t6 = _mm256_unpacklo_epi32(r[6], r[7]);
404    let t7 = _mm256_unpackhi_epi32(r[6], r[7]);
405    let s0 = _mm256_unpacklo_epi64(t0, t2);
406    let s1 = _mm256_unpackhi_epi64(t0, t2);
407    let s2 = _mm256_unpacklo_epi64(t1, t3);
408    let s3 = _mm256_unpackhi_epi64(t1, t3);
409    let s4 = _mm256_unpacklo_epi64(t4, t6);
410    let s5 = _mm256_unpackhi_epi64(t4, t6);
411    let s6 = _mm256_unpacklo_epi64(t5, t7);
412    let s7 = _mm256_unpackhi_epi64(t5, t7);
413    [
414        _mm256_permute2x128_si256(s0, s4, 0x20),
415        _mm256_permute2x128_si256(s1, s5, 0x20),
416        _mm256_permute2x128_si256(s2, s6, 0x20),
417        _mm256_permute2x128_si256(s3, s7, 0x20),
418        _mm256_permute2x128_si256(s0, s4, 0x31),
419        _mm256_permute2x128_si256(s1, s5, 0x31),
420        _mm256_permute2x128_si256(s2, s6, 0x31),
421        _mm256_permute2x128_si256(s3, s7, 0x31),
422    ]
423}
424
425/// The 8-way AVX2 MD5 compress + transpose over the eight (already padded) lane buffers.
426#[cfg(target_arch = "x86_64")]
427#[target_feature(enable = "avx2")]
428unsafe fn md5_x8_run(pad: [&[u8]; 8], nb: usize) -> [[u8; 16]; 8] {
429    use core::arch::x86_64::*;
430
431    let rotl = |x: __m256i, s: u32| -> __m256i {
432        _mm256_or_si256(
433            _mm256_sll_epi32(x, _mm_cvtsi32_si128(s as i32)),
434            _mm256_srl_epi32(x, _mm_cvtsi32_si128((32 - s) as i32)),
435        )
436    };
437    let ones = _mm256_set1_epi32(-1);
438
439    let mut sa = _mm256_set1_epi32(0x67452301u32 as i32);
440    let mut sb = _mm256_set1_epi32(0xefcdab89u32 as i32);
441    let mut sc = _mm256_set1_epi32(0x98badcfeu32 as i32);
442    let mut sd = _mm256_set1_epi32(0x10325476u32 as i32);
443
444    for bi in 0..nb {
445        // Register transpose: load each lane's block as two rows (words 0–7 and 8–15) and transpose
446        // the 8×8 so `mw[g]` = word `g` of all eight messages — SIMD shuffles, not 128 scalar loads.
447        let base = bi * 64;
448        let ld =
449            |p: &[u8], off: usize| _mm256_loadu_si256(p.as_ptr().add(base + off) as *const __m256i);
450        let lo = transpose8x8([
451            ld(pad[0], 0),
452            ld(pad[1], 0),
453            ld(pad[2], 0),
454            ld(pad[3], 0),
455            ld(pad[4], 0),
456            ld(pad[5], 0),
457            ld(pad[6], 0),
458            ld(pad[7], 0),
459        ]);
460        let hi = transpose8x8([
461            ld(pad[0], 32),
462            ld(pad[1], 32),
463            ld(pad[2], 32),
464            ld(pad[3], 32),
465            ld(pad[4], 32),
466            ld(pad[5], 32),
467            ld(pad[6], 32),
468            ld(pad[7], 32),
469        ]);
470        let mut mw = [_mm256_setzero_si256(); 16];
471        mw[..8].copy_from_slice(&lo);
472        mw[8..].copy_from_slice(&hi);
473        let (mut a, mut b, mut c, mut d) = (sa, sb, sc, sd);
474        for i in 0..64 {
475            let (f, g) = match i / 16 {
476                0 => (
477                    _mm256_or_si256(_mm256_and_si256(b, c), _mm256_andnot_si256(b, d)),
478                    i,
479                ),
480                1 => (
481                    _mm256_or_si256(_mm256_and_si256(b, d), _mm256_andnot_si256(d, c)),
482                    (5 * i + 1) % 16,
483                ),
484                2 => (
485                    _mm256_xor_si256(_mm256_xor_si256(b, c), d),
486                    (3 * i + 5) % 16,
487                ),
488                _ => (
489                    _mm256_xor_si256(c, _mm256_or_si256(b, _mm256_xor_si256(d, ones))),
490                    (7 * i) % 16,
491                ),
492            };
493            let t = _mm256_add_epi32(
494                _mm256_add_epi32(a, f),
495                _mm256_add_epi32(mw[g], _mm256_set1_epi32(MD5_K[i] as i32)),
496            );
497            a = d;
498            d = c;
499            c = b;
500            b = _mm256_add_epi32(b, rotl(t, MD5_S[i]));
501        }
502        sa = _mm256_add_epi32(sa, a);
503        sb = _mm256_add_epi32(sb, b);
504        sc = _mm256_add_epi32(sc, c);
505        sd = _mm256_add_epi32(sd, d);
506    }
507
508    let mut a8 = [0u32; 8];
509    let mut b8 = [0u32; 8];
510    let mut c8 = [0u32; 8];
511    let mut d8 = [0u32; 8];
512    _mm256_storeu_si256(a8.as_mut_ptr() as *mut __m256i, sa);
513    _mm256_storeu_si256(b8.as_mut_ptr() as *mut __m256i, sb);
514    _mm256_storeu_si256(c8.as_mut_ptr() as *mut __m256i, sc);
515    _mm256_storeu_si256(d8.as_mut_ptr() as *mut __m256i, sd);
516    let mut out = [[0u8; 16]; 8];
517    for (j, o) in out.iter_mut().enumerate() {
518        o[0..4].copy_from_slice(&a8[j].to_le_bytes());
519        o[4..8].copy_from_slice(&b8[j].to_le_bytes());
520        o[8..12].copy_from_slice(&c8[j].to_le_bytes());
521        o[12..16].copy_from_slice(&d8[j].to_le_bytes());
522    }
523    out
524}
525
526/// SHA-1 digest of `data` (RFC 3174) — 20 bytes.
527pub fn sha1(data: &[u8]) -> [u8; 20] {
528    // Fast path: SHA-NI hardware instructions (≈ an order of magnitude faster than scalar). Gated on
529    // a one-shot runtime CPU-feature check; falls back to `sha1_scalar` everywhere else.
530    #[cfg(target_arch = "x86_64")]
531    {
532        if x86_sha::available() {
533            let mut h: [u32; 5] = [0x67452301, 0xEFCDAB89, 0x98BADCFE, 0x10325476, 0xC3D2E1F0];
534            // SAFETY: guarded by the `sha`/`ssse3`/`sse4.1` feature detection just checked.
535            unsafe { x86_sha::sha1_blocks(data, &mut h) };
536            let mut out = [0u8; 20];
537            for (i, hi) in h.iter().enumerate() {
538                out[4 * i..4 * i + 4].copy_from_slice(&hi.to_be_bytes());
539            }
540            return out;
541        }
542    }
543
544    sha1_scalar(data)
545}
546
547/// Portable scalar SHA-1 — the fallback taken on any target without the SHA-NI fast path (non-x86,
548/// or x86 lacking the `sha` extension). It is `pub(crate)` so the tests exercise it DIRECTLY even on
549/// hardware where [`sha1`] dispatches to SHA-NI; otherwise this whole path would ship untested to
550/// every non-SHA-NI machine.
551pub(crate) fn sha1_scalar(data: &[u8]) -> [u8; 20] {
552    let mut h: [u32; 5] = [0x67452301, 0xEFCDAB89, 0x98BADCFE, 0x10325476, 0xC3D2E1F0];
553
554    #[inline(always)]
555    fn compress(h: &mut [u32; 5], block: &[u8; 64]) {
556        // Decode and extend the message schedule to 80 big-endian words.
557        let mut w = [0u32; 80];
558        for (i, word) in w.iter_mut().take(16).enumerate() {
559            *word = u32::from_be_bytes([
560                block[4 * i],
561                block[4 * i + 1],
562                block[4 * i + 2],
563                block[4 * i + 3],
564            ]);
565        }
566        for i in 16..80 {
567            w[i] = (w[i - 3] ^ w[i - 8] ^ w[i - 14] ^ w[i - 16]).rotate_left(1);
568        }
569        let (mut a, mut b, mut c, mut d, mut e) = (h[0], h[1], h[2], h[3], h[4]);
570        for (i, &wi) in w.iter().enumerate() {
571            let (f, k) = match i {
572                0..=19 => ((b & c) | (!b & d), 0x5A827999),
573                20..=39 => (b ^ c ^ d, 0x6ED9EBA1),
574                40..=59 => ((b & c) | (b & d) | (c & d), 0x8F1BBCDC),
575                _ => (b ^ c ^ d, 0xCA62C1D6),
576            };
577            let tmp = a
578                .rotate_left(5)
579                .wrapping_add(f)
580                .wrapping_add(e)
581                .wrapping_add(k)
582                .wrapping_add(wi);
583            e = d;
584            d = c;
585            c = b.rotate_left(30);
586            b = a;
587            a = tmp;
588        }
589        h[0] = h[0].wrapping_add(a);
590        h[1] = h[1].wrapping_add(b);
591        h[2] = h[2].wrapping_add(c);
592        h[3] = h[3].wrapping_add(d);
593        h[4] = h[4].wrapping_add(e);
594    }
595
596    each_padded_block(data, Endian::Big, |block| compress(&mut h, block));
597
598    let mut out = [0u8; 20];
599    for (i, hi) in h.iter().enumerate() {
600        out[4 * i..4 * i + 4].copy_from_slice(&hi.to_be_bytes());
601    }
602    out
603}
604
605#[derive(Clone, Copy)]
606enum Endian {
607    Little,
608    Big,
609}
610
611/// Drive `compress` over the Merkle–Damgård padded message — ALLOC-FREE. Full 64-byte blocks are
612/// fed directly from `data` (no copy); only the final partial block plus the `0x80`/zero/length
613/// padding is staged in a 128-byte stack buffer (the padding spills to a second block when the tail
614/// is ≥ 56 bytes). The bit length is little-endian for MD5, big-endian for SHA-1. This keeps the hot
615/// path — small UUID inputs — entirely on the stack.
616#[inline(always)]
617fn each_padded_block(data: &[u8], endian: Endian, mut compress: impl FnMut(&[u8; 64])) {
618    let mut chunks = data.chunks_exact(64);
619    for chunk in &mut chunks {
620        let mut block = [0u8; 64];
621        block.copy_from_slice(chunk);
622        compress(&block);
623    }
624    let rem = chunks.remainder();
625    let bit_len = (data.len() as u64).wrapping_mul(8);
626    let len_bytes = match endian {
627        Endian::Little => bit_len.to_le_bytes(),
628        Endian::Big => bit_len.to_be_bytes(),
629    };
630
631    let mut tail = [0u8; 128];
632    tail[..rem.len()].copy_from_slice(rem);
633    tail[rem.len()] = 0x80;
634    if rem.len() < 56 {
635        // Padding + length fit in one final block.
636        tail[56..64].copy_from_slice(&len_bytes);
637        let mut b = [0u8; 64];
638        b.copy_from_slice(&tail[..64]);
639        compress(&b);
640    } else {
641        // Spills to a second block; the length goes at the very end.
642        tail[120..128].copy_from_slice(&len_bytes);
643        let mut b0 = [0u8; 64];
644        b0.copy_from_slice(&tail[..64]);
645        compress(&b0);
646        let mut b1 = [0u8; 64];
647        b1.copy_from_slice(&tail[64..128]);
648        compress(&b1);
649    }
650}
651
652/// Lowercase hex of a digest — handy for tests and debugging.
653pub fn to_hex(bytes: &[u8]) -> String {
654    const HEX: &[u8; 16] = b"0123456789abcdef";
655    let mut s = String::with_capacity(bytes.len() * 2);
656    for &b in bytes {
657        s.push(HEX[(b >> 4) as usize] as char);
658        s.push(HEX[(b & 0xf) as usize] as char);
659    }
660    s
661}
662
663/// SHA-1 over Intel SHA extensions (SHA-NI). Beats the scalar core by ~10× by running the round
664/// function in dedicated silicon (`_mm_sha1rnds4` etc.). Selected at runtime; the scalar core is the
665/// fallback. The instruction sequence is the canonical Intel reference (validated bit-exact against
666/// the `sha1` crate + RFC vectors in the tests).
667#[cfg(target_arch = "x86_64")]
668mod x86_sha {
669    use super::{each_padded_block, Endian};
670
671    /// True when the CPU has the SHA + SSSE3 + SSE4.1 instructions this path needs. `std`'s detection
672    /// caches the result, so this is a cheap load after the first call.
673    #[inline]
674    pub fn available() -> bool {
675        std::is_x86_feature_detected!("sha")
676            && std::is_x86_feature_detected!("ssse3")
677            && std::is_x86_feature_detected!("sse4.1")
678    }
679
680    /// Hash every (padded) block of `data` into `h`. Caller must ensure [`available`].
681    #[target_feature(enable = "sha,sse2,ssse3,sse4.1")]
682    pub unsafe fn sha1_blocks(data: &[u8], h: &mut [u32; 5]) {
683        each_padded_block(data, Endian::Big, |block| compress(h, block));
684    }
685
686    /// One 64-byte block through the SHA-NI round pipeline (Intel's `sha1_process_x86`).
687    #[target_feature(enable = "sha,sse2,ssse3,sse4.1")]
688    unsafe fn compress(state: &mut [u32; 5], block: &[u8; 64]) {
689        use core::arch::x86_64::*;
690
691        // Full 16-byte reversal: puts big-endian W0 in lane 3, aligned with A (lane 3) and the carried
692        // E (lane 3). E is NOT shuffled — `set_epi32(e,0,0,0)` already places it in lane 3.
693        let mask = _mm_set_epi64x(0x0001_0203_0405_0607, 0x0809_0a0b_0c0d_0e0fu64 as i64);
694        let mut abcd = _mm_shuffle_epi32(_mm_loadu_si128(state.as_ptr() as *const __m128i), 0x1B);
695        let mut e0 = _mm_set_epi32(state[4] as i32, 0, 0, 0);
696        let abcd_save = abcd;
697        let e0_save = e0;
698        let p = block.as_ptr();
699        let mut msg0 = _mm_shuffle_epi8(_mm_loadu_si128(p as *const __m128i), mask);
700        let mut msg1 = _mm_shuffle_epi8(_mm_loadu_si128(p.add(16) as *const __m128i), mask);
701        let mut msg2 = _mm_shuffle_epi8(_mm_loadu_si128(p.add(32) as *const __m128i), mask);
702        let mut msg3 = _mm_shuffle_epi8(_mm_loadu_si128(p.add(48) as *const __m128i), mask);
703        let mut e1;
704
705        // Rounds 0–3
706        e0 = _mm_add_epi32(e0, msg0);
707        e1 = abcd;
708        abcd = _mm_sha1rnds4_epu32(abcd, e0, 0);
709        // 4–7
710        e1 = _mm_sha1nexte_epu32(e1, msg1);
711        e0 = abcd;
712        abcd = _mm_sha1rnds4_epu32(abcd, e1, 0);
713        msg0 = _mm_sha1msg1_epu32(msg0, msg1);
714        // 8–11
715        e0 = _mm_sha1nexte_epu32(e0, msg2);
716        e1 = abcd;
717        abcd = _mm_sha1rnds4_epu32(abcd, e0, 0);
718        msg1 = _mm_sha1msg1_epu32(msg1, msg2);
719        msg0 = _mm_xor_si128(msg0, msg2);
720        // 12–15
721        e1 = _mm_sha1nexte_epu32(e1, msg3);
722        e0 = abcd;
723        msg0 = _mm_sha1msg2_epu32(msg0, msg3);
724        abcd = _mm_sha1rnds4_epu32(abcd, e1, 0);
725        msg2 = _mm_sha1msg1_epu32(msg2, msg3);
726        msg1 = _mm_xor_si128(msg1, msg3);
727        // 16–19
728        e0 = _mm_sha1nexte_epu32(e0, msg0);
729        e1 = abcd;
730        msg1 = _mm_sha1msg2_epu32(msg1, msg0);
731        abcd = _mm_sha1rnds4_epu32(abcd, e0, 0);
732        msg3 = _mm_sha1msg1_epu32(msg3, msg0);
733        msg2 = _mm_xor_si128(msg2, msg0);
734        // 20–23
735        e1 = _mm_sha1nexte_epu32(e1, msg1);
736        e0 = abcd;
737        msg2 = _mm_sha1msg2_epu32(msg2, msg1);
738        abcd = _mm_sha1rnds4_epu32(abcd, e1, 1);
739        msg0 = _mm_sha1msg1_epu32(msg0, msg1);
740        msg3 = _mm_xor_si128(msg3, msg1);
741        // 24–27
742        e0 = _mm_sha1nexte_epu32(e0, msg2);
743        e1 = abcd;
744        msg3 = _mm_sha1msg2_epu32(msg3, msg2);
745        abcd = _mm_sha1rnds4_epu32(abcd, e0, 1);
746        msg1 = _mm_sha1msg1_epu32(msg1, msg2);
747        msg0 = _mm_xor_si128(msg0, msg2);
748        // 28–31
749        e1 = _mm_sha1nexte_epu32(e1, msg3);
750        e0 = abcd;
751        msg0 = _mm_sha1msg2_epu32(msg0, msg3);
752        abcd = _mm_sha1rnds4_epu32(abcd, e1, 1);
753        msg2 = _mm_sha1msg1_epu32(msg2, msg3);
754        msg1 = _mm_xor_si128(msg1, msg3);
755        // 32–35
756        e0 = _mm_sha1nexte_epu32(e0, msg0);
757        e1 = abcd;
758        msg1 = _mm_sha1msg2_epu32(msg1, msg0);
759        abcd = _mm_sha1rnds4_epu32(abcd, e0, 1);
760        msg3 = _mm_sha1msg1_epu32(msg3, msg0);
761        msg2 = _mm_xor_si128(msg2, msg0);
762        // 36–39
763        e1 = _mm_sha1nexte_epu32(e1, msg1);
764        e0 = abcd;
765        msg2 = _mm_sha1msg2_epu32(msg2, msg1);
766        abcd = _mm_sha1rnds4_epu32(abcd, e1, 1);
767        msg0 = _mm_sha1msg1_epu32(msg0, msg1);
768        msg3 = _mm_xor_si128(msg3, msg1);
769        // 40–43
770        e0 = _mm_sha1nexte_epu32(e0, msg2);
771        e1 = abcd;
772        msg3 = _mm_sha1msg2_epu32(msg3, msg2);
773        abcd = _mm_sha1rnds4_epu32(abcd, e0, 2);
774        msg1 = _mm_sha1msg1_epu32(msg1, msg2);
775        msg0 = _mm_xor_si128(msg0, msg2);
776        // 44–47
777        e1 = _mm_sha1nexte_epu32(e1, msg3);
778        e0 = abcd;
779        msg0 = _mm_sha1msg2_epu32(msg0, msg3);
780        abcd = _mm_sha1rnds4_epu32(abcd, e1, 2);
781        msg2 = _mm_sha1msg1_epu32(msg2, msg3);
782        msg1 = _mm_xor_si128(msg1, msg3);
783        // 48–51
784        e0 = _mm_sha1nexte_epu32(e0, msg0);
785        e1 = abcd;
786        msg1 = _mm_sha1msg2_epu32(msg1, msg0);
787        abcd = _mm_sha1rnds4_epu32(abcd, e0, 2);
788        msg3 = _mm_sha1msg1_epu32(msg3, msg0);
789        msg2 = _mm_xor_si128(msg2, msg0);
790        // 52–55
791        e1 = _mm_sha1nexte_epu32(e1, msg1);
792        e0 = abcd;
793        msg2 = _mm_sha1msg2_epu32(msg2, msg1);
794        abcd = _mm_sha1rnds4_epu32(abcd, e1, 2);
795        msg0 = _mm_sha1msg1_epu32(msg0, msg1);
796        msg3 = _mm_xor_si128(msg3, msg1);
797        // 56–59
798        e0 = _mm_sha1nexte_epu32(e0, msg2);
799        e1 = abcd;
800        msg3 = _mm_sha1msg2_epu32(msg3, msg2);
801        abcd = _mm_sha1rnds4_epu32(abcd, e0, 2);
802        msg1 = _mm_sha1msg1_epu32(msg1, msg2);
803        msg0 = _mm_xor_si128(msg0, msg2);
804        // 60–63
805        e1 = _mm_sha1nexte_epu32(e1, msg3);
806        e0 = abcd;
807        msg0 = _mm_sha1msg2_epu32(msg0, msg3);
808        abcd = _mm_sha1rnds4_epu32(abcd, e1, 3);
809        msg2 = _mm_sha1msg1_epu32(msg2, msg3);
810        msg1 = _mm_xor_si128(msg1, msg3);
811        // 64–67
812        e0 = _mm_sha1nexte_epu32(e0, msg0);
813        e1 = abcd;
814        msg1 = _mm_sha1msg2_epu32(msg1, msg0);
815        abcd = _mm_sha1rnds4_epu32(abcd, e0, 3);
816        msg3 = _mm_sha1msg1_epu32(msg3, msg0);
817        msg2 = _mm_xor_si128(msg2, msg0);
818        // 68–71
819        e1 = _mm_sha1nexte_epu32(e1, msg1);
820        e0 = abcd;
821        msg2 = _mm_sha1msg2_epu32(msg2, msg1);
822        abcd = _mm_sha1rnds4_epu32(abcd, e1, 3);
823        msg3 = _mm_xor_si128(msg3, msg1);
824        // 72–75
825        e0 = _mm_sha1nexte_epu32(e0, msg2);
826        e1 = abcd;
827        msg3 = _mm_sha1msg2_epu32(msg3, msg2);
828        abcd = _mm_sha1rnds4_epu32(abcd, e0, 3);
829        // 76–79
830        e1 = _mm_sha1nexte_epu32(e1, msg3);
831        e0 = abcd;
832        abcd = _mm_sha1rnds4_epu32(abcd, e1, 3);
833
834        // Fold this block's result back into the running state.
835        e0 = _mm_sha1nexte_epu32(e0, e0_save);
836        abcd = _mm_add_epi32(abcd, abcd_save);
837
838        abcd = _mm_shuffle_epi32(abcd, 0x1B);
839        _mm_storeu_si128(state.as_mut_ptr() as *mut __m128i, abcd);
840        state[4] = _mm_extract_epi32(e0, 3) as u32;
841    }
842}
843
844#[cfg(test)]
845#[path = "../../logicaffeine_tests/unit/logicaffeine_base/hash/tests.rs"]
846mod tests;