Skip to main content

crc32fast/specialized/
pclmulqdq.rs

1//! Specialized checksum code for the x86 CPU architecture, based on the efficient algorithm described
2//! in the following whitepaper:
3//!
4//! Gopal, V., Ozturk, E., Guilford, J., Wolrich, G., Feghali, W., Dixon, M., & Karakoyunlu, D. (2009).
5//! _Fast CRC computation for generic polynomials using PCLMULQDQ instruction_. Intel.
6//! (Mirror link: <https://fossies.org/linux/zlib-ng/doc/crc-pclmulqdq.pdf>, accessed 2024-05-20)
7//!
8//! Throughout the code, this work is referred to as "the paper".
9//!
10//! On top of the 128-bit `PCLMULQDQ` implementation, two wider variants use `VPCLMULQDQ` to fold
11//! several independent 128-bit streams per instruction: an `AVX2` variant over 256-bit `YMM`
12//! registers (8 streams) and an `AVX-512` variant over 512-bit `ZMM` registers (16 streams). Both
13//! rely on `VPCLMULQDQ` intrinsics stabilized in Rust 1.89 and are only compiled when the
14//! `stable_vpclmulqdq` cfg is set by `build.rs`, leaving the crate MSRV unchanged otherwise. The
15//! best variant supported by the running CPU is chosen at runtime.
16//!
17//! Each `unsafe fn` here is unsafe only because it needs the CPU features in its
18//! `#[target_feature]` list (PCLMULQDQ for `reduce128`). None of them has a memory-safety
19//! precondition: every load is bounds-checked.
20
21#[cfg(target_arch = "x86")]
22use core::arch::x86 as arch;
23#[cfg(target_arch = "x86_64")]
24use core::arch::x86_64 as arch;
25
26/// Which SIMD implementation to use, chosen once at construction from the CPU's features.
27#[derive(Clone, Copy)]
28enum Kind {
29    /// 128-bit `PCLMULQDQ`, fold by 4.
30    Sse,
31    /// 256-bit `VPCLMULQDQ`, 8 streams.
32    #[cfg(stable_vpclmulqdq)]
33    Avx2,
34    /// 512-bit `VPCLMULQDQ`, 16 streams.
35    #[cfg(stable_vpclmulqdq)]
36    Avx512,
37}
38
39#[cfg(feature = "std")]
40impl Kind {
41    /// Encodes `kind` for `State::detect`'s cache, which reserves 0 for "not detected yet".
42    #[inline]
43    fn encode(kind: Option<Kind>) -> u8 {
44        match kind {
45            None => 1,
46            Some(Kind::Sse) => 2,
47            #[cfg(stable_vpclmulqdq)]
48            Some(Kind::Avx2) => 3,
49            #[cfg(stable_vpclmulqdq)]
50            Some(Kind::Avx512) => 4,
51        }
52    }
53
54    /// Decodes what `encode` returned.
55    #[inline]
56    fn decode(code: u8) -> Option<Kind> {
57        match code {
58            2 => Some(Kind::Sse),
59            #[cfg(stable_vpclmulqdq)]
60            3 => Some(Kind::Avx2),
61            #[cfg(stable_vpclmulqdq)]
62            4 => Some(Kind::Avx512),
63            _ => {
64                debug_assert_eq!(code, 1, "code from `encode` has no `decode` arm");
65                None
66            }
67        }
68    }
69}
70
71#[derive(Clone)]
72pub struct State {
73    kind: Kind,
74}
75
76impl State {
77    #[cfg(not(feature = "std"))]
78    #[inline]
79    fn detect() -> Option<Kind> {
80        if cfg!(target_feature = "pclmulqdq")
81            && cfg!(target_feature = "sse2")
82            && cfg!(target_feature = "sse4.1")
83            && cfg!(target_feature = "ssse3")
84        {
85            #[cfg(stable_vpclmulqdq)]
86            {
87                if cfg!(target_feature = "avx512f") && cfg!(target_feature = "vpclmulqdq") {
88                    return Some(Kind::Avx512);
89                }
90                if cfg!(target_feature = "avx2") && cfg!(target_feature = "vpclmulqdq") {
91                    return Some(Kind::Avx2);
92                }
93            }
94
95            return Some(Kind::Sse);
96        }
97
98        None
99    }
100
101    /// The kernel for this CPU, if any. Finding it takes up to seven feature checks, each a load
102    /// and a branch. `Hasher::new` asks every time, and `crc32fast::hash` constructs a `Hasher` for
103    /// every call, so the answer is cached: after the first call, this is one load.
104    #[cfg(feature = "std")]
105    #[inline]
106    fn detect() -> Option<Kind> {
107        use core::sync::atomic::{AtomicU8, Ordering};
108
109        // 0 = not detected yet, else `Kind::encode` of the result. Racing threads store the same
110        // value, so relaxed ordering is enough.
111        static CACHE: AtomicU8 = AtomicU8::new(0);
112        match CACHE.load(Ordering::Relaxed) {
113            0 => {
114                let kind = Self::detect_uncached();
115                CACHE.store(Kind::encode(kind), Ordering::Relaxed);
116                kind
117            }
118            code => Kind::decode(code),
119        }
120    }
121
122    #[cfg(feature = "std")]
123    #[cold]
124    fn detect_uncached() -> Option<Kind> {
125        if is_x86_feature_detected!("pclmulqdq")
126            && is_x86_feature_detected!("sse2")
127            && is_x86_feature_detected!("sse4.1")
128            && is_x86_feature_detected!("ssse3")
129        {
130            #[cfg(stable_vpclmulqdq)]
131            {
132                if is_x86_feature_detected!("avx512f") && is_x86_feature_detected!("vpclmulqdq") {
133                    return Some(Kind::Avx512);
134                }
135                if is_x86_feature_detected!("avx2") && is_x86_feature_detected!("vpclmulqdq") {
136                    return Some(Kind::Avx2);
137                }
138            }
139
140            return Some(Kind::Sse);
141        }
142
143        None
144    }
145
146    #[inline]
147    pub fn new() -> Option<Self> {
148        // SAFETY: `detect` only returns a `Kind` whose instructions the CPU supports.
149        Self::detect().map(|kind| Self { kind })
150    }
151
152    #[inline]
153    pub fn update(&self, state: u32, buf: &[u8]) -> u32 {
154        // SAFETY: The kernels are only unsafe because the CPU might lack their target features.
155        // `detect` checked every feature listed on the kernel for `self.kind`, and `kind` can't be
156        // changed after `new`.
157        unsafe {
158            match self.kind {
159                Kind::Sse => calculate(state, buf),
160                #[cfg(stable_vpclmulqdq)]
161                Kind::Avx2 => calculate_avx2(state, buf),
162                #[cfg(stable_vpclmulqdq)]
163                Kind::Avx512 => calculate_avx512(state, buf),
164            }
165        }
166    }
167}
168
169const K1: i64 = 0x154442bd4;
170const K2: i64 = 0x1c6e41596;
171const K3: i64 = 0x1751997d0;
172const K4: i64 = 0x0ccaa009e;
173
174/// Barrett reduction constants: `floor(x^95 / G(x))` and `G(x)`, bit-reflected.
175const BARRETT_MU: i64 = 0xb4e5b025f7011641_u64 as i64;
176const BARRETT_G: i64 = 0x1db710641;
177
178// The wider kernels have progressively more streams to initialize and collapse. Keep their
179// crossovers conservative so short inputs do not pay that fixed cost.
180const MIN_FOLD_BY_4_BYTES: usize = 128;
181#[cfg(stable_vpclmulqdq)]
182const MIN_AVX512_BYTES: usize = 2 * 1024;
183
184// Fold constants for the wider strides. For a fold by `D` bits the pair is
185// `(reflect(x^(D+32) mod P), reflect(x^(D-32) mod P))`, as for `K1`/`K2` (D = 512) and
186// `K3`/`K4` (D = 128). AVX2 uses 8 streams (D = 1024), AVX-512 uses 16 streams (D = 2048).
187#[cfg(stable_vpclmulqdq)]
188const K_1024_LOW: i64 = 0x1e88ef372;
189#[cfg(stable_vpclmulqdq)]
190const K_1024_HIGH: i64 = 0x14a7fe880;
191#[cfg(stable_vpclmulqdq)]
192const K_2048_LOW: i64 = 0x11542778a;
193#[cfg(stable_vpclmulqdq)]
194const K_2048_HIGH: i64 = 0x1322d1430;
195
196#[target_feature(
197    enable = "pclmulqdq",
198    enable = "sse2",
199    enable = "sse4.1",
200    enable = "ssse3"
201)]
202unsafe fn calculate(crc: u32, mut data: &[u8]) -> u32 {
203    // Below 16 bytes there isn't even a single full block to load, so use the scalar fallback.
204    if data.len() < 16 {
205        return crate::baseline::update_short(crc, data);
206    }
207    let input = data;
208
209    // For 16..127 bytes a single-accumulator fold-by-1 is enough; the fold-by-4 setup below only
210    // pays off once there are several 64-byte groups.
211    if data.len() < MIN_FOLD_BY_4_BYTES {
212        let mut x = get(&mut data);
213        x = arch::_mm_xor_si128(x, arch::_mm_cvtsi32_si128(!crc as i32));
214        return reduce_128_to_crc(x, input, data);
215    }
216
217    // Step 1: fold by 4 loop
218    let mut x3 = get(&mut data);
219    let mut x2 = get(&mut data);
220    let mut x1 = get(&mut data);
221    let mut x0 = get(&mut data);
222
223    // fold in our initial value, part of the incremental crc checksum
224    x3 = arch::_mm_xor_si128(x3, arch::_mm_cvtsi32_si128(!crc as i32));
225
226    let k1k2 = arch::_mm_set_epi64x(K2, K1);
227    while data.len() >= 64 {
228        x3 = reduce128(x3, get(&mut data), k1k2);
229        x2 = reduce128(x2, get(&mut data), k1k2);
230        x1 = reduce128(x1, get(&mut data), k1k2);
231        x0 = reduce128(x0, get(&mut data), k1k2);
232    }
233
234    let k3k4 = arch::_mm_set_epi64x(K4, K3);
235    let mut x = reduce128(x3, x2, k3k4);
236    x = reduce128(x, x1, k3k4);
237    x = reduce128(x, x0, k3k4);
238
239    reduce_128_to_crc(x, input, data)
240}
241
242/// 256-bit `VPCLMULQDQ` variant: 8 streams across four `YMM` registers (two lanes each), folding
243/// two streams per carry-less multiply.
244#[cfg(stable_vpclmulqdq)]
245#[allow(clippy::incompatible_msrv)] // intrinsics are gated to rustc >= 1.89 by build.rs
246#[target_feature(
247    enable = "pclmulqdq",
248    enable = "sse2",
249    enable = "sse4.1",
250    enable = "ssse3",
251    enable = "avx",
252    enable = "avx2",
253    enable = "vpclmulqdq"
254)]
255unsafe fn calculate_avx2(crc: u32, mut data: &[u8]) -> u32 {
256    // Too small for the wide loop; use the 128-bit path.
257    if data.len() < 256 {
258        return calculate(crc, data);
259    }
260    let input = data;
261
262    // First 128 bytes as 8 streams (four YMM registers, two lanes each).
263    let mut v0 = get256(&mut data);
264    let mut v1 = get256(&mut data);
265    let mut v2 = get256(&mut data);
266    let mut v3 = get256(&mut data);
267
268    // Fold the initial CRC into the lowest-offset stream.
269    v0 = arch::_mm256_xor_si256(
270        v0,
271        arch::_mm256_castsi128_si256(arch::_mm_cvtsi32_si128(!crc as i32)),
272    );
273
274    let k = arch::_mm256_set_epi64x(K_1024_HIGH, K_1024_LOW, K_1024_HIGH, K_1024_LOW);
275    while data.len() >= 128 {
276        v0 = reduce256(v0, get256(&mut data), k);
277        v1 = reduce256(v1, get256(&mut data), k);
278        v2 = reduce256(v2, get256(&mut data), k);
279        v3 = reduce256(v3, get256(&mut data), k);
280    }
281
282    // Collapse the 8 streams, in increasing byte offset, folding each into the next by 128 bits.
283    let k3k4 = arch::_mm_set_epi64x(K4, K3);
284    let mut x = arch::_mm256_castsi256_si128(v0);
285    x = reduce128(x, arch::_mm256_extracti128_si256(v0, 1), k3k4);
286    x = reduce128(x, arch::_mm256_castsi256_si128(v1), k3k4);
287    x = reduce128(x, arch::_mm256_extracti128_si256(v1, 1), k3k4);
288    x = reduce128(x, arch::_mm256_castsi256_si128(v2), k3k4);
289    x = reduce128(x, arch::_mm256_extracti128_si256(v2, 1), k3k4);
290    x = reduce128(x, arch::_mm256_castsi256_si128(v3), k3k4);
291    x = reduce128(x, arch::_mm256_extracti128_si256(v3, 1), k3k4);
292
293    reduce_128_to_crc(x, input, data)
294}
295
296/// 512-bit `VPCLMULQDQ` variant: 16 streams across four `ZMM` registers (four lanes each), folding
297/// four streams per carry-less multiply.
298#[cfg(stable_vpclmulqdq)]
299#[allow(clippy::incompatible_msrv)] // intrinsics are gated to rustc >= 1.89 by build.rs
300#[target_feature(
301    enable = "pclmulqdq",
302    enable = "sse2",
303    enable = "sse4.1",
304    enable = "ssse3",
305    enable = "avx",
306    enable = "avx2",
307    enable = "vpclmulqdq",
308    enable = "avx512f"
309)]
310unsafe fn calculate_avx512(crc: u32, mut data: &[u8]) -> u32 {
311    // Use a conservative crossover because the 16-stream setup and collapse are costly near 1 KiB.
312    if data.len() < MIN_AVX512_BYTES {
313        return calculate_avx2(crc, data);
314    }
315    let input = data;
316
317    // First 256 bytes as 16 streams (four ZMM registers, four lanes each).
318    let mut v0 = get512(&mut data);
319    let mut v1 = get512(&mut data);
320    let mut v2 = get512(&mut data);
321    let mut v3 = get512(&mut data);
322
323    // Fold the initial CRC into the lowest-offset stream.
324    v0 = arch::_mm512_xor_si512(
325        v0,
326        arch::_mm512_castsi128_si512(arch::_mm_cvtsi32_si128(!crc as i32)),
327    );
328
329    let k = arch::_mm512_set_epi64(
330        K_2048_HIGH,
331        K_2048_LOW,
332        K_2048_HIGH,
333        K_2048_LOW,
334        K_2048_HIGH,
335        K_2048_LOW,
336        K_2048_HIGH,
337        K_2048_LOW,
338    );
339    while data.len() >= 256 {
340        v0 = reduce512(v0, get512(&mut data), k);
341        v1 = reduce512(v1, get512(&mut data), k);
342        v2 = reduce512(v2, get512(&mut data), k);
343        v3 = reduce512(v3, get512(&mut data), k);
344    }
345
346    // Collapse the 16 streams, in increasing byte offset, folding each into the next by 128 bits.
347    let k3k4 = arch::_mm_set_epi64x(K4, K3);
348    let mut x = arch::_mm512_castsi512_si128(v0);
349    x = reduce128(x, arch::_mm512_extracti32x4_epi32(v0, 1), k3k4);
350    x = reduce128(x, arch::_mm512_extracti32x4_epi32(v0, 2), k3k4);
351    x = reduce128(x, arch::_mm512_extracti32x4_epi32(v0, 3), k3k4);
352    x = reduce128(x, arch::_mm512_castsi512_si128(v1), k3k4);
353    x = reduce128(x, arch::_mm512_extracti32x4_epi32(v1, 1), k3k4);
354    x = reduce128(x, arch::_mm512_extracti32x4_epi32(v1, 2), k3k4);
355    x = reduce128(x, arch::_mm512_extracti32x4_epi32(v1, 3), k3k4);
356    x = reduce128(x, arch::_mm512_castsi512_si128(v2), k3k4);
357    x = reduce128(x, arch::_mm512_extracti32x4_epi32(v2, 1), k3k4);
358    x = reduce128(x, arch::_mm512_extracti32x4_epi32(v2, 2), k3k4);
359    x = reduce128(x, arch::_mm512_extracti32x4_epi32(v2, 3), k3k4);
360    x = reduce128(x, arch::_mm512_castsi512_si128(v3), k3k4);
361    x = reduce128(x, arch::_mm512_extracti32x4_epi32(v3, 1), k3k4);
362    x = reduce128(x, arch::_mm512_extracti32x4_epi32(v3, 2), k3k4);
363    x = reduce128(x, arch::_mm512_extracti32x4_epi32(v3, 3), k3k4);
364
365    // A substantial remainder is faster through SSE's complete fold-by-4 kernel than through the
366    // serial fold-by-1 tail below. Finalizing and restarting is valid because CRC updates compose.
367    if data.len() >= MIN_FOLD_BY_4_BYTES {
368        let crc = reduce_128_to_crc(x, input, &[]);
369        return calculate(crc, data);
370    }
371
372    reduce_128_to_crc(x, input, data)
373}
374
375/// Finishes a fold: `x` is `input` folded up to `rest`, its unconsumed tail. Folds any remaining
376/// 16-byte chunks into `x`, then a final partial (`< 16` byte) block, reduces from 128 to 32 bits
377/// with a Barrett reduction, and returns the CRC. Shared by all of the fold implementations.
378/// `input` is at least 16 bytes long.
379#[target_feature(
380    enable = "pclmulqdq",
381    enable = "sse2",
382    enable = "sse4.1",
383    enable = "ssse3"
384)]
385unsafe fn reduce_128_to_crc(mut x: arch::__m128i, input: &[u8], mut rest: &[u8]) -> u32 {
386    let k3k4 = arch::_mm_set_epi64x(K4, K3);
387
388    // Fold by 1 over any remaining whole 16-byte blocks.
389    while rest.len() >= 16 {
390        x = reduce128(x, get(&mut rest), k3k4);
391    }
392
393    // Fold a final partial block of `n` (1..=15) bytes. `x` and those bytes are `16 + n` bytes of
394    // message: the first `n` are folded forward by 128 bits, into the last 16. The last 16 are
395    // the high `16 - n` bytes of `x` followed by the final `n` bytes of the input, which one load
396    // ending at the end of `input` reads. That load overlaps bytes already folded in, which the
397    // blend drops. `input` is at least 16 bytes long, so it stays in bounds.
398    //
399    // Byte `i` of `shl` is `i + n - 16`. As a `pshufb` mask it moves the low `n` bytes of `x` to
400    // the top and zeroes the rest. `shr` is `shl` with each byte's high bit flipped: it moves the
401    // high `16 - n` bytes of `x` to the bottom, and its high bits mark the `n` bytes above them,
402    // where the blend takes the loaded bytes.
403    let n = rest.len();
404    if n > 0 {
405        let seq = arch::_mm_setr_epi8(0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15);
406        let shl = arch::_mm_add_epi8(seq, arch::_mm_set1_epi8(n as i8 - 16));
407        let shr = arch::_mm_xor_si128(shl, arch::_mm_set1_epi8(-128));
408
409        let first = arch::_mm_shuffle_epi8(x, shl);
410        let tail =
411            arch::_mm_loadu_si128(input[input.len() - 16..].as_ptr() as *const arch::__m128i);
412        let last = arch::_mm_blendv_epi8(arch::_mm_shuffle_epi8(x, shr), tail, shr);
413        x = reduce128(first, last, k3k4);
414    }
415
416    // Reduce the 128-bit message polynomial to its CRC: multiply by `x^32` and reduce modulo
417    // `G(x)`. Fold the low 64 bits (the high-order terms, since the bits are reflected) into the
418    // high 64, leaving 96 bits. A Barrett reduction with a 64-bit quotient estimate,
419    // `floor(x^95 / G(x))`, takes those to 32 without folding them to 64 first.
420    //
421    // libdeflate's `crc32_pclmul_template.h` and the Linux kernel's `crc-pclmul-template.S` (with
422    // `n=32` and `LSB_CRC=1`) do the same; see there for the math.
423    let x = arch::_mm_xor_si128(
424        arch::_mm_clmulepi64_si128(x, k3k4, 0x10),
425        arch::_mm_srli_si128(x, 8),
426    );
427    let barrett = arch::_mm_set_epi64x(BARRETT_G, BARRETT_MU);
428    let t = arch::_mm_clmulepi64_si128(x, barrett, 0x00);
429    let t = arch::_mm_clmulepi64_si128(t, barrett, 0x10);
430    !(arch::_mm_extract_epi32(arch::_mm_xor_si128(x, t), 2) as u32)
431}
432
433#[inline]
434unsafe fn reduce128(a: arch::__m128i, b: arch::__m128i, keys: arch::__m128i) -> arch::__m128i {
435    let t1 = arch::_mm_clmulepi64_si128(a, keys, 0x00);
436    let t2 = arch::_mm_clmulepi64_si128(a, keys, 0x11);
437    arch::_mm_xor_si128(arch::_mm_xor_si128(b, t1), t2)
438}
439
440#[cfg(stable_vpclmulqdq)]
441#[allow(clippy::incompatible_msrv)] // intrinsics are gated to rustc >= 1.89 by build.rs
442#[target_feature(enable = "avx2", enable = "vpclmulqdq")]
443#[inline]
444unsafe fn reduce256(a: arch::__m256i, b: arch::__m256i, keys: arch::__m256i) -> arch::__m256i {
445    let t1 = arch::_mm256_clmulepi64_epi128(a, keys, 0x00);
446    let t2 = arch::_mm256_clmulepi64_epi128(a, keys, 0x11);
447    arch::_mm256_xor_si256(arch::_mm256_xor_si256(b, t1), t2)
448}
449
450#[cfg(stable_vpclmulqdq)]
451#[allow(clippy::incompatible_msrv)] // intrinsics are gated to rustc >= 1.89 by build.rs
452#[target_feature(enable = "avx512f", enable = "vpclmulqdq")]
453#[inline]
454unsafe fn reduce512(a: arch::__m512i, b: arch::__m512i, keys: arch::__m512i) -> arch::__m512i {
455    let t1 = arch::_mm512_clmulepi64_epi128(a, keys, 0x00);
456    let t2 = arch::_mm512_clmulepi64_epi128(a, keys, 0x11);
457    arch::_mm512_xor_si512(arch::_mm512_xor_si512(b, t1), t2)
458}
459
460// The loads below index `a[..N]` before reading through its pointer, so a miscounted length panics
461// instead of reading out of bounds. The callers' loop conditions already imply the check, so it
462// compiles away: the kernels' machine code is unchanged.
463
464/// Loads the next 16 bytes of `a` as a vector and advances `a` past them.
465#[inline]
466fn get(a: &mut &[u8]) -> arch::__m128i {
467    // SAFETY: `a[..16]` is 16 readable bytes, `_mm_loadu_si128` doesn't need them aligned, and SSE2
468    // is enabled for the whole build (`specialized/mod.rs` only compiles this module when it is).
469    let r = unsafe { arch::_mm_loadu_si128(a[..16].as_ptr() as *const arch::__m128i) };
470    *a = &a[16..];
471    r
472}
473
474#[cfg(stable_vpclmulqdq)]
475#[target_feature(enable = "avx")]
476#[inline]
477unsafe fn get256(a: &mut &[u8]) -> arch::__m256i {
478    let r = arch::_mm256_loadu_si256(a[..32].as_ptr() as *const arch::__m256i);
479    *a = &a[32..];
480    r
481}
482
483#[cfg(stable_vpclmulqdq)]
484#[allow(clippy::incompatible_msrv)] // intrinsics are gated to rustc >= 1.89 by build.rs
485#[target_feature(enable = "avx512f")]
486#[inline]
487unsafe fn get512(a: &mut &[u8]) -> arch::__m512i {
488    let r = arch::_mm512_loadu_si512(a[..64].as_ptr() as *const _);
489    *a = &a[64..];
490    r
491}
492
493#[cfg(test)]
494mod test {
495    quickcheck::quickcheck! {
496        fn check_against_baseline(init: u32, chunks: Vec<(Vec<u8>, usize)>) -> bool {
497            let mut baseline = init;
498            let mut pclmulqdq = init;
499            let spec = super::State::new().expect("not supported");
500
501            for (chunk, mut offset) in chunks {
502                // simulate random alignments by offsetting the slice by up to 15 bytes
503                offset &= 0xF;
504                if chunk.len() <= offset {
505                    baseline = crate::baseline::update_fast_16(baseline, &chunk);
506                    pclmulqdq = spec.update(pclmulqdq, &chunk);
507                } else {
508                    baseline = crate::baseline::update_fast_16(baseline, &chunk[offset..]);
509                    pclmulqdq = spec.update(pclmulqdq, &chunk[offset..]);
510                }
511            }
512            pclmulqdq == baseline
513        }
514    }
515
516    // Exercises the wide fold paths across the sizes and alignments where the strategy switches.
517    #[test]
518    fn check_large_inputs_against_baseline() {
519        let mut data = vec![0u8; 8200];
520        let mut s: u32 = 0x1234_5678;
521        for b in data.iter_mut() {
522            s = s.wrapping_mul(1_664_525).wrapping_add(1_013_904_223);
523            *b = (s >> 24) as u8;
524        }
525
526        for &len in &[
527            0usize, 1, 15, 16, 17, 63, 64, 127, 128, 129, 255, 256, 257, 511, 512, 513, 1023, 1024,
528            1025, 2047, 2048, 2049, 2175, 2176, 2303, 2304, 4096, 8192, 8199,
529        ] {
530            for &offset in &[0usize, 1, 3, 7, 8, 15] {
531                if offset + len > data.len() {
532                    continue;
533                }
534                let slice = &data[offset..offset + len];
535                let baseline = crate::baseline::update_fast_16(0, slice);
536                let spec = super::State::new().expect("not supported");
537                let specialized = spec.update(0, slice);
538
539                assert_eq!(
540                    specialized, baseline,
541                    "mismatch for len={len} offset={offset}",
542                );
543            }
544        }
545    }
546}