Skip to main content

logicaffeine_base/
word.rs

1//! Fixed-width wrapping integers — the ring ℤ/2ᵏℤ.
2//!
3//! Unlike [`crate::numeric::BigInt`], whose arithmetic is exact and unbounded, a `Word`
4//! is **total and wrapping**: `Word32::MAX.add(Word32::ONE) == Word32::ZERO`. This is the
5//! natural home for the bit-twiddling primitives — ChaCha20 lives over `Word32`, Keccak
6//! over `Word64` — where each operation is a single native instruction and the modular
7//! semantics are exact rather than an overflow into arbitrary precision. Rotation
8//! (`rotl`/`rotr`) is width-defined and lives only here.
9
10macro_rules! impl_word {
11    ($name:ident, $prim:ty, $bits:literal) => {
12        #[doc = concat!("A ", $bits, "-bit wrapping integer: the ring ℤ/2^", $bits, "ℤ, where every operation is total and wraps modulo 2^", $bits, ".")]
13        #[derive(Clone, Copy, PartialEq, Eq, Hash, Debug, PartialOrd, Ord)]
14        #[repr(transparent)]
15        pub struct $name(pub $prim);
16
17        impl $name {
18            /// Bit width of the ring.
19            pub const BITS: u32 = <$prim>::BITS;
20            /// Additive identity.
21            pub const ZERO: Self = Self(0);
22            /// Multiplicative identity.
23            pub const ONE: Self = Self(1);
24            /// The all-ones value (`2^BITS − 1`).
25            pub const MAX: Self = Self(<$prim>::MAX);
26
27            /// The underlying primitive value.
28            #[inline]
29            pub const fn get(self) -> $prim {
30                self.0
31            }
32
33            /// Wrapping addition in ℤ/2ᵏ.
34            #[inline]
35            pub const fn add(self, o: Self) -> Self {
36                Self(self.0.wrapping_add(o.0))
37            }
38
39            /// Wrapping subtraction in ℤ/2ᵏ.
40            #[inline]
41            pub const fn sub(self, o: Self) -> Self {
42                Self(self.0.wrapping_sub(o.0))
43            }
44
45            /// Wrapping multiplication in ℤ/2ᵏ.
46            #[inline]
47            pub const fn mul(self, o: Self) -> Self {
48                Self(self.0.wrapping_mul(o.0))
49            }
50
51            /// Bitwise AND.
52            #[inline]
53            pub const fn bitand(self, o: Self) -> Self {
54                Self(self.0 & o.0)
55            }
56
57            /// Bitwise OR.
58            #[inline]
59            pub const fn bitor(self, o: Self) -> Self {
60                Self(self.0 | o.0)
61            }
62
63            /// Bitwise XOR.
64            #[inline]
65            pub const fn bitxor(self, o: Self) -> Self {
66                Self(self.0 ^ o.0)
67            }
68
69            /// Bitwise complement.
70            #[inline]
71            pub const fn not(self) -> Self {
72                Self(!self.0)
73            }
74
75            /// Logical left shift by `n` (the count is taken modulo `BITS`, matching the
76            /// hardware shift and the language's `shifted left by`).
77            #[inline]
78            pub const fn shl(self, n: u32) -> Self {
79                Self(self.0.wrapping_shl(n))
80            }
81
82            /// Logical right shift by `n` (count modulo `BITS`).
83            #[inline]
84            pub const fn shr(self, n: u32) -> Self {
85                Self(self.0.wrapping_shr(n))
86            }
87
88            /// Left rotation by `n` — a width-defined bit-permutation (the crypto primitive).
89            #[inline]
90            pub const fn rotl(self, n: u32) -> Self {
91                Self(self.0.rotate_left(n))
92            }
93
94            /// Right rotation by `n`.
95            #[inline]
96            pub const fn rotr(self, n: u32) -> Self {
97                Self(self.0.rotate_right(n))
98            }
99        }
100
101        // Operator traits delegate to the wrapping primitives, so generated Rust can write the
102        // natural `a + b` / `a ^ b` and get ring semantics — no per-site `wrapping_*` in codegen.
103        impl ::core::ops::Add for $name {
104            type Output = Self;
105            #[inline]
106            fn add(self, o: Self) -> Self { Self(self.0.wrapping_add(o.0)) }
107        }
108        impl ::core::ops::Sub for $name {
109            type Output = Self;
110            #[inline]
111            fn sub(self, o: Self) -> Self { Self(self.0.wrapping_sub(o.0)) }
112        }
113        impl ::core::ops::Mul for $name {
114            type Output = Self;
115            #[inline]
116            fn mul(self, o: Self) -> Self { Self(self.0.wrapping_mul(o.0)) }
117        }
118        impl ::core::ops::BitAnd for $name {
119            type Output = Self;
120            #[inline]
121            fn bitand(self, o: Self) -> Self { Self(self.0 & o.0) }
122        }
123        impl ::core::ops::BitOr for $name {
124            type Output = Self;
125            #[inline]
126            fn bitor(self, o: Self) -> Self { Self(self.0 | o.0) }
127        }
128        impl ::core::ops::BitXor for $name {
129            type Output = Self;
130            #[inline]
131            fn bitxor(self, o: Self) -> Self { Self(self.0 ^ o.0) }
132        }
133        impl ::core::ops::Not for $name {
134            type Output = Self;
135            #[inline]
136            fn not(self) -> Self { Self(!self.0) }
137        }
138        // `/` and `%` are the underlying UNSIGNED integer division / remainder — so `x % 2^k` is a
139        // mask and `x / 2^k` a shift (the crypto reduction primitives), with no sign-correction.
140        impl ::core::ops::Div for $name {
141            type Output = Self;
142            #[inline]
143            fn div(self, o: Self) -> Self { Self(self.0 / o.0) }
144        }
145        impl ::core::ops::Rem for $name {
146            type Output = Self;
147            #[inline]
148            fn rem(self, o: Self) -> Self { Self(self.0 % o.0) }
149        }
150        impl ::core::ops::Shl<u32> for $name {
151            type Output = Self;
152            #[inline]
153            fn shl(self, n: u32) -> Self { Self(self.0.wrapping_shl(n)) }
154        }
155        impl ::core::ops::Shr<u32> for $name {
156            type Output = Self;
157            #[inline]
158            fn shr(self, n: u32) -> Self { Self(self.0.wrapping_shr(n)) }
159        }
160        // Displays as the underlying unsigned value (decimal) — the canonical scalar form the
161        // tree-walker prints, so tw / VM / AOT render a word identically.
162        impl ::core::fmt::Display for $name {
163            #[inline]
164            fn fmt(&self, f: &mut ::core::fmt::Formatter<'_>) -> ::core::fmt::Result {
165                ::core::write!(f, "{}", self.0)
166            }
167        }
168    };
169}
170
171impl_word!(Word8, u8, "8");
172impl_word!(Word16, u16, "16");
173impl_word!(Word32, u32, "32");
174impl_word!(Word64, u64, "64");
175
176/// A fixed-width wrapping integer of any supported width — the single runtime carrier for
177/// `Word8`/`Word16`/`Word32`/`Word64` across the interpreter, VM, and wire, so the rest of the system
178/// matches on one `Word` value rather than a type per width. Each width is its own ring: a `Word16`
179/// wraps at 2¹⁶ exactly as the compiled tier's `Word16` newtype does. Binary ops require matching
180/// widths; a width mismatch is a type error the caller reports (the ops return `None`).
181#[derive(Clone, Copy, PartialEq, Eq, Hash, Debug)]
182pub enum WordVal {
183    /// An 8-bit wrapping value.
184    W8(Word8),
185    /// A 16-bit wrapping value.
186    W16(Word16),
187    /// A 32-bit wrapping value.
188    W32(Word32),
189    /// A 64-bit wrapping value.
190    W64(Word64),
191}
192
193/// Apply one width-generic binary expression to two words of the SAME width.
194macro_rules! word_zip {
195    ($x:expr, $y:expr, |$a:ident, $b:ident| $e:expr) => {
196        match ($x, $y) {
197            (WordVal::W8($a), WordVal::W8($b)) => Some(WordVal::W8($e)),
198            (WordVal::W16($a), WordVal::W16($b)) => Some(WordVal::W16($e)),
199            (WordVal::W32($a), WordVal::W32($b)) => Some(WordVal::W32($e)),
200            (WordVal::W64($a), WordVal::W64($b)) => Some(WordVal::W64($e)),
201            _ => None,
202        }
203    };
204}
205
206/// Apply one width-generic unary expression, preserving the width.
207macro_rules! word_map {
208    ($x:expr, |$a:ident| $e:expr) => {
209        match $x {
210            WordVal::W8($a) => WordVal::W8($e),
211            WordVal::W16($a) => WordVal::W16($e),
212            WordVal::W32($a) => WordVal::W32($e),
213            WordVal::W64($a) => WordVal::W64($e),
214        }
215    };
216}
217
218impl WordVal {
219    /// Every width a word can have, narrowest first.
220    pub const WIDTHS: [u32; 4] = [8, 16, 32, 64];
221
222    /// Bit width: 8, 16, 32, or 64.
223    #[inline]
224    pub const fn width(self) -> u32 {
225        match self {
226            WordVal::W8(_) => 8,
227            WordVal::W16(_) => 16,
228            WordVal::W32(_) => 32,
229            WordVal::W64(_) => 64,
230        }
231    }
232
233    /// The value zero-extended to `u64` — the canonical scalar form for display, hashing into
234    /// other contexts, and the wire.
235    #[inline]
236    pub const fn to_u64(self) -> u64 {
237        match self {
238            WordVal::W8(w) => w.0 as u64,
239            WordVal::W16(w) => w.0 as u64,
240            WordVal::W32(w) => w.0 as u64,
241            WordVal::W64(w) => w.0,
242        }
243    }
244
245    /// Build a word of the given `width` from the low bits of `bits` (the value is reduced into the
246    /// width's ring); `None` for a width that is not 8, 16, 32, or 64.
247    #[inline]
248    pub const fn from_u64(width: u32, bits: u64) -> Option<Self> {
249        match width {
250            8 => Some(WordVal::W8(Word8(bits as u8))),
251            16 => Some(WordVal::W16(Word16(bits as u16))),
252            32 => Some(WordVal::W32(Word32(bits as u32))),
253            64 => Some(WordVal::W64(Word64(bits))),
254            _ => None,
255        }
256    }
257
258    /// The type name (`Word8` … `Word64`) — what errors and `type_name` report.
259    #[inline]
260    pub const fn type_name(self) -> &'static str {
261        match self {
262            WordVal::W8(_) => "Word8",
263            WordVal::W16(_) => "Word16",
264            WordVal::W32(_) => "Word32",
265            WordVal::W64(_) => "Word64",
266        }
267    }
268
269    /// Wrapping addition; `None` on a width mismatch.
270    #[inline]
271    pub fn add(self, o: Self) -> Option<Self> {
272        word_zip!(self, o, |a, b| a.add(b))
273    }
274    /// Wrapping subtraction; `None` on a width mismatch.
275    #[inline]
276    pub fn sub(self, o: Self) -> Option<Self> {
277        word_zip!(self, o, |a, b| a.sub(b))
278    }
279    /// Wrapping multiplication; `None` on a width mismatch.
280    #[inline]
281    pub fn mul(self, o: Self) -> Option<Self> {
282        word_zip!(self, o, |a, b| a.mul(b))
283    }
284    /// Truncating unsigned division; `None` on a width mismatch. The caller must ensure a
285    /// non-zero divisor — the concrete `/` panics on zero, exactly as the AOT `Word` newtype
286    /// (and the native unsigned integers) do.
287    #[inline]
288    pub fn div(self, o: Self) -> Option<Self> {
289        word_zip!(self, o, |a, b| a / b)
290    }
291    /// Unsigned remainder; `None` on a width mismatch. The caller must ensure a non-zero divisor.
292    #[inline]
293    pub fn rem(self, o: Self) -> Option<Self> {
294        word_zip!(self, o, |a, b| a % b)
295    }
296    /// Bitwise AND; `None` on a width mismatch.
297    #[inline]
298    pub fn bitand(self, o: Self) -> Option<Self> {
299        word_zip!(self, o, |a, b| a.bitand(b))
300    }
301    /// Bitwise OR; `None` on a width mismatch.
302    #[inline]
303    pub fn bitor(self, o: Self) -> Option<Self> {
304        word_zip!(self, o, |a, b| a.bitor(b))
305    }
306    /// Bitwise XOR; `None` on a width mismatch.
307    #[inline]
308    pub fn bitxor(self, o: Self) -> Option<Self> {
309        word_zip!(self, o, |a, b| a.bitxor(b))
310    }
311
312    /// Bitwise complement (width-preserving).
313    #[inline]
314    pub const fn not(self) -> Self {
315        word_map!(self, |w| w.not())
316    }
317    /// Logical left shift by `n` (width-preserving; the count is taken modulo the width).
318    #[inline]
319    pub const fn shl(self, n: u32) -> Self {
320        word_map!(self, |w| w.shl(n))
321    }
322    /// Logical right shift by `n` (width-preserving; the count is taken modulo the width).
323    #[inline]
324    pub const fn shr(self, n: u32) -> Self {
325        word_map!(self, |w| w.shr(n))
326    }
327    /// Left rotation by `n` (width-preserving) — the bit-permutation crypto needs.
328    #[inline]
329    pub const fn rotl(self, n: u32) -> Self {
330        word_map!(self, |w| w.rotl(n))
331    }
332    /// Right rotation by `n` (width-preserving).
333    #[inline]
334    pub const fn rotr(self, n: u32) -> Self {
335        word_map!(self, |w| w.rotr(n))
336    }
337}
338
339impl std::fmt::Display for WordVal {
340    /// A word renders as its unsigned decimal value (no width suffix), so a `Word32` holding 5
341    /// and an `Int` 5 print identically — the value is what `Show` reports.
342    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
343        write!(f, "{}", self.to_u64())
344    }
345}
346
347// ── SIMD lane vectors — fixed-width vectors over the Word ring ─────────────────────────────────
348//
349// `Lanes8Word32` is 8 lanes of `Word32` = exactly one AVX2 `__m256i`. The whole point of the type
350// is that a vectorized algorithm WRITTEN in Logos over these lanes compiles to the same instructions
351// as hand-written AVX2 (each lane op IS an intrinsic). The runtime carries the portable scalar
352// representation `[u32; 8]`; every lane op has an AVX2 fast path AND a scalar fallback, and the two
353// are proven byte-identical by a fuzz test (the SIMD-correctness proof at the base level). The
354// language's tier differential (tree-walker == VM == AOT) then proves the pipeline lowers it right.
355
356/// Eight lanes of `Word32` (one 256-bit SIMD register). Operations are lane-wise over the ℤ/2³² ring.
357#[derive(Clone, Copy, PartialEq, Eq, Hash, Debug)]
358#[repr(C, align(32))]
359pub struct Lanes8Word32(pub [u32; 8]);
360
361impl Lanes8Word32 {
362    /// The number of lanes.
363    pub const LANES: usize = 8;
364
365    /// Broadcast one value into all eight lanes.
366    #[inline]
367    pub const fn splat(x: u32) -> Self {
368        Self([x; 8])
369    }
370
371    /// Pack the first eight `Word32`s of a slice into a lane vector (shorter slices zero-fill).
372    #[inline]
373    pub fn from_words(s: &[Word32]) -> Self {
374        let mut a = [0u32; 8];
375        for (i, w) in s.iter().take(8).enumerate() {
376            a[i] = w.0;
377        }
378        Self(a)
379    }
380
381    /// The lanes as eight `Word32`s.
382    #[inline]
383    pub fn to_words(self) -> [Word32; 8] {
384        self.0.map(Word32)
385    }
386
387    /// Lane `i` (0-based) as a `Word32`.
388    #[inline]
389    pub fn lane(self, i: usize) -> Word32 {
390        Word32(self.0[i])
391    }
392
393    /// Lane-wise XOR (`vpxor`). `#[inline(always)]` + compile-time `cfg(target_feature="avx2")`
394    /// intrinsics so a hot Logos lane kernel (ChaCha/NTT) inlines register-resident under `+avx2`
395    /// (no per-op `#[target_feature]` call boundary — that pessimizes ~20× on Keccak-scale kernels).
396    #[inline(always)]
397    pub fn bitxor(self, o: Self) -> Self {
398        #[cfg(all(target_arch = "x86_64", target_feature = "avx2"))]
399        unsafe {
400            use std::arch::x86_64::*;
401            let a = _mm256_loadu_si256(self.0.as_ptr() as *const __m256i);
402            let b = _mm256_loadu_si256(o.0.as_ptr() as *const __m256i);
403            let mut r = [0u32; 8];
404            _mm256_storeu_si256(r.as_mut_ptr() as *mut __m256i, _mm256_xor_si256(a, b));
405            return Self(r);
406        }
407        #[allow(unreachable_code)]
408        {
409            let mut r = [0u32; 8];
410            for i in 0..8 {
411                r[i] = self.0[i] ^ o.0[i];
412            }
413            Self(r)
414        }
415    }
416
417    /// Scalar lane-wise reference implementations — the *spec* the AVX2 lowerings are fuzz-checked
418    /// against. Test-only: each dispatched op inlines its own `#[allow(unreachable_code)]` scalar
419    /// fallback, so these exist purely as the independent differential oracle.
420    #[cfg(test)]
421    #[inline]
422    fn bitxor_scalar(self, o: Self) -> Self {
423        Self(core::array::from_fn(|i| self.0[i] ^ o.0[i]))
424    }
425    #[cfg(test)]
426    #[inline]
427    fn add_scalar(self, o: Self) -> Self {
428        Self(core::array::from_fn(|i| self.0[i].wrapping_add(o.0[i])))
429    }
430    #[cfg(test)]
431    #[inline]
432    fn sub_scalar(self, o: Self) -> Self {
433        Self(core::array::from_fn(|i| self.0[i].wrapping_sub(o.0[i])))
434    }
435    #[cfg(test)]
436    #[inline]
437    fn rotl_scalar(self, n: u32) -> Self {
438        Self(core::array::from_fn(|i| self.0[i].rotate_left(n)))
439    }
440    #[cfg(test)]
441    #[inline]
442    fn montmul32_scalar(self, b: Self, q: Self, qinv: Self) -> Self {
443        Self(core::array::from_fn(|i| {
444            let p = (self.0[i] as i32 as i64) * (b.0[i] as i32 as i64);
445            let t = (p as i32).wrapping_mul(qinv.0[i] as i32) as i64;
446            (((p - t * (q.0[i] as i32 as i64)) >> 32) as i32) as u32
447        }))
448    }
449
450    /// Lane-wise AND (`_mm256_and_si256`) — the MD5 F/G-function bit mixing; LLVM lowers the loop to one
451    /// `vpand`. AND/OR/NOT have no cross-lane dependency, so the scalar form auto-vectorizes cleanly.
452    #[inline]
453    pub fn bitand(self, o: Self) -> Self {
454        let mut r = [0u32; 8];
455        for i in 0..8 {
456            r[i] = self.0[i] & o.0[i];
457        }
458        Self(r)
459    }
460
461    /// Lane-wise OR (`_mm256_or_si256`).
462    #[inline]
463    pub fn bitor(self, o: Self) -> Self {
464        let mut r = [0u32; 8];
465        for i in 0..8 {
466            r[i] = self.0[i] | o.0[i];
467        }
468        Self(r)
469    }
470
471    /// Lane-wise complement (`vpxor` with all-ones) — MD5's `~b`/`~d` terms.
472    #[inline]
473    pub fn not(self) -> Self {
474        let mut r = [0u32; 8];
475        for i in 0..8 {
476            r[i] = !self.0[i];
477        }
478        Self(r)
479    }
480
481    /// Lane-wise wrapping add in ℤ/2³² (`vpaddd`) — cfg-inline so it fuses into hot Logos lane kernels.
482    #[inline(always)]
483    pub fn add(self, o: Self) -> Self {
484        #[cfg(all(target_arch = "x86_64", target_feature = "avx2"))]
485        unsafe {
486            use std::arch::x86_64::*;
487            let a = _mm256_loadu_si256(self.0.as_ptr() as *const __m256i);
488            let b = _mm256_loadu_si256(o.0.as_ptr() as *const __m256i);
489            let mut r = [0u32; 8];
490            _mm256_storeu_si256(r.as_mut_ptr() as *mut __m256i, _mm256_add_epi32(a, b));
491            return Self(r);
492        }
493        #[allow(unreachable_code)]
494        {
495            let mut r = [0u32; 8];
496            for i in 0..8 {
497                r[i] = self.0[i].wrapping_add(o.0[i]);
498            }
499            Self(r)
500        }
501    }
502
503    /// Lane-wise left rotation by `n` (ChaCha diffusion) — `(x<<n)|(x>>(32−n))` via `vpslld`/`vpsrld`.
504    /// cfg-inline; `n` is taken mod 32 (n = 0 → the `32−n = 32` shift zeroes → identity).
505    #[inline(always)]
506    pub fn rotl(self, n: u32) -> Self {
507        let n = n % 32;
508        #[cfg(all(target_arch = "x86_64", target_feature = "avx2"))]
509        unsafe {
510            use std::arch::x86_64::*;
511            let x = _mm256_loadu_si256(self.0.as_ptr() as *const __m256i);
512            let l = _mm256_sll_epi32(x, _mm_cvtsi32_si128(n as i32));
513            let r_sh = _mm256_srl_epi32(x, _mm_cvtsi32_si128((32 - n) as i32));
514            let mut r = [0u32; 8];
515            _mm256_storeu_si256(r.as_mut_ptr() as *mut __m256i, _mm256_or_si256(l, r_sh));
516            return Self(r);
517        }
518        #[allow(unreachable_code)]
519        {
520            let mut r = [0u32; 8];
521            for i in 0..8 {
522                r[i] = self.0[i].rotate_left(n);
523            }
524            Self(r)
525        }
526    }
527
528    /// Lane-wise wrapping subtract in ℤ/2³² (`vpsubd`) — the i32 NTT butterfly's difference. cfg-inline.
529    #[inline(always)]
530    pub fn sub(self, o: Self) -> Self {
531        #[cfg(all(target_arch = "x86_64", target_feature = "avx2"))]
532        unsafe {
533            use std::arch::x86_64::*;
534            let a = _mm256_loadu_si256(self.0.as_ptr() as *const __m256i);
535            let b = _mm256_loadu_si256(o.0.as_ptr() as *const __m256i);
536            let mut r = [0u32; 8];
537            _mm256_storeu_si256(r.as_mut_ptr() as *mut __m256i, _mm256_sub_epi32(a, b));
538            return Self(r);
539        }
540        #[allow(unreachable_code)]
541        {
542            let mut r = [0u32; 8];
543            for i in 0..8 {
544                r[i] = self.0[i].wrapping_sub(o.0[i]);
545            }
546            Self(r)
547        }
548    }
549
550    /// The signed i32 Montgomery multiply — per lane `montgomery_reduce(aᵢ·bᵢ) = (aᵢbᵢ − t·q)≫32`,
551    /// `t = (aᵢbᵢ mod 2³²)·qinv`, the ML-DSA (Dilithium) NTT butterfly's multiply (q = 8380417,
552    /// q,qinv broadcast). AVX2: `vpmuldq` the even and the (≫32) odd 32-bit lanes to eight i64
553    /// products, reduce each (the result lands in the high 32 bits), recombine with `vpblendd`.
554    #[inline(always)]
555    pub fn montmul32(self, b: Self, q: Self, qinv: Self) -> Self {
556        #[cfg(all(target_arch = "x86_64", target_feature = "avx2"))]
557        unsafe {
558            use std::arch::x86_64::*;
559            let a = _mm256_loadu_si256(self.0.as_ptr() as *const __m256i);
560            let bb = _mm256_loadu_si256(b.0.as_ptr() as *const __m256i);
561            let qv = _mm256_loadu_si256(q.0.as_ptr() as *const __m256i);
562            let qiv = _mm256_loadu_si256(qinv.0.as_ptr() as *const __m256i);
563            // Eight i64 products: even 32-bit lanes directly, odd lanes shifted into even position.
564            let pe = _mm256_mul_epi32(a, bb);
565            let po = _mm256_mul_epi32(_mm256_srli_epi64(a, 32), _mm256_srli_epi64(bb, 32));
566            // Reduce: t = (p mod 2³²)·qinv; re = p − t·q lives in the high 32.
567            let te = _mm256_mul_epi32(pe, qiv);
568            let re = _mm256_sub_epi64(pe, _mm256_mul_epi32(te, qv));
569            let to = _mm256_mul_epi32(po, qiv);
570            let ro = _mm256_sub_epi64(po, _mm256_mul_epi32(to, qv));
571            let res = _mm256_blend_epi32(_mm256_srli_epi64(re, 32), ro, 0xAA);
572            let mut r = [0u32; 8];
573            _mm256_storeu_si256(r.as_mut_ptr() as *mut __m256i, res);
574            return Self(r);
575        }
576        #[allow(unreachable_code)]
577        {
578            let qq = q.0[0] as i32 as i64;
579            let qi = qinv.0[0] as i32;
580            let mut r = [0u32; 8];
581            for i in 0..8 {
582                let p = (self.0[i] as i32 as i64) * (b.0[i] as i32 as i64);
583                let t = (p as i32).wrapping_mul(qi) as i64;
584                r[i] = (((p - t * qq) >> 32) as i32) as u32;
585            }
586            Self(r)
587        }
588    }
589
590    /// Broadcast each `2h`-block's low `h` lanes into both halves — the within-vector NTT source-low
591    /// duplication for 8 i32 lanes, stride `h ∈ {4,2,1}`. `h=4`→`vperm2i128(0x00)` (128-bit halves);
592    /// `h=2`→`vpshufd(0x44)`; `h=1`→`vpshufd(0xA0)`. (The byte op is the i16 stride-`2h` shuffle.)
593    #[inline(always)]
594    pub fn ntt_bcast_lo(self, h: usize) -> Self {
595        #[cfg(all(target_arch = "x86_64", target_feature = "avx2"))]
596        unsafe {
597            use std::arch::x86_64::*;
598            let a = _mm256_loadu_si256(self.0.as_ptr() as *const __m256i);
599            let v = match h {
600                4 => _mm256_permute2x128_si256::<0x00>(a, a),
601                2 => _mm256_shuffle_epi32::<0x44>(a),
602                1 => _mm256_shuffle_epi32::<0xA0>(a),
603                _ => unreachable!("i32 within-vector NTT stride is 4/2/1"),
604            };
605            let mut r = [0u32; 8];
606            _mm256_storeu_si256(r.as_mut_ptr() as *mut __m256i, v);
607            return Self(r);
608        }
609        #[allow(unreachable_code)]
610        Self(core::array::from_fn(|i| {
611            self.0[(i / (2 * h)) * (2 * h) + (i % (2 * h)) % h]
612        }))
613    }
614
615    /// Broadcast each `2h`-block's high `h` lanes into both halves. `h=4`→`vperm2i128(0x11)`;
616    /// `h=2`→`vpshufd(0xEE)`; `h=1`→`vpshufd(0xF5)`.
617    #[inline(always)]
618    pub fn ntt_bcast_hi(self, h: usize) -> Self {
619        #[cfg(all(target_arch = "x86_64", target_feature = "avx2"))]
620        unsafe {
621            use std::arch::x86_64::*;
622            let a = _mm256_loadu_si256(self.0.as_ptr() as *const __m256i);
623            let v = match h {
624                4 => _mm256_permute2x128_si256::<0x11>(a, a),
625                2 => _mm256_shuffle_epi32::<0xEE>(a),
626                1 => _mm256_shuffle_epi32::<0xF5>(a),
627                _ => unreachable!("i32 within-vector NTT stride is 4/2/1"),
628            };
629            let mut r = [0u32; 8];
630            _mm256_storeu_si256(r.as_mut_ptr() as *mut __m256i, v);
631            return Self(r);
632        }
633        #[allow(unreachable_code)]
634        Self(core::array::from_fn(|i| {
635            self.0[(i / (2 * h)) * (2 * h) + h + (i % (2 * h)) % h]
636        }))
637    }
638
639    /// Recombine the `+`/`−` halves: each `2h`-block's low `h` from `self`, high `h` from `o`.
640    /// `h=4`→`vperm2i128(0x30)`; `h=2`→`vpblendd(0xCC)`; `h=1`→`vpblendd(0xAA)`.
641    #[inline(always)]
642    pub fn ntt_blend(self, o: Self, h: usize) -> Self {
643        #[cfg(all(target_arch = "x86_64", target_feature = "avx2"))]
644        unsafe {
645            use std::arch::x86_64::*;
646            let a = _mm256_loadu_si256(self.0.as_ptr() as *const __m256i);
647            let b = _mm256_loadu_si256(o.0.as_ptr() as *const __m256i);
648            let v = match h {
649                4 => _mm256_permute2x128_si256::<0x30>(a, b),
650                2 => _mm256_blend_epi32::<0xCC>(a, b),
651                1 => _mm256_blend_epi32::<0xAA>(a, b),
652                _ => unreachable!("i32 within-vector NTT stride is 4/2/1"),
653            };
654            let mut r = [0u32; 8];
655            _mm256_storeu_si256(r.as_mut_ptr() as *mut __m256i, v);
656            return Self(r);
657        }
658        #[allow(unreachable_code)]
659        Self(core::array::from_fn(|i| {
660            if (i % (2 * h)) < h {
661                self.0[i]
662            } else {
663                o.0[i]
664            }
665        }))
666    }
667}
668
669// Operator traits delegate to the lane ops, so generated Rust writes the natural `v ^ w` / `v + w`
670// and gets the AVX2 lowering — the same free-operator path Word uses.
671impl ::core::ops::BitXor for Lanes8Word32 {
672    type Output = Self;
673    #[inline]
674    fn bitxor(self, o: Self) -> Self {
675        Lanes8Word32::bitxor(self, o)
676    }
677}
678impl ::core::ops::Add for Lanes8Word32 {
679    type Output = Self;
680    #[inline]
681    fn add(self, o: Self) -> Self {
682        Lanes8Word32::add(self, o)
683    }
684}
685impl ::core::ops::Sub for Lanes8Word32 {
686    type Output = Self;
687    #[inline]
688    fn sub(self, o: Self) -> Self {
689        Lanes8Word32::sub(self, o)
690    }
691}
692impl ::core::ops::BitAnd for Lanes8Word32 {
693    type Output = Self;
694    #[inline]
695    fn bitand(self, o: Self) -> Self {
696        Lanes8Word32::bitand(self, o)
697    }
698}
699impl ::core::ops::BitOr for Lanes8Word32 {
700    type Output = Self;
701    #[inline]
702    fn bitor(self, o: Self) -> Self {
703        Lanes8Word32::bitor(self, o)
704    }
705}
706impl ::core::ops::Not for Lanes8Word32 {
707    type Output = Self;
708    #[inline]
709    fn not(self) -> Self {
710        Lanes8Word32::not(self)
711    }
712}
713
714/// Four lanes of `Word32` = one 128-bit register (`__m128i`) — the SHA-1 state/message carrier. Unlike
715/// the arithmetic lane types, its vocabulary is the four Intel SHA operations (`sha1rnds4`/`sha1msg1`/
716/// `sha1msg2`/`sha1nexte`), so SHA-1 WRITTEN in Logos over these compiles to the `sha1rnds4` hardware
717/// sequence (AOT) and runs the byte-identical software spec [`crate::sha_ops`] on the interpreter.
718/// Lane `i` is bits `[32i+31 : 32i]` — index 0 low, index 3 high — matching `_mm_loadu_si128`.
719#[derive(Clone, Copy, PartialEq, Eq, Hash, Debug)]
720#[repr(C, align(16))]
721pub struct Lanes4Word32(pub [u32; 4]);
722
723impl Lanes4Word32 {
724    /// The number of lanes.
725    pub const LANES: usize = 4;
726
727    /// Broadcast one value into all four lanes.
728    #[inline]
729    pub const fn splat(x: u32) -> Self {
730        Self([x; 4])
731    }
732
733    /// Pack the first four `Word32`s of a slice (shorter slices zero-fill), lane 0 = element 0.
734    #[inline]
735    pub fn from_words(s: &[Word32]) -> Self {
736        let mut a = [0u32; 4];
737        for (i, w) in s.iter().take(4).enumerate() {
738            a[i] = w.0;
739        }
740        Self(a)
741    }
742
743    /// The lanes as four `Word32`s.
744    #[inline]
745    pub fn to_words(self) -> [Word32; 4] {
746        self.0.map(Word32)
747    }
748
749    /// Lane `i` (0-based) as a `Word32`.
750    #[inline]
751    pub fn lane(self, i: usize) -> Word32 {
752        Word32(self.0[i])
753    }
754
755    /// Four SHA-1 rounds (`sha1rnds4`), `func` ∈ 0..=3 — the Intel SHA-NI instruction when the CPU has
756    /// it, else the byte-identical software spec ([`crate::sha_ops`], proven equal by fuzz). `self` is
757    /// the ABCD state, `msg` the four message dwords with the round's E folded in.
758    #[inline(always)]
759    pub fn sha1rnds4(self, msg: Self, func: u32) -> Self {
760        // When the crate is built with SHA statically enabled (`target-cpu=native` or
761        // `-C target-feature=+sha`), the intrinsic is callable WITHOUT a `#[target_feature]` boundary,
762        // so this inlines and — chained across a compress — LLVM keeps the lanes in XMM registers
763        // (no per-op detect branch, no memory round-trip). The `not` arm is the portable runtime-detect.
764        #[cfg(all(target_arch = "x86_64", target_feature = "sha"))]
765        unsafe {
766            use core::arch::x86_64::*;
767            let a: __m128i = core::mem::transmute(self.0);
768            let b: __m128i = core::mem::transmute(msg.0);
769            let r = match func & 3 {
770                0 => _mm_sha1rnds4_epu32(a, b, 0),
771                1 => _mm_sha1rnds4_epu32(a, b, 1),
772                2 => _mm_sha1rnds4_epu32(a, b, 2),
773                _ => _mm_sha1rnds4_epu32(a, b, 3),
774            };
775            Self(core::mem::transmute(r))
776        }
777        #[cfg(not(all(target_arch = "x86_64", target_feature = "sha")))]
778        {
779            #[cfg(target_arch = "x86_64")]
780            {
781                if shani_available() {
782                    return unsafe { self.sha1rnds4_hw(msg, func) };
783                }
784            }
785            Self(crate::sha_ops::sha1rnds4(self.0, msg.0, func))
786        }
787    }
788    /// Message-schedule step 1 (`sha1msg1`).
789    #[inline(always)]
790    pub fn sha1msg1(self, o: Self) -> Self {
791        #[cfg(all(target_arch = "x86_64", target_feature = "sha"))]
792        unsafe {
793            use core::arch::x86_64::*;
794            let a: __m128i = core::mem::transmute(self.0);
795            let b: __m128i = core::mem::transmute(o.0);
796            Self(core::mem::transmute(_mm_sha1msg1_epu32(a, b)))
797        }
798        #[cfg(not(all(target_arch = "x86_64", target_feature = "sha")))]
799        {
800            #[cfg(target_arch = "x86_64")]
801            {
802                if shani_available() {
803                    return unsafe { self.sha1msg1_hw(o) };
804                }
805            }
806            Self(crate::sha_ops::sha1msg1(self.0, o.0))
807        }
808    }
809    /// Message-schedule step 2 (`sha1msg2`).
810    #[inline(always)]
811    pub fn sha1msg2(self, o: Self) -> Self {
812        #[cfg(all(target_arch = "x86_64", target_feature = "sha"))]
813        unsafe {
814            use core::arch::x86_64::*;
815            let a: __m128i = core::mem::transmute(self.0);
816            let b: __m128i = core::mem::transmute(o.0);
817            Self(core::mem::transmute(_mm_sha1msg2_epu32(a, b)))
818        }
819        #[cfg(not(all(target_arch = "x86_64", target_feature = "sha")))]
820        {
821            #[cfg(target_arch = "x86_64")]
822            {
823                if shani_available() {
824                    return unsafe { self.sha1msg2_hw(o) };
825                }
826            }
827            Self(crate::sha_ops::sha1msg2(self.0, o.0))
828        }
829    }
830    /// Fold the next round constant E (`sha1nexte`).
831    #[inline(always)]
832    pub fn sha1nexte(self, o: Self) -> Self {
833        #[cfg(all(target_arch = "x86_64", target_feature = "sha"))]
834        unsafe {
835            use core::arch::x86_64::*;
836            let a: __m128i = core::mem::transmute(self.0);
837            let b: __m128i = core::mem::transmute(o.0);
838            Self(core::mem::transmute(_mm_sha1nexte_epu32(a, b)))
839        }
840        #[cfg(not(all(target_arch = "x86_64", target_feature = "sha")))]
841        {
842            #[cfg(target_arch = "x86_64")]
843            {
844                if shani_available() {
845                    return unsafe { self.sha1nexte_hw(o) };
846                }
847            }
848            Self(crate::sha_ops::sha1nexte(self.0, o.0))
849        }
850    }
851
852    #[cfg(all(target_arch = "x86_64", not(target_feature = "sha")))]
853    #[target_feature(enable = "sha,sse2,sse4.1")]
854    unsafe fn sha1rnds4_hw(self, msg: Self, func: u32) -> Self {
855        use std::arch::x86_64::*;
856        let a = _mm_loadu_si128(self.0.as_ptr() as *const __m128i);
857        let b = _mm_loadu_si128(msg.0.as_ptr() as *const __m128i);
858        // The round-function selector is a compile-time immediate, so branch to the four forms.
859        let r = match func & 3 {
860            0 => _mm_sha1rnds4_epu32(a, b, 0),
861            1 => _mm_sha1rnds4_epu32(a, b, 1),
862            2 => _mm_sha1rnds4_epu32(a, b, 2),
863            _ => _mm_sha1rnds4_epu32(a, b, 3),
864        };
865        let mut out = [0u32; 4];
866        _mm_storeu_si128(out.as_mut_ptr() as *mut __m128i, r);
867        Self(out)
868    }
869
870    #[cfg(all(target_arch = "x86_64", not(target_feature = "sha")))]
871    #[target_feature(enable = "sha,sse2,ssse3,sse4.1")]
872    unsafe fn sha1msg1_hw(self, o: Self) -> Self {
873        use std::arch::x86_64::*;
874        let a = _mm_loadu_si128(self.0.as_ptr() as *const __m128i);
875        let b = _mm_loadu_si128(o.0.as_ptr() as *const __m128i);
876        let mut out = [0u32; 4];
877        _mm_storeu_si128(out.as_mut_ptr() as *mut __m128i, _mm_sha1msg1_epu32(a, b));
878        Self(out)
879    }
880
881    #[cfg(all(target_arch = "x86_64", not(target_feature = "sha")))]
882    #[target_feature(enable = "sha,sse2,ssse3,sse4.1")]
883    unsafe fn sha1msg2_hw(self, o: Self) -> Self {
884        use std::arch::x86_64::*;
885        let a = _mm_loadu_si128(self.0.as_ptr() as *const __m128i);
886        let b = _mm_loadu_si128(o.0.as_ptr() as *const __m128i);
887        let mut out = [0u32; 4];
888        _mm_storeu_si128(out.as_mut_ptr() as *mut __m128i, _mm_sha1msg2_epu32(a, b));
889        Self(out)
890    }
891
892    #[cfg(all(target_arch = "x86_64", not(target_feature = "sha")))]
893    #[target_feature(enable = "sha,sse2,sse4.1")]
894    unsafe fn sha1nexte_hw(self, o: Self) -> Self {
895        use std::arch::x86_64::*;
896        let a = _mm_loadu_si128(self.0.as_ptr() as *const __m128i);
897        let b = _mm_loadu_si128(o.0.as_ptr() as *const __m128i);
898        let mut out = [0u32; 4];
899        _mm_storeu_si128(out.as_mut_ptr() as *mut __m128i, _mm_sha1nexte_epu32(a, b));
900        Self(out)
901    }
902
903    /// Lane-wise wrapping add (`_mm_add_epi32`) — folds the round E into the message dwords and the
904    /// per-block state back into the running hash. LLVM lowers the four-lane loop to one `paddd`.
905    #[inline]
906    pub fn add(self, o: Self) -> Self {
907        let mut out = [0u32; 4];
908        for i in 0..4 {
909            out[i] = self.0[i].wrapping_add(o.0[i]);
910        }
911        Self(out)
912    }
913
914    /// Lane-wise XOR (`_mm_xor_si128`) — the message-schedule W_t ⊕ W_{t-2} coupling; lowers to `pxor`.
915    #[inline]
916    pub fn bitxor(self, o: Self) -> Self {
917        let mut out = [0u32; 4];
918        for i in 0..4 {
919            out[i] = self.0[i] ^ o.0[i];
920        }
921        Self(out)
922    }
923}
924
925impl ::core::ops::Add for Lanes4Word32 {
926    type Output = Self;
927    #[inline]
928    fn add(self, o: Self) -> Self {
929        Lanes4Word32::add(self, o)
930    }
931}
932impl ::core::ops::BitXor for Lanes4Word32 {
933    type Output = Self;
934    #[inline]
935    fn bitxor(self, o: Self) -> Self {
936        Lanes4Word32::bitxor(self, o)
937    }
938}
939
940/// Sixteen `Word8` lanes = one 128-bit register (`__m128i`) — the BYTE-SHUFFLE carrier for SIMD text
941/// codecs (hex encode/decode). Its vocabulary is `shuffle` (`pshufb`, a 16-entry byte LUT), byte AND,
942/// per-byte shift, and the two byte interleaves — so a hex codec WRITTEN in Logos over it compiles to
943/// the `pshufb` sequence (AOT, when SSSE3 is statically enabled) and runs the byte-identical scalar
944/// spec on the interpreter. Lane `i` is byte `i` (index 0 low), matching `_mm_loadu_si128`.
945#[derive(Clone, Copy, PartialEq, Eq, Hash, Debug)]
946#[repr(C, align(16))]
947pub struct Lanes16Word8(pub [u8; 16]);
948
949impl Lanes16Word8 {
950    /// The number of lanes.
951    pub const LANES: usize = 16;
952
953    /// Broadcast one byte into all sixteen lanes.
954    #[inline]
955    pub const fn splat(x: u8) -> Self {
956        Self([x; 16])
957    }
958
959    /// Pack the first sixteen bytes of a slice (shorter slices zero-fill).
960    #[inline]
961    pub fn from_bytes(s: &[u8]) -> Self {
962        let mut a = [0u8; 16];
963        for (i, b) in s.iter().take(16).enumerate() {
964            a[i] = *b;
965        }
966        Self(a)
967    }
968
969    /// The sixteen lane bytes.
970    #[inline]
971    pub fn to_bytes(self) -> [u8; 16] {
972        self.0
973    }
974
975    /// Lane `i` (0-based).
976    #[inline]
977    pub fn lane(self, i: usize) -> u8 {
978        self.0[i]
979    }
980
981    /// Byte shuffle (`pshufb`): `out[i] = if idx[i] & 0x80 { 0 } else { self[idx[i] & 0x0f] }` — a
982    /// 16-entry byte lookup, the core of SIMD hex codecs (nibble → hex char; hyphen strip).
983    #[inline]
984    pub fn shuffle(self, idx: Self) -> Self {
985        #[cfg(all(target_arch = "x86_64", target_feature = "ssse3"))]
986        unsafe {
987            use core::arch::x86_64::*;
988            let a: __m128i = core::mem::transmute(self.0);
989            let b: __m128i = core::mem::transmute(idx.0);
990            Self(core::mem::transmute(_mm_shuffle_epi8(a, b)))
991        }
992        #[cfg(not(all(target_arch = "x86_64", target_feature = "ssse3")))]
993        {
994            let mut r = [0u8; 16];
995            for i in 0..16 {
996                let x = idx.0[i];
997                r[i] = if x & 0x80 != 0 {
998                    0
999                } else {
1000                    self.0[(x & 0x0f) as usize]
1001                };
1002            }
1003            Self(r)
1004        }
1005    }
1006
1007    /// Lane-wise AND (`_mm_and_si128`) — the low-nibble mask; auto-vectorizes to `pand`.
1008    #[inline]
1009    pub fn bitand(self, o: Self) -> Self {
1010        let mut r = [0u8; 16];
1011        for i in 0..16 {
1012            r[i] = self.0[i] & o.0[i];
1013        }
1014        Self(r)
1015    }
1016
1017    /// Per-byte logical shift right by `n` — the high-nibble extract (`v >> 4`).
1018    #[inline]
1019    pub fn shr_bytes(self, n: u32) -> Self {
1020        let mut r = [0u8; 16];
1021        for i in 0..16 {
1022            r[i] = self.0[i] >> n;
1023        }
1024        Self(r)
1025    }
1026
1027    /// Interleave the low eight bytes (`_mm_unpacklo_epi8`): `[a0,b0,a1,b1,…,a7,b7]`.
1028    #[inline]
1029    pub fn interleave_lo(self, o: Self) -> Self {
1030        #[cfg(all(target_arch = "x86_64", target_feature = "ssse3"))]
1031        unsafe {
1032            use core::arch::x86_64::*;
1033            let a: __m128i = core::mem::transmute(self.0);
1034            let b: __m128i = core::mem::transmute(o.0);
1035            Self(core::mem::transmute(_mm_unpacklo_epi8(a, b)))
1036        }
1037        #[cfg(not(all(target_arch = "x86_64", target_feature = "ssse3")))]
1038        {
1039            let mut r = [0u8; 16];
1040            for i in 0..8 {
1041                r[2 * i] = self.0[i];
1042                r[2 * i + 1] = o.0[i];
1043            }
1044            Self(r)
1045        }
1046    }
1047
1048    /// Interleave the high eight bytes (`_mm_unpackhi_epi8`): `[a8,b8,…,a15,b15]`.
1049    #[inline]
1050    pub fn interleave_hi(self, o: Self) -> Self {
1051        #[cfg(all(target_arch = "x86_64", target_feature = "ssse3"))]
1052        unsafe {
1053            use core::arch::x86_64::*;
1054            let a: __m128i = core::mem::transmute(self.0);
1055            let b: __m128i = core::mem::transmute(o.0);
1056            Self(core::mem::transmute(_mm_unpackhi_epi8(a, b)))
1057        }
1058        #[cfg(not(all(target_arch = "x86_64", target_feature = "ssse3")))]
1059        {
1060            let mut r = [0u8; 16];
1061            for i in 0..8 {
1062                r[2 * i] = self.0[8 + i];
1063                r[2 * i + 1] = o.0[8 + i];
1064            }
1065            Self(r)
1066        }
1067    }
1068
1069    /// Per-byte wrapping add (`_mm_add_epi8`) — the ASCII→nibble decode (`lo + 9·hibit`).
1070    #[inline]
1071    pub fn byte_add(self, o: Self) -> Self {
1072        let mut r = [0u8; 16];
1073        for i in 0..16 {
1074            r[i] = self.0[i].wrapping_add(o.0[i]);
1075        }
1076        Self(r)
1077    }
1078
1079    /// Multiply-add adjacent byte pairs (`pmaddubsw`): `self` unsigned × `o` signed, summing pairs into
1080    /// eight saturating `i16` lanes stored little-endian. Weights `[16,1,…]` fuse each nibble pair into
1081    /// the decoded byte (hex parse). Result carries 8 `u16` in its 16 bytes; narrow with `packus`.
1082    #[inline]
1083    pub fn maddubs(self, o: Self) -> Self {
1084        let mut r = [0u8; 16];
1085        for i in 0..8 {
1086            let a0 = self.0[2 * i] as i32;
1087            let a1 = self.0[2 * i + 1] as i32;
1088            let b0 = o.0[2 * i] as i8 as i32;
1089            let b1 = o.0[2 * i + 1] as i8 as i32;
1090            let s = (a0 * b0 + a1 * b1).clamp(-32768, 32767) as i16 as u16;
1091            r[2 * i] = (s & 0xff) as u8;
1092            r[2 * i + 1] = (s >> 8) as u8;
1093        }
1094        Self(r)
1095    }
1096
1097    /// Pack two `8×i16` vectors to `16×u8` with unsigned saturation (`packuswb`): `self`'s eight 16-bit
1098    /// lanes → bytes 0–7, `o`'s → bytes 8–15. Narrows the `maddubs` output back to bytes.
1099    #[inline]
1100    pub fn packus(self, o: Self) -> Self {
1101        let mut r = [0u8; 16];
1102        for i in 0..8 {
1103            let a = (self.0[2 * i] as u16 | (self.0[2 * i + 1] as u16) << 8) as i16;
1104            r[i] = a.clamp(0, 255) as u8;
1105            let b = (o.0[2 * i] as u16 | (o.0[2 * i + 1] as u16) << 8) as i16;
1106            r[8 + i] = b.clamp(0, 255) as u8;
1107        }
1108        Self(r)
1109    }
1110}
1111
1112impl ::core::ops::BitAnd for Lanes16Word8 {
1113    type Output = Self;
1114    #[inline]
1115    fn bitand(self, o: Self) -> Self {
1116        Lanes16Word8::bitand(self, o)
1117    }
1118}
1119
1120/// True when the CPU has the SHA + SSE4.1 (+ SSSE3) instructions the SHA-NI lane ops use; `std` caches
1121/// the detection so this is a cheap load after the first call. Only the portable build path (SHA not
1122/// statically enabled) runtime-detects; a `target-feature=+sha` build skips it entirely.
1123#[cfg(all(target_arch = "x86_64", not(target_feature = "sha")))]
1124#[inline]
1125fn shani_available() -> bool {
1126    std::is_x86_feature_detected!("sha")
1127        && std::is_x86_feature_detected!("ssse3")
1128        && std::is_x86_feature_detected!("sse4.1")
1129}
1130
1131/// Four lanes of `Word64` (one 256-bit SIMD register) — the Poly1305 accumulator lane vector.
1132/// Carries `[u64; 4]`; ops have an AVX2 fast path proven byte-identical to the scalar lanes.
1133#[derive(Clone, Copy, PartialEq, Eq, Hash, Debug)]
1134#[repr(C, align(32))]
1135pub struct Lanes4Word64(pub [u64; 4]);
1136
1137impl Lanes4Word64 {
1138    /// The number of lanes.
1139    pub const LANES: usize = 4;
1140
1141    /// Pack the first four `Word64`s of a slice into a lane vector (shorter slices zero-fill).
1142    #[inline]
1143    pub fn from_words(s: &[Word64]) -> Self {
1144        let mut a = [0u64; 4];
1145        for (i, w) in s.iter().take(4).enumerate() {
1146            a[i] = w.0;
1147        }
1148        Self(a)
1149    }
1150
1151    /// The lanes as four `Word64`s.
1152    #[inline]
1153    pub fn to_words(self) -> [Word64; 4] {
1154        self.0.map(Word64)
1155    }
1156
1157    /// Lane `i` (0-based) as a `Word64`.
1158    #[inline]
1159    pub fn lane(self, i: usize) -> Word64 {
1160        Word64(self.0[i])
1161    }
1162
1163    /// The horizontal sum of the four lanes (wrapping in ℤ/2⁶⁴) — combines the per-lane partial
1164    /// products in a 4-way Poly1305 multiply. Reads the scalar array; no SIMD needed.
1165    #[inline]
1166    pub fn hsum(self) -> u64 {
1167        self.0[0]
1168            .wrapping_add(self.0[1])
1169            .wrapping_add(self.0[2])
1170            .wrapping_add(self.0[3])
1171    }
1172
1173    /// Lane-wise wrapping add in ℤ/2⁶⁴ (`vpaddq`). `#[inline(always)]` + compile-time
1174    /// `cfg(target_feature="avx2")` (no runtime `is_x86_feature_detected` branch, no `#[target_feature]`
1175    /// call boundary) so the 4-way Poly1305 accumulator stays register-resident under `+avx2`.
1176    #[inline(always)]
1177    pub fn add(self, o: Self) -> Self {
1178        #[cfg(all(target_arch = "x86_64", target_feature = "avx2"))]
1179        unsafe {
1180            use std::arch::x86_64::*;
1181            let a = _mm256_loadu_si256(self.0.as_ptr() as *const __m256i);
1182            let b = _mm256_loadu_si256(o.0.as_ptr() as *const __m256i);
1183            let mut r = [0u64; 4];
1184            _mm256_storeu_si256(r.as_mut_ptr() as *mut __m256i, _mm256_add_epi64(a, b));
1185            return Self(r);
1186        }
1187        #[allow(unreachable_code)]
1188        {
1189            let mut r = [0u64; 4];
1190            for i in 0..4 {
1191                r[i] = self.0[i].wrapping_add(o.0[i]);
1192            }
1193            Self(r)
1194        }
1195    }
1196
1197    #[cfg(test)]
1198    #[inline]
1199    fn add_scalar(self, o: Self) -> Self {
1200        let mut r = [0u64; 4];
1201        for i in 0..4 {
1202            r[i] = self.0[i].wrapping_add(o.0[i]);
1203        }
1204        Self(r)
1205    }
1206
1207    /// Lane-wise widening multiply of the low 32 bits: `(aₗₒ·bₗₒ)` per lane → a 64-bit product
1208    /// (`vpmuludq`). `#[inline(always)]` + compile-time `cfg(target_feature="avx2")` so the Poly1305
1209    /// 4-way limb multiply inlines register-resident under `+avx2`.
1210    #[inline(always)]
1211    pub fn mul_lo32_wide(self, o: Self) -> Self {
1212        #[cfg(all(target_arch = "x86_64", target_feature = "avx2"))]
1213        unsafe {
1214            use std::arch::x86_64::*;
1215            let a = _mm256_loadu_si256(self.0.as_ptr() as *const __m256i);
1216            let b = _mm256_loadu_si256(o.0.as_ptr() as *const __m256i);
1217            let mut r = [0u64; 4];
1218            _mm256_storeu_si256(r.as_mut_ptr() as *mut __m256i, _mm256_mul_epu32(a, b));
1219            return Self(r);
1220        }
1221        #[allow(unreachable_code)]
1222        {
1223            let mut r = [0u64; 4];
1224            for i in 0..4 {
1225                r[i] = (self.0[i] & 0xffff_ffff) * (o.0[i] & 0xffff_ffff);
1226            }
1227            Self(r)
1228        }
1229    }
1230
1231    #[cfg(test)]
1232    #[inline]
1233    fn mul_lo32_wide_scalar(self, o: Self) -> Self {
1234        let mut r = [0u64; 4];
1235        for i in 0..4 {
1236            r[i] = (self.0[i] & 0xffff_ffff) * (o.0[i] & 0xffff_ffff);
1237        }
1238        Self(r)
1239    }
1240
1241    // ── Bitwise ops — the 4-way Keccak-f[1600] substrate (θ/ρ/π/χ/ι over 4 independent states) ─────
1242    // `#[inline(always)]` with COMPILE-TIME `cfg(target_feature="avx2")` intrinsics (NOT a separate
1243    // `#[target_feature]` fn) so they inline straight into a hot kernel (Keccak's ~600 ops) with the
1244    // vectors register-resident — no per-op call boundary, no per-op runtime detect. This is what
1245    // closes the ~20× gap of a `#[target_feature]`-per-op lane Keccak (measured). A build with
1246    // `-C target-feature=+avx2` / `target-cpu=native` takes the fast path; otherwise portable scalar.
1247
1248    /// Broadcast one `u64` into all four lanes (Keccak's ι round-constant XOR is a splat).
1249    #[inline(always)]
1250    pub fn splat(x: u64) -> Self {
1251        Self([x; 4])
1252    }
1253
1254    /// Lane-wise XOR (`vpxor`) — θ column parity, χ, and ι.
1255    #[inline(always)]
1256    pub fn bitxor(self, o: Self) -> Self {
1257        #[cfg(all(target_arch = "x86_64", target_feature = "avx2"))]
1258        unsafe {
1259            use std::arch::x86_64::*;
1260            let a = _mm256_loadu_si256(self.0.as_ptr() as *const __m256i);
1261            let b = _mm256_loadu_si256(o.0.as_ptr() as *const __m256i);
1262            let mut r = [0u64; 4];
1263            _mm256_storeu_si256(r.as_mut_ptr() as *mut __m256i, _mm256_xor_si256(a, b));
1264            return Self(r);
1265        }
1266        #[allow(unreachable_code)]
1267        Self([
1268            self.0[0] ^ o.0[0],
1269            self.0[1] ^ o.0[1],
1270            self.0[2] ^ o.0[2],
1271            self.0[3] ^ o.0[3],
1272        ])
1273    }
1274
1275    /// Lane-wise AND (`vpand`).
1276    #[inline(always)]
1277    pub fn and(self, o: Self) -> Self {
1278        #[cfg(all(target_arch = "x86_64", target_feature = "avx2"))]
1279        unsafe {
1280            use std::arch::x86_64::*;
1281            let a = _mm256_loadu_si256(self.0.as_ptr() as *const __m256i);
1282            let b = _mm256_loadu_si256(o.0.as_ptr() as *const __m256i);
1283            let mut r = [0u64; 4];
1284            _mm256_storeu_si256(r.as_mut_ptr() as *mut __m256i, _mm256_and_si256(a, b));
1285            return Self(r);
1286        }
1287        #[allow(unreachable_code)]
1288        Self([
1289            self.0[0] & o.0[0],
1290            self.0[1] & o.0[1],
1291            self.0[2] & o.0[2],
1292            self.0[3] & o.0[3],
1293        ])
1294    }
1295
1296    /// Lane-wise AND-NOT `(¬self) & o` (`vpandn`) — Keccak's χ nonlinearity `¬bᵢ₊₁ ∧ bᵢ₊₂` in one op.
1297    #[inline(always)]
1298    pub fn andnot(self, o: Self) -> Self {
1299        #[cfg(all(target_arch = "x86_64", target_feature = "avx2"))]
1300        unsafe {
1301            use std::arch::x86_64::*;
1302            let a = _mm256_loadu_si256(self.0.as_ptr() as *const __m256i);
1303            let b = _mm256_loadu_si256(o.0.as_ptr() as *const __m256i);
1304            let mut r = [0u64; 4];
1305            _mm256_storeu_si256(r.as_mut_ptr() as *mut __m256i, _mm256_andnot_si256(a, b));
1306            return Self(r);
1307        }
1308        #[allow(unreachable_code)]
1309        Self([
1310            !self.0[0] & o.0[0],
1311            !self.0[1] & o.0[1],
1312            !self.0[2] & o.0[2],
1313            !self.0[3] & o.0[3],
1314        ])
1315    }
1316
1317    /// Lane-wise left rotation by `n` (mod 64) — Keccak's ρ offsets and θ's D term. `(x<<n)|(x>>(64−n))`
1318    /// via `vpsllq`/`vpsrlq` (n = 0 is the identity — the `64−n = 64` shift zeroes).
1319    #[inline(always)]
1320    pub fn rotl(self, n: u32) -> Self {
1321        let n = n % 64;
1322        #[cfg(all(target_arch = "x86_64", target_feature = "avx2"))]
1323        unsafe {
1324            use std::arch::x86_64::*;
1325            if n == 0 {
1326                return self;
1327            }
1328            let x = _mm256_loadu_si256(self.0.as_ptr() as *const __m256i);
1329            let l = _mm256_sll_epi64(x, _mm_cvtsi32_si128(n as i32));
1330            let r_sh = _mm256_srl_epi64(x, _mm_cvtsi32_si128((64 - n) as i32));
1331            let mut r = [0u64; 4];
1332            _mm256_storeu_si256(r.as_mut_ptr() as *mut __m256i, _mm256_or_si256(l, r_sh));
1333            return Self(r);
1334        }
1335        #[allow(unreachable_code)]
1336        {
1337            let mut r = [0u64; 4];
1338            for i in 0..4 {
1339                r[i] = self.0[i].rotate_left(n);
1340            }
1341            Self(r)
1342        }
1343    }
1344}
1345
1346impl ::core::ops::Add for Lanes4Word64 {
1347    type Output = Self;
1348    #[inline]
1349    fn add(self, o: Self) -> Self {
1350        Lanes4Word64::add(self, o)
1351    }
1352}
1353
1354impl ::core::ops::BitXor for Lanes4Word64 {
1355    type Output = Self;
1356    #[inline]
1357    fn bitxor(self, o: Self) -> Self {
1358        Lanes4Word64::bitxor(self, o)
1359    }
1360}
1361
1362impl ::core::ops::BitAnd for Lanes4Word64 {
1363    type Output = Self;
1364    #[inline]
1365    fn bitand(self, o: Self) -> Self {
1366        Lanes4Word64::and(self, o)
1367    }
1368}
1369
1370/// Sixteen lanes of `Word16` (one 256-bit SIMD register) — the NTT coefficient lane vector. Carries
1371/// `[u16; 16]`; the multiply-high is the SIGNED `_mm256_mulhi_epi16` (the Montgomery butterfly's
1372/// `mulhi`). Ops have an AVX2 fast path proven byte-identical to the scalar lanes.
1373#[derive(Clone, Copy, PartialEq, Eq, Hash, Debug)]
1374#[repr(C, align(32))]
1375pub struct Lanes16Word16(pub [u16; 16]);
1376
1377/// The AVX2 256-bit lane vector — the real `__m256i` intrinsic on x86_64, a placeholder elsewhere.
1378/// The SIMD fast path is `#[cfg(target_arch = "x86_64")]`-compiled out on other targets (e.g. the
1379/// `wasm32` web build), so the placeholder is never constructed; this keeps the lane ops' signatures
1380/// and closures arch-independent while the scalar fallback runs everywhere.
1381#[cfg(target_arch = "x86_64")]
1382type Avx256 = std::arch::x86_64::__m256i;
1383#[cfg(not(target_arch = "x86_64"))]
1384type Avx256 = [u16; 16];
1385
1386// The four AVX2 lane butterflies, isolated behind safe wrappers so the lane methods' closures stay
1387// arch-independent. On x86_64 each is the intrinsic (the caller `binop` runtime-detects avx2 before
1388// invoking it); on other targets the SIMD path is `#[cfg]`-compiled out, so these are never called.
1389#[cfg(target_arch = "x86_64")]
1390#[inline]
1391fn simd_add(a: Avx256, b: Avx256) -> Avx256 {
1392    unsafe { std::arch::x86_64::_mm256_add_epi16(a, b) }
1393}
1394#[cfg(target_arch = "x86_64")]
1395#[inline]
1396fn simd_sub(a: Avx256, b: Avx256) -> Avx256 {
1397    unsafe { std::arch::x86_64::_mm256_sub_epi16(a, b) }
1398}
1399#[cfg(target_arch = "x86_64")]
1400#[inline]
1401fn simd_mullo(a: Avx256, b: Avx256) -> Avx256 {
1402    unsafe { std::arch::x86_64::_mm256_mullo_epi16(a, b) }
1403}
1404#[cfg(target_arch = "x86_64")]
1405#[inline]
1406fn simd_mulhi(a: Avx256, b: Avx256) -> Avx256 {
1407    unsafe { std::arch::x86_64::_mm256_mulhi_epi16(a, b) }
1408}
1409#[cfg(not(target_arch = "x86_64"))]
1410#[inline]
1411fn simd_add(_a: Avx256, _b: Avx256) -> Avx256 {
1412    unreachable!("SIMD lane path is x86_64-only")
1413}
1414#[cfg(not(target_arch = "x86_64"))]
1415#[inline]
1416fn simd_sub(_a: Avx256, _b: Avx256) -> Avx256 {
1417    unreachable!("SIMD lane path is x86_64-only")
1418}
1419#[cfg(not(target_arch = "x86_64"))]
1420#[inline]
1421fn simd_mullo(_a: Avx256, _b: Avx256) -> Avx256 {
1422    unreachable!("SIMD lane path is x86_64-only")
1423}
1424#[cfg(not(target_arch = "x86_64"))]
1425#[inline]
1426fn simd_mulhi(_a: Avx256, _b: Avx256) -> Avx256 {
1427    unreachable!("SIMD lane path is x86_64-only")
1428}
1429
1430impl Lanes16Word16 {
1431    /// The number of lanes.
1432    pub const LANES: usize = 16;
1433
1434    /// Broadcast one value into all sixteen lanes.
1435    #[inline]
1436    pub const fn splat(x: u16) -> Self {
1437        Self([x; 16])
1438    }
1439
1440    /// Pack the first sixteen `Word16`s of a slice into a lane vector (shorter slices zero-fill).
1441    #[inline]
1442    pub fn from_words(s: &[Word16]) -> Self {
1443        let mut a = [0u16; 16];
1444        for (i, w) in s.iter().take(16).enumerate() {
1445            a[i] = w.0;
1446        }
1447        Self(a)
1448    }
1449
1450    /// The lanes as sixteen `Word16`s.
1451    #[inline]
1452    pub fn to_words(self) -> [Word16; 16] {
1453        self.0.map(Word16)
1454    }
1455
1456    /// Lane `i` (0-based) as a `Word16`.
1457    #[inline]
1458    pub fn lane(self, i: usize) -> Word16 {
1459        Word16(self.0[i])
1460    }
1461
1462    /// Lane-wise wrapping add in ℤ/2¹⁶ (`vpaddw`).
1463    #[inline(always)]
1464    pub fn add(self, o: Self) -> Self {
1465        self.binop(o, |a, b| a.wrapping_add(b), |a, b| simd_add(a, b))
1466    }
1467
1468    /// Lane-wise wrapping subtract in ℤ/2¹⁶ (`vpsubw`).
1469    #[inline(always)]
1470    pub fn sub(self, o: Self) -> Self {
1471        self.binop(o, |a, b| a.wrapping_sub(b), |a, b| simd_sub(a, b))
1472    }
1473
1474    /// Lane-wise low 16 bits of the product (`vpmullw`) — interpretation-independent.
1475    #[inline(always)]
1476    pub fn mullo(self, o: Self) -> Self {
1477        self.binop(o, |a, b| a.wrapping_mul(b), |a, b| simd_mullo(a, b))
1478    }
1479
1480    /// Lane-wise high 16 bits of the SIGNED product (`vpmulhw`) — the Montgomery butterfly's `mulhi`.
1481    #[inline(always)]
1482    pub fn mulhi(self, o: Self) -> Self {
1483        self.binop(
1484            o,
1485            |a, b| (((a as i16 as i32) * (b as i16 as i32)) >> 16) as u16,
1486            |a, b| simd_mulhi(a, b),
1487        )
1488    }
1489
1490    /// Broadcast each `2h`-block's low `h` lanes into both of its halves — the within-vector NTT
1491    /// butterfly's source-low duplication, at stride `h ∈ {8,4,2}`. `h=8`→`vperm2i128(v,v,0x00)`;
1492    /// `h=4`→`vpshufd(v,0x44)`; `h=2`→`vpshufd(v,0xA0)` (all per-128-bit-lane, so the multiple
1493    /// blocks packed in one register are handled at once).
1494    #[inline(always)]
1495    pub fn ntt_bcast_lo(self, h: usize) -> Self {
1496        #[cfg(all(target_arch = "x86_64", target_feature = "avx2"))]
1497        {
1498            use std::arch::x86_64::*;
1499            let mut r = [0u16; 16];
1500            unsafe {
1501                let a = _mm256_loadu_si256(self.0.as_ptr() as *const __m256i);
1502                let v = match h {
1503                    8 => _mm256_permute2x128_si256::<0x00>(a, a),
1504                    4 => _mm256_shuffle_epi32::<0x44>(a),
1505                    2 => _mm256_shuffle_epi32::<0xA0>(a),
1506                    _ => unreachable!("within-vector NTT stride is 8/4/2"),
1507                };
1508                _mm256_storeu_si256(r.as_mut_ptr() as *mut __m256i, v);
1509            }
1510            return Self(r);
1511        }
1512        #[allow(unreachable_code)]
1513        Self(core::array::from_fn(|i| {
1514            self.0[(i / (2 * h)) * (2 * h) + (i % (2 * h)) % h]
1515        }))
1516    }
1517
1518    /// Broadcast each `2h`-block's high `h` lanes into both of its halves — the source-high
1519    /// duplication. `h=8`→`vperm2i128(v,v,0x11)`; `h=4`→`vpshufd(v,0xEE)`; `h=2`→`vpshufd(v,0xF5)`.
1520    #[inline(always)]
1521    pub fn ntt_bcast_hi(self, h: usize) -> Self {
1522        #[cfg(all(target_arch = "x86_64", target_feature = "avx2"))]
1523        {
1524            use std::arch::x86_64::*;
1525            let mut r = [0u16; 16];
1526            unsafe {
1527                let a = _mm256_loadu_si256(self.0.as_ptr() as *const __m256i);
1528                let v = match h {
1529                    8 => _mm256_permute2x128_si256::<0x11>(a, a),
1530                    4 => _mm256_shuffle_epi32::<0xEE>(a),
1531                    2 => _mm256_shuffle_epi32::<0xF5>(a),
1532                    _ => unreachable!("within-vector NTT stride is 8/4/2"),
1533                };
1534                _mm256_storeu_si256(r.as_mut_ptr() as *mut __m256i, v);
1535            }
1536            return Self(r);
1537        }
1538        #[allow(unreachable_code)]
1539        Self(core::array::from_fn(|i| {
1540            self.0[(i / (2 * h)) * (2 * h) + h + (i % (2 * h)) % h]
1541        }))
1542    }
1543
1544    /// Recombine the `+`/`−` halves of the within-vector butterfly: each `2h`-block's low `h` lanes
1545    /// from `self`, high `h` from `o`. `h=8`→`vperm2i128(a,b,0x30)`; `h=4`→`vpblendd(a,b,0xCC)`;
1546    /// `h=2`→`vpblendd(a,b,0xAA)`.
1547    #[inline(always)]
1548    pub fn ntt_blend(self, o: Self, h: usize) -> Self {
1549        #[cfg(all(target_arch = "x86_64", target_feature = "avx2"))]
1550        {
1551            use std::arch::x86_64::*;
1552            let mut r = [0u16; 16];
1553            unsafe {
1554                let a = _mm256_loadu_si256(self.0.as_ptr() as *const __m256i);
1555                let b = _mm256_loadu_si256(o.0.as_ptr() as *const __m256i);
1556                let v = match h {
1557                    8 => _mm256_permute2x128_si256::<0x30>(a, b),
1558                    4 => _mm256_blend_epi32::<0xCC>(a, b),
1559                    2 => _mm256_blend_epi32::<0xAA>(a, b),
1560                    _ => unreachable!("within-vector NTT stride is 8/4/2"),
1561                };
1562                _mm256_storeu_si256(r.as_mut_ptr() as *mut __m256i, v);
1563            }
1564            return Self(r);
1565        }
1566        #[allow(unreachable_code)]
1567        Self(core::array::from_fn(|i| {
1568            if (i % (2 * h)) < h {
1569                self.0[i]
1570            } else {
1571                o.0[i]
1572            }
1573        }))
1574    }
1575
1576    /// Shared add/sub/mullo/mulhi dispatcher. `#[inline(always)]` + compile-time
1577    /// `cfg(target_feature="avx2")` (NOT a runtime `is_x86_feature_detected` branch) so a chain of
1578    /// NTT butterflies inlines register-resident under `+avx2`: LLVM forwards each op's store-to-`r`
1579    /// into the next op's load and keeps the coefficients in one YMM register. A runtime branch is
1580    /// opaque to that forwarding — it forces a load/store round-trip per op (the ~20× lane pessimization).
1581    #[inline(always)]
1582    fn binop(
1583        self,
1584        o: Self,
1585        scalar: impl Fn(u16, u16) -> u16,
1586        #[allow(unused_variables)] vector: impl Fn(Avx256, Avx256) -> Avx256,
1587    ) -> Self {
1588        #[cfg(all(target_arch = "x86_64", target_feature = "avx2"))]
1589        {
1590            use std::arch::x86_64::*;
1591            let mut r = [0u16; 16];
1592            unsafe {
1593                let a = _mm256_loadu_si256(self.0.as_ptr() as *const __m256i);
1594                let b = _mm256_loadu_si256(o.0.as_ptr() as *const __m256i);
1595                _mm256_storeu_si256(r.as_mut_ptr() as *mut __m256i, vector(a, b));
1596            }
1597            return Self(r);
1598        }
1599        #[allow(unreachable_code)]
1600        Self(core::array::from_fn(|i| scalar(self.0[i], o.0[i])))
1601    }
1602}
1603
1604macro_rules! lanes16_op {
1605    ($trait:ident, $tm:ident, $m:ident) => {
1606        impl ::core::ops::$trait for Lanes16Word16 {
1607            type Output = Self;
1608            #[inline]
1609            fn $tm(self, o: Self) -> Self {
1610                Lanes16Word16::$m(self, o)
1611            }
1612        }
1613    };
1614}
1615lanes16_op!(Add, add, add);
1616lanes16_op!(Sub, sub, sub);
1617lanes16_op!(Mul, mul, mullo);
1618
1619/// A SIMD lane vector of any supported lane config — the single runtime carrier the interpreter/VM
1620/// match on, mirroring [`WordVal`]. Binary ops require the same config; a mismatch returns `None`.
1621#[derive(Clone, Copy, PartialEq, Eq, Hash, Debug)]
1622pub enum LanesVal {
1623    /// 8 lanes of `Word32` (one `__m256i`).
1624    L8W32(Lanes8Word32),
1625    /// 4 lanes of `Word64` (one `__m256i`) — the Poly1305 accumulator.
1626    L4W64(Lanes4Word64),
1627    /// 16 lanes of `Word16` (one `__m256i`) — NTT coefficients.
1628    L16W16(Lanes16Word16),
1629    /// 4 lanes of `Word32` (one `__m128i`) — the SHA-1 state/message register (SHA-NI ops).
1630    L4W32(Lanes4Word32),
1631    /// 16 lanes of `Word8` (one `__m128i`) — the byte-shuffle register for SIMD text codecs.
1632    L16W8(Lanes16Word8),
1633}
1634
1635impl LanesVal {
1636    /// The lane count.
1637    #[inline]
1638    pub const fn lanes(self) -> usize {
1639        match self {
1640            LanesVal::L8W32(_) => 8,
1641            LanesVal::L4W64(_) => 4,
1642            LanesVal::L16W16(_) => 16,
1643            LanesVal::L4W32(_) => 4,
1644            LanesVal::L16W8(_) => 16,
1645        }
1646    }
1647
1648    /// The lane-element bit width.
1649    #[inline]
1650    pub const fn elem_bits(self) -> u32 {
1651        match self {
1652            LanesVal::L8W32(_) => 32,
1653            LanesVal::L4W64(_) => 64,
1654            LanesVal::L16W16(_) => 16,
1655            LanesVal::L4W32(_) => 32,
1656            LanesVal::L16W8(_) => 8,
1657        }
1658    }
1659
1660    /// The Logos type name.
1661    #[inline]
1662    pub const fn type_name(self) -> &'static str {
1663        match self {
1664            LanesVal::L8W32(_) => "Lanes8Word32",
1665            LanesVal::L4W64(_) => "Lanes4Word64",
1666            LanesVal::L16W16(_) => "Lanes16Word16",
1667            LanesVal::L4W32(_) => "Lanes4Word32",
1668            LanesVal::L16W8(_) => "Lanes16Word8",
1669        }
1670    }
1671
1672    /// Lane `i`'s value, zero-extended to `u64` (for unpacking back into a Seq and for display).
1673    #[inline]
1674    pub fn lane(self, i: usize) -> u64 {
1675        match self {
1676            LanesVal::L8W32(v) => v.lane(i).0 as u64,
1677            LanesVal::L4W64(v) => v.lane(i).0,
1678            LanesVal::L16W16(v) => v.lane(i).0 as u64,
1679            LanesVal::L4W32(v) => v.lane(i).0 as u64,
1680            LanesVal::L16W8(v) => v.lane(i) as u64,
1681        }
1682    }
1683
1684    /// Byte-shuffle vocabulary, defined only on the `L16W8` config (SIMD hex codec); `None` otherwise.
1685    #[inline]
1686    pub fn shuffle(self, idx: Self) -> Option<Self> {
1687        match (self, idx) {
1688            (LanesVal::L16W8(a), LanesVal::L16W8(b)) => Some(LanesVal::L16W8(a.shuffle(b))),
1689            _ => None,
1690        }
1691    }
1692    #[inline]
1693    pub fn byte_and(self, o: Self) -> Option<Self> {
1694        match (self, o) {
1695            (LanesVal::L16W8(a), LanesVal::L16W8(b)) => Some(LanesVal::L16W8(a.bitand(b))),
1696            _ => None,
1697        }
1698    }
1699    #[inline]
1700    pub fn shr_bytes(self, n: u32) -> Option<Self> {
1701        match self {
1702            LanesVal::L16W8(a) => Some(LanesVal::L16W8(a.shr_bytes(n))),
1703            _ => None,
1704        }
1705    }
1706    #[inline]
1707    pub fn interleave_lo(self, o: Self) -> Option<Self> {
1708        match (self, o) {
1709            (LanesVal::L16W8(a), LanesVal::L16W8(b)) => Some(LanesVal::L16W8(a.interleave_lo(b))),
1710            _ => None,
1711        }
1712    }
1713    #[inline]
1714    pub fn interleave_hi(self, o: Self) -> Option<Self> {
1715        match (self, o) {
1716            (LanesVal::L16W8(a), LanesVal::L16W8(b)) => Some(LanesVal::L16W8(a.interleave_hi(b))),
1717            _ => None,
1718        }
1719    }
1720    #[inline]
1721    pub fn byte_add(self, o: Self) -> Option<Self> {
1722        match (self, o) {
1723            (LanesVal::L16W8(a), LanesVal::L16W8(b)) => Some(LanesVal::L16W8(a.byte_add(b))),
1724            _ => None,
1725        }
1726    }
1727    #[inline]
1728    pub fn maddubs_bytes(self, o: Self) -> Option<Self> {
1729        match (self, o) {
1730            (LanesVal::L16W8(a), LanesVal::L16W8(b)) => Some(LanesVal::L16W8(a.maddubs(b))),
1731            _ => None,
1732        }
1733    }
1734    #[inline]
1735    pub fn packus_bytes(self, o: Self) -> Option<Self> {
1736        match (self, o) {
1737            (LanesVal::L16W8(a), LanesVal::L16W8(b)) => Some(LanesVal::L16W8(a.packus(b))),
1738            _ => None,
1739        }
1740    }
1741
1742    /// The four SHA-1 (SHA-NI) operations, defined only on the `L4W32` config; `None` otherwise.
1743    #[inline]
1744    pub fn sha1rnds4(self, msg: Self, func: u32) -> Option<Self> {
1745        match (self, msg) {
1746            (LanesVal::L4W32(a), LanesVal::L4W32(b)) => Some(LanesVal::L4W32(a.sha1rnds4(b, func))),
1747            _ => None,
1748        }
1749    }
1750    #[inline]
1751    pub fn sha1msg1(self, o: Self) -> Option<Self> {
1752        match (self, o) {
1753            (LanesVal::L4W32(a), LanesVal::L4W32(b)) => Some(LanesVal::L4W32(a.sha1msg1(b))),
1754            _ => None,
1755        }
1756    }
1757    #[inline]
1758    pub fn sha1msg2(self, o: Self) -> Option<Self> {
1759        match (self, o) {
1760            (LanesVal::L4W32(a), LanesVal::L4W32(b)) => Some(LanesVal::L4W32(a.sha1msg2(b))),
1761            _ => None,
1762        }
1763    }
1764    #[inline]
1765    pub fn sha1nexte(self, o: Self) -> Option<Self> {
1766        match (self, o) {
1767            (LanesVal::L4W32(a), LanesVal::L4W32(b)) => Some(LanesVal::L4W32(a.sha1nexte(b))),
1768            _ => None,
1769        }
1770    }
1771
1772    /// Lane-wise XOR; `None` on a config mismatch (or a config that does not define XOR).
1773    #[inline]
1774    pub fn bitxor(self, o: Self) -> Option<Self> {
1775        match (self, o) {
1776            (LanesVal::L8W32(a), LanesVal::L8W32(b)) => Some(LanesVal::L8W32(a.bitxor(b))),
1777            (LanesVal::L4W64(a), LanesVal::L4W64(b)) => Some(LanesVal::L4W64(a.bitxor(b))),
1778            (LanesVal::L4W32(a), LanesVal::L4W32(b)) => Some(LanesVal::L4W32(a.bitxor(b))),
1779            _ => None,
1780        }
1781    }
1782
1783    /// Lane-wise AND (the MD5 F/G mixing) — `None` on a config mismatch or a config without AND.
1784    #[inline]
1785    pub fn bitand(self, o: Self) -> Option<Self> {
1786        match (self, o) {
1787            (LanesVal::L8W32(a), LanesVal::L8W32(b)) => Some(LanesVal::L8W32(a.bitand(b))),
1788            (LanesVal::L16W8(a), LanesVal::L16W8(b)) => Some(LanesVal::L16W8(a.bitand(b))),
1789            _ => None,
1790        }
1791    }
1792
1793    /// Lane-wise OR — `None` on a config mismatch or a config without OR.
1794    #[inline]
1795    pub fn bitor(self, o: Self) -> Option<Self> {
1796        match (self, o) {
1797            (LanesVal::L8W32(a), LanesVal::L8W32(b)) => Some(LanesVal::L8W32(a.bitor(b))),
1798            _ => None,
1799        }
1800    }
1801
1802    /// Lane-wise complement — `None` for a config without NOT.
1803    #[inline]
1804    pub fn lane_not(self) -> Option<Self> {
1805        match self {
1806            LanesVal::L8W32(a) => Some(LanesVal::L8W32(a.not())),
1807            _ => None,
1808        }
1809    }
1810
1811    /// Lane-wise wrapping add; `None` on a config mismatch.
1812    #[inline]
1813    pub fn add(self, o: Self) -> Option<Self> {
1814        match (self, o) {
1815            (LanesVal::L8W32(a), LanesVal::L8W32(b)) => Some(LanesVal::L8W32(a.add(b))),
1816            (LanesVal::L4W64(a), LanesVal::L4W64(b)) => Some(LanesVal::L4W64(a.add(b))),
1817            (LanesVal::L16W16(a), LanesVal::L16W16(b)) => Some(LanesVal::L16W16(a.add(b))),
1818            (LanesVal::L4W32(a), LanesVal::L4W32(b)) => Some(LanesVal::L4W32(a.add(b))),
1819            _ => None,
1820        }
1821    }
1822
1823    /// Lane-wise wrapping subtract; `None` on a config mismatch (the i16 NTT and the i32 ML-DSA NTT).
1824    #[inline]
1825    pub fn sub(self, o: Self) -> Option<Self> {
1826        match (self, o) {
1827            (LanesVal::L16W16(a), LanesVal::L16W16(b)) => Some(LanesVal::L16W16(a.sub(b))),
1828            (LanesVal::L8W32(a), LanesVal::L8W32(b)) => Some(LanesVal::L8W32(a.sub(b))),
1829            _ => None,
1830        }
1831    }
1832
1833    /// Lane-wise low-16 multiply (`vpmullw`); `None` unless `Word16`.
1834    #[inline]
1835    pub fn mullo(self, o: Self) -> Option<Self> {
1836        match (self, o) {
1837            (LanesVal::L16W16(a), LanesVal::L16W16(b)) => Some(LanesVal::L16W16(a.mullo(b))),
1838            _ => None,
1839        }
1840    }
1841
1842    /// Lane-wise SIGNED high-16 multiply (`vpmulhw`, the Montgomery `mulhi`); `None` unless `Word16`.
1843    #[inline]
1844    pub fn mulhi(self, o: Self) -> Option<Self> {
1845        match (self, o) {
1846            (LanesVal::L16W16(a), LanesVal::L16W16(b)) => Some(LanesVal::L16W16(a.mulhi(b))),
1847            _ => None,
1848        }
1849    }
1850
1851    /// Within-vector NTT source-low duplication at stride `h` (`vperm2i128`/`vpshufd`); `None`
1852    /// unless `Word16`.
1853    #[inline]
1854    pub fn ntt_bcast_lo(self, h: usize) -> Option<Self> {
1855        match self {
1856            LanesVal::L16W16(a) => Some(LanesVal::L16W16(a.ntt_bcast_lo(h))),
1857            LanesVal::L8W32(a) => Some(LanesVal::L8W32(a.ntt_bcast_lo(h))),
1858            _ => None,
1859        }
1860    }
1861
1862    /// Within-vector NTT source-high duplication at stride `h`; `None` unless `Word16`/`Word32`.
1863    #[inline]
1864    pub fn ntt_bcast_hi(self, h: usize) -> Option<Self> {
1865        match self {
1866            LanesVal::L16W16(a) => Some(LanesVal::L16W16(a.ntt_bcast_hi(h))),
1867            LanesVal::L8W32(a) => Some(LanesVal::L8W32(a.ntt_bcast_hi(h))),
1868            _ => None,
1869        }
1870    }
1871
1872    /// Within-vector NTT half-recombine at stride `h` (`vperm2i128`/`vpblendd`); `None` unless both
1873    /// are `Word16`/`Word32`.
1874    #[inline]
1875    pub fn ntt_blend(self, o: Self, h: usize) -> Option<Self> {
1876        match (self, o) {
1877            (LanesVal::L16W16(a), LanesVal::L16W16(b)) => Some(LanesVal::L16W16(a.ntt_blend(b, h))),
1878            (LanesVal::L8W32(a), LanesVal::L8W32(b)) => Some(LanesVal::L8W32(a.ntt_blend(b, h))),
1879            _ => None,
1880        }
1881    }
1882
1883    /// Lane-wise left rotation by `n`; `None` for a config that does not define rotation.
1884    #[inline]
1885    pub fn rotl(self, n: u32) -> Option<Self> {
1886        match self {
1887            LanesVal::L8W32(a) => Some(LanesVal::L8W32(a.rotl(n))),
1888            LanesVal::L4W64(a) => Some(LanesVal::L4W64(a.rotl(n))),
1889            _ => None,
1890        }
1891    }
1892
1893    /// Lane-wise widening low-32 multiply (the Poly1305 4-way limb product); `None` unless `Word64`.
1894    #[inline]
1895    pub fn mul_lo32_wide(self, o: Self) -> Option<Self> {
1896        match (self, o) {
1897            (LanesVal::L4W64(a), LanesVal::L4W64(b)) => Some(LanesVal::L4W64(a.mul_lo32_wide(b))),
1898            _ => None,
1899        }
1900    }
1901
1902    /// The signed i32 Montgomery multiply (ML-DSA NTT butterfly), `q`/`qinv` broadcast; `None` unless
1903    /// all four are `Word32`.
1904    #[inline]
1905    pub fn montmul32(self, b: Self, q: Self, qinv: Self) -> Option<Self> {
1906        match (self, b, q, qinv) {
1907            (LanesVal::L8W32(a), LanesVal::L8W32(b), LanesVal::L8W32(q), LanesVal::L8W32(qi)) => {
1908                Some(LanesVal::L8W32(a.montmul32(b, q, qi)))
1909            }
1910            _ => None,
1911        }
1912    }
1913
1914    /// Horizontal sum of the lanes as an `Int`.
1915    #[inline]
1916    pub fn hsum(self) -> i64 {
1917        match self {
1918            LanesVal::L8W32(a) => (0..8).map(|i| a.lane(i).0 as i64).sum(),
1919            LanesVal::L4W64(a) => a.hsum() as i64,
1920            LanesVal::L16W16(a) => (0..16).map(|i| a.lane(i).0 as i64).sum(),
1921            LanesVal::L4W32(a) => (0..4).map(|i| a.lane(i).0 as i64).sum(),
1922            LanesVal::L16W8(a) => (0..16).map(|i| a.lane(i) as i64).sum(),
1923        }
1924    }
1925}
1926
1927#[cfg(test)]
1928#[path = "../../logicaffeine_tests/unit/logicaffeine_base/word/tests.rs"]
1929mod tests;