structured-zstd 0.0.40

Pure Rust zstd implementation — managed fork of ruzstd. Dictionary decompression, no FFI.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
//! CPU kernel dispatch — single detect+match at the dispatch site,
//! propagated through the inner pipeline as a generic parameter so
//! leaf hot-path code monomorphises against the chosen kernel.
//!
//! See issue #247 for the architecture rationale: per-subsystem
//! dispatch scatters the choice across HUF / FSE / SIMD-copy
//! independently and pays the cost N times per call. Lifting the
//! dispatch to the outermost feasible call site collapses it to one
//! detect there; the inner leaf-hot-path ops then route through
//! `K::method` calls on the chosen kernel zero-sized type.
//!
//! Current wiring (as of #247 Part 2): the only active dispatch site
//! is `decoding::literals_section_decoder::decompress_literals`,
//! which `match`es `detect_cpu_kernel()` and routes into per-K
//! `decompress_literals_*` `#[target_feature]` wrappers. The full
//! pipeline-wide propagation envisioned in the issue (FrameDecoder /
//! FrameCompressor entry, sequence executor, match copy) is
//! incremental; subsequent tiers extend the dispatch surface without
//! changing this trait or the kernel ZSTs.
//!
//! Structure code (block loop, FCS check, offset history, repeat
//! semantics) stays single-impl and only carries `K` as a phantom on
//! the outer function. Monomorphisation specialises ONLY the bodies
//! that actually differ per ISA — `mask_lower_bits`, `huf_burst`,
//! `copy_chunk`, etc.

#[cfg(feature = "std")]
use std::sync::OnceLock;

/// Trait covering the leaf hot-path operations whose bodies differ
/// per ISA. Implementations are ZSTs; the trait is `Copy` so it can
/// be `Default`-constructed at each call site without runtime cost.
///
/// New methods land here ONLY when their codegen genuinely differs
/// per kernel (BMI2 intrinsic vs scalar shift, AVX2 256-bit move vs
/// SSE2 128-bit move, etc.). Structure ops that have one canonical
/// implementation must NOT be on this trait — they stay on the
/// existing decoder / encoder types.
// Public (rather than `pub(crate)`) because `BitReaderReversed` is
// generic over `K: CpuKernel = ScalarKernel` and is re-exported via
// the `bench_internals`-gated `testing` module; under that feature
// the visibility of every type that appears in `BitReaderReversed`'s
// bounds (the trait + the default kernel) must match the type's own
// visibility, otherwise rustc rejects with `private_bounds` /
// `private_interfaces`. The trait surface stays narrow on stable
// crate users: nothing outside `bench_internals` constructs a
// non-Scalar kernel directly.
pub trait CpuKernel: Copy + 'static {
    /// Mask the low `n` bits of `value`, returning the remaining
    /// high bits zeroed. The FSE bitstream hot path fires this 3×
    /// per decoded sequence; on BMI2-capable hardware this maps to
    /// a single `_bzhi_u64` instruction, otherwise to a scalar
    /// `u64::MAX >> (64 - n)` shift + mask.
    ///
    /// Precondition: `n <= 64`. Behaviour for `n == 0` is "return 0";
    /// behaviour for `n > 64` is unspecified — callers MUST uphold
    /// the bound. The test-only `mask_lower_bits` helper in
    /// `bit_reader_reverse.rs` debug-asserts the bound for its
    /// unit tests, but production callers (FSE / HUF hot paths)
    /// derive `n` from `accuracy_log` / `max_num_bits` which the
    /// per-stream table builders pin to `n <= MAX_*_BITS` at
    /// construction time; no per-call wrapper assert runs.
    fn mask_lower_bits(value: u64, n: u8) -> u64;
}

/// Scalar fallback — portable, no SIMD or BMI2 intrinsics. Selected
/// when no x86 or aarch64 feature is detected at runtime.
#[derive(Copy, Clone, Default)]
pub struct ScalarKernel;

impl CpuKernel for ScalarKernel {
    #[inline(always)]
    fn mask_lower_bits(value: u64, n: u8) -> u64 {
        // `checked_shr` returns `None` for shift counts >= 64, which
        // happens exactly when `n == 0` (`64 - 0 = 64`). Mapping
        // both that case and the invalid `n > 64` underflow to 0
        // gives the mathematically-correct empty mask for n=0 and
        // a safe-ish fallback for the invalid range.
        let mask = u64::MAX
            .checked_shr(64u32.wrapping_sub(n as u32))
            .unwrap_or(0);
        value & mask
    }
}

// The SSE2 tier exists in `CpuKernelTag` (it carries the 128-bit copy-chunk
// choice for the unified copy dispatch) but needs no `CpuKernel` ZST yet: the
// only trait method, `mask_lower_bits`, has no SSE2-specific form (SSE2 has no
// bit-extract), so the Sse2 tag routes through the scalar bodies for the
// FSE/HUF paths. A dedicated `Sse2Kernel` lands when `copy_chunk` moves onto
// the trait.

/// x86_64 BMI2-only kernel: `_bzhi_u64` for mask_lower_bits. Selected
/// when the CPU has BMI2 but not the AVX2 SIMD width to upgrade to
/// the Avx2 kernel. Treated as a stepping stone between Sse2 and
/// Avx2 on hardware that has BMI2 but not AVX2 (rare in practice but
/// matches donor's gating).
#[cfg(all(target_arch = "x86_64", feature = "kernel_bmi2"))]
#[derive(Copy, Clone, Default)]
pub(crate) struct Bmi2Kernel;

#[cfg(all(target_arch = "x86_64", feature = "kernel_bmi2"))]
impl CpuKernel for Bmi2Kernel {
    #[inline(always)]
    fn mask_lower_bits(value: u64, n: u8) -> u64 {
        // SAFETY: this kernel ZST is only reachable via the
        // `match detect_cpu_kernel() { CpuKernelTag::Bmi2 => ... }`
        // dispatch arms at decoder entry sites, all of which fire only
        // after `detect_cpu_kernel` confirmed BMI2 is available on the
        // running CPU.
        unsafe { mask_lower_bits_bmi2_impl(value, n) }
    }
}

/// x86_64 AVX2 + BMI2 kernel (x86-64-v3 baseline). The common modern
/// x86 case — most CPUs released since 2013 (Haswell) have AVX2+BMI2.
/// Uses `_bzhi_u64` for mask ops; future trait methods will use AVX2
/// 256-bit moves for `copy_chunk` and pext for HUF burst.
#[cfg(all(target_arch = "x86_64", feature = "kernel_avx2"))]
#[derive(Copy, Clone, Default)]
pub(crate) struct Avx2Kernel;

#[cfg(all(target_arch = "x86_64", feature = "kernel_avx2"))]
impl CpuKernel for Avx2Kernel {
    #[inline(always)]
    fn mask_lower_bits(value: u64, n: u8) -> u64 {
        // SAFETY: Avx2Kernel is selected only after runtime detect
        // confirmed both AVX2 and BMI2 — `_bzhi_u64` is callable.
        unsafe { mask_lower_bits_bmi2_impl(value, n) }
    }
}

/// x86_64 AVX-512 VBMI2 + AVX2 + BMI2 kernel. Selected when the CPU
/// has the AVX-512 VBMI2 family available — VBMI2 unlocks a faster
/// HUF burst inner loop (VPSHUFB-based table lookup); BMI2 mask_lower
/// bits stays identical to Avx2 kernel.
#[cfg(all(target_arch = "x86_64", feature = "kernel_vbmi2"))]
#[derive(Copy, Clone, Default)]
pub(crate) struct Vbmi2Kernel;

#[cfg(all(target_arch = "x86_64", feature = "kernel_vbmi2"))]
impl CpuKernel for Vbmi2Kernel {
    #[inline(always)]
    fn mask_lower_bits(value: u64, n: u8) -> u64 {
        // SAFETY: same precondition as Avx2Kernel — BMI2 confirmed
        // at runtime before this kernel is instantiated.
        unsafe { mask_lower_bits_bmi2_impl(value, n) }
    }
}

/// aarch64 NEON baseline kernel. Used on all aarch64 hardware that
/// exposes NEON (effectively universal on the supported targets).
///
/// `#[allow(dead_code)]`: scaffolding for the future aarch64 dispatch
/// arm in `decompress_literals` / `decode_and_execute_sequences`.
/// The struct + trait impl land first so the dispatch wiring can be
/// added incrementally without churning the CpuKernel surface; until
/// the dispatch arm uses it the type is reachable only as a phantom.
#[cfg(all(target_arch = "aarch64", feature = "kernel_neon"))]
#[allow(dead_code)]
#[derive(Copy, Clone, Default)]
pub(crate) struct NeonKernel;

#[cfg(all(target_arch = "aarch64", feature = "kernel_neon"))]
impl CpuKernel for NeonKernel {
    #[inline(always)]
    fn mask_lower_bits(value: u64, n: u8) -> u64 {
        // aarch64 has no BMI2 equivalent that improves on the scalar
        // shift-and-mask sequence for this op; the codegen is
        // identical to the Scalar kernel here. Other trait methods
        // (huf_burst, copy_chunk) will diverge once they land.
        ScalarKernel::mask_lower_bits(value, n)
    }
}

/// aarch64 SVE kernel. Variable-vector-length SVE extends NEON for
/// HUF burst / SIMD copy on Graviton3 / Apple M-series with SVE
/// support. Mask op identical to NEON / Scalar.
///
/// `#[allow(dead_code)]`: same scaffolding rationale as `NeonKernel`.
#[cfg(all(target_arch = "aarch64", feature = "kernel_sve"))]
#[allow(dead_code)]
#[derive(Copy, Clone, Default)]
pub(crate) struct SveKernel;

#[cfg(all(target_arch = "aarch64", feature = "kernel_sve"))]
impl CpuKernel for SveKernel {
    #[inline(always)]
    fn mask_lower_bits(value: u64, n: u8) -> u64 {
        ScalarKernel::mask_lower_bits(value, n)
    }
}

/// Single `#[target_feature(enable = "bmi2")]` wrapper around the
/// `_bzhi_u64` intrinsic. Lifted to a free function so each kernel
/// impl that needs the BMI2 path (Bmi2 / Avx2 / Vbmi2) calls the
/// same shared body. With `#[inline]` LLVM inlines the call into
/// any caller that itself has BMI2 in scope; outside that scope the
/// target_feature boundary is preserved.
#[cfg(all(target_arch = "x86_64", feature = "kernel_bmi2"))]
#[target_feature(enable = "bmi2")]
#[inline]
unsafe fn mask_lower_bits_bmi2_impl(value: u64, n: u8) -> u64 {
    // The intrinsic call is permitted directly inside a function
    // already annotated `#[target_feature(enable = "bmi2")]` — no
    // `unsafe { ... }` block needed (the function-level `unsafe`
    // already covers it). SAFETY: caller selected a kernel whose
    // CpuKernelTag was resolved after `is_x86_feature_detected!("bmi2")`
    // returned true, so the BMI2 instruction set is available.
    core::arch::x86_64::_bzhi_u64(value, n as u32)
}

/// Pure boolean-input variant of the x86 kernel-tag selection. Both the
/// `std` runtime-detect path and the `no_std` compile-time-cfg path
/// route through this helper so the precedence rules stay in one place
/// (and are unit-testable without runtime CPUID).
///
/// The VBMI2 tier requires every AVX-512 sub-feature it touches AND the
/// AVX2 baseline — VBMI2 kernels mix VBMI2-only intrinsics with AVX2
/// 256-bit moves, so the dispatch must be conditioned on `has_avx2` too.
/// Likewise the Avx2 tier requires both AVX2 and BMI2.
#[cfg(target_arch = "x86_64")]
#[inline(always)]
// Params go unused when the matching `kernel_*` feature is disabled (the
// rung that consumes them is `#[cfg]`-ed out); they are still passed by the
// detect callers. Silence the conditional unused-variable warning rather
// than thread per-feature `_`-prefixes through the signature.
#[allow(unused_variables)]
const fn select_x86_kernel(
    has_avx512vbmi2: bool,
    has_avx512f: bool,
    has_avx512vl: bool,
    has_avx512bw: bool,
    has_bmi2: bool,
    has_avx2: bool,
    has_sse2: bool,
) -> CpuKernelTag {
    #[cfg(feature = "kernel_vbmi2")]
    if has_avx512vbmi2 && has_avx512f && has_avx512vl && has_avx512bw && has_bmi2 && has_avx2 {
        return CpuKernelTag::Vbmi2;
    }
    #[cfg(feature = "kernel_avx2")]
    if has_avx2 && has_bmi2 {
        return CpuKernelTag::Avx2;
    }
    #[cfg(feature = "kernel_bmi2")]
    if has_bmi2 {
        return CpuKernelTag::Bmi2;
    }
    #[cfg(feature = "kernel_sse2")]
    if has_sse2 {
        return CpuKernelTag::Sse2;
    }
    CpuKernelTag::Scalar
}

/// Cached runtime-detected kernel tag. The actual `CpuKernel` impl
/// (`ScalarKernel` / `Bmi2Kernel` / `Avx2Kernel` / `Vbmi2Kernel` /
/// `NeonKernel` / `SveKernel`) is constructed at the dispatch site —
/// currently only `decoding::literals_section_decoder::decompress_literals`
/// — via a `match` on this tag that branches into the per-K
/// `target_feature`-wrapped specialisation. Pipeline-wide dispatch
/// (FrameDecoder / FrameCompressor entry, sequence executor, match
/// copy) lands incrementally in follow-up tiers.
#[derive(Copy, Clone, Debug, Eq, PartialEq)]
pub(crate) enum CpuKernelTag {
    Scalar,
    #[cfg(all(target_arch = "x86_64", feature = "kernel_sse2"))]
    Sse2,
    #[cfg(all(target_arch = "x86_64", feature = "kernel_bmi2"))]
    Bmi2,
    #[cfg(all(target_arch = "x86_64", feature = "kernel_avx2"))]
    Avx2,
    #[cfg(all(target_arch = "x86_64", feature = "kernel_vbmi2"))]
    Vbmi2,
    #[cfg(all(target_arch = "aarch64", feature = "kernel_neon"))]
    Neon,
    // Both constructors of `Sve` need a reachable feature: runtime
    // detection via `std::arch::is_aarch64_feature_detected!` (so
    // `feature = "std"`) or compile-time `target_feature = "sve"` in
    // RUSTFLAGS. Without either, the variant is unreachable and a
    // `match` arm referencing it warns as dead.
    #[cfg(all(
        target_arch = "aarch64",
        feature = "kernel_sve",
        any(feature = "std", target_feature = "sve"),
    ))]
    Sve,
}

/// Detect once and cache the best available CPU kernel for the
/// current process. Subsequent calls return the cached tag without
/// re-running CPU-feature detection. Std-only — no-std targets use
/// the compile-time variant below that resolves at build time.
#[cfg(feature = "std")]
pub(crate) fn detect_cpu_kernel() -> CpuKernelTag {
    static CACHED: OnceLock<CpuKernelTag> = OnceLock::new();
    *CACHED.get_or_init(detect_cpu_kernel_uncached)
}

#[cfg(feature = "std")]
fn detect_cpu_kernel_uncached() -> CpuKernelTag {
    #[cfg(target_arch = "x86_64")]
    {
        use std::arch::is_x86_feature_detected;
        // Gate each probe on its tier feature: `cfg!(...)` const-folds, so the
        // `&&` short-circuits away the runtime `is_x86_feature_detected!` call
        // (and its CPUID/cache traffic) for tiers the build disabled — the
        // matching `select_x86_kernel` rung is `#[cfg]`-ed out anyway.
        return select_x86_kernel(
            cfg!(feature = "kernel_vbmi2") && is_x86_feature_detected!("avx512vbmi2"),
            cfg!(feature = "kernel_vbmi2") && is_x86_feature_detected!("avx512f"),
            cfg!(feature = "kernel_vbmi2") && is_x86_feature_detected!("avx512vl"),
            cfg!(feature = "kernel_vbmi2") && is_x86_feature_detected!("avx512bw"),
            cfg!(feature = "kernel_bmi2") && is_x86_feature_detected!("bmi2"),
            cfg!(feature = "kernel_avx2") && is_x86_feature_detected!("avx2"),
            cfg!(feature = "kernel_sse2") && is_x86_feature_detected!("sse2"),
        );
    }
    #[cfg(target_arch = "aarch64")]
    {
        #[cfg(any(feature = "kernel_sve", feature = "kernel_neon"))]
        use std::arch::is_aarch64_feature_detected;
        #[cfg(feature = "kernel_sve")]
        if is_aarch64_feature_detected!("sve") {
            return CpuKernelTag::Sve;
        }
        #[cfg(feature = "kernel_neon")]
        if is_aarch64_feature_detected!("neon") {
            return CpuKernelTag::Neon;
        }
        return CpuKernelTag::Scalar;
    }
    #[allow(unreachable_code)]
    CpuKernelTag::Scalar
}

/// no-std variant: rely on compile-time `target_feature` flags
/// instead of runtime detection. Resolves to the most-capable kernel
/// that the build target supports.
#[cfg(not(feature = "std"))]
pub(crate) fn detect_cpu_kernel() -> CpuKernelTag {
    #[cfg(target_arch = "x86_64")]
    {
        // Route through the same const-fn precedence helper as the
        // `feature = "std"` path. `cfg!(target_feature = ...)`
        // returns a compile-time bool that constant-folds through
        // `select_x86_kernel`, so the runtime call has the same
        // codegen as the previous hand-written #[cfg] chain.
        return select_x86_kernel(
            cfg!(target_feature = "avx512vbmi2"),
            cfg!(target_feature = "avx512f"),
            cfg!(target_feature = "avx512vl"),
            cfg!(target_feature = "avx512bw"),
            cfg!(target_feature = "bmi2"),
            cfg!(target_feature = "avx2"),
            cfg!(target_feature = "sse2"),
        );
    }
    #[cfg(target_arch = "aarch64")]
    {
        #[cfg(all(feature = "kernel_sve", target_feature = "sve"))]
        {
            return CpuKernelTag::Sve;
        }
        #[cfg(all(feature = "kernel_neon", target_feature = "neon"))]
        {
            return CpuKernelTag::Neon;
        }
    }
    #[allow(unreachable_code)]
    CpuKernelTag::Scalar
}

impl CpuKernelTag {
    /// Stable lowercase diagnostic name for this tier (used by
    /// [`active_cpu_kernel_name`] and the bench/dashboard reporting). Pure
    /// mapping over the tag, so every arm is exercisable in tests regardless
    /// of which tier the running CPU actually resolves to.
    pub(crate) fn name(self) -> &'static str {
        match self {
            CpuKernelTag::Scalar => "scalar",
            #[cfg(all(target_arch = "x86_64", feature = "kernel_sse2"))]
            CpuKernelTag::Sse2 => "sse2",
            #[cfg(all(target_arch = "x86_64", feature = "kernel_bmi2"))]
            CpuKernelTag::Bmi2 => "bmi2",
            #[cfg(all(target_arch = "x86_64", feature = "kernel_avx2"))]
            CpuKernelTag::Avx2 => "avx2",
            #[cfg(all(target_arch = "x86_64", feature = "kernel_vbmi2"))]
            CpuKernelTag::Vbmi2 => "vbmi2",
            #[cfg(all(target_arch = "aarch64", feature = "kernel_neon"))]
            CpuKernelTag::Neon => "neon",
            #[cfg(all(
                target_arch = "aarch64",
                feature = "kernel_sve",
                any(feature = "std", target_feature = "sve"),
            ))]
            CpuKernelTag::Sve => "sve",
        }
    }
}

/// Name of the CPU kernel tier this process selected for the entropy /
/// sequence hot paths: decode (literals + FSE sequence decode) and encode
/// (entropy) share this dispatch (see #247). Returned as a stable lowercase
/// string for diagnostics and benchmark/dashboard reporting; the value is
/// what the runtime CPU-feature detection (or compile-time `target_feature`
/// on `no_std`) actually resolves to on this machine, so a dashboard can
/// attribute a measurement to the kernel that produced it.
pub fn active_cpu_kernel_name() -> &'static str {
    detect_cpu_kernel().name()
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn scalar_mask_lower_bits_zero_n_returns_zero() {
        assert_eq!(ScalarKernel::mask_lower_bits(0xDEADBEEF, 0), 0);
    }

    #[test]
    fn scalar_mask_lower_bits_full_64_returns_full_value() {
        assert_eq!(
            ScalarKernel::mask_lower_bits(0xFFFF_FFFF_FFFF_FFFF, 64),
            0xFFFF_FFFF_FFFF_FFFF
        );
    }

    #[test]
    fn scalar_mask_lower_bits_mid_keeps_low_n_bits() {
        // n=8: keep low 8 bits, zero the rest
        assert_eq!(ScalarKernel::mask_lower_bits(0xDEAD_BEEF, 8), 0xEF);
        assert_eq!(
            ScalarKernel::mask_lower_bits(0x0102_0304_0506_0708, 16),
            0x0708
        );
    }

    // Gated on `std` AND `kernel_avx2`: the `is_x86_feature_detected!`
    // guard below is a no-op under `--no-default-features` (no std,
    // no runtime feature detection), so the test body would call
    // `Avx2Kernel::mask_lower_bits` unconditionally and SIGILL on any
    // non-BMI2 CPU — hence `feature = "std"`. `Avx2Kernel` itself is
    // `#[cfg(feature = "kernel_avx2")]`, so the test must also require
    // that feature or a `std`-only trimmed build (`kernel_avx2` off)
    // fails to compile against the undefined type.
    #[cfg(all(target_arch = "x86_64", feature = "std", feature = "kernel_avx2"))]
    #[test]
    fn avx2_mask_lower_bits_matches_scalar_on_bmi2_hw() {
        // Only run when BMI2 actually available — otherwise constructing
        // Avx2Kernel via dispatch wouldn't happen.
        if !std::arch::is_x86_feature_detected!("bmi2") {
            return;
        }
        for n in 0..=64u8 {
            let v = 0x1234_5678_9ABC_DEF0u64;
            assert_eq!(
                Avx2Kernel::mask_lower_bits(v, n),
                ScalarKernel::mask_lower_bits(v, n),
                "mismatch at n={}",
                n
            );
        }
    }

    /// Regression: a CPU advertising AVX-512 VBMI2 but NOT AVX2 (the
    /// AMD64 baseline allows this combination at the spec level) was
    /// previously selected as `Vbmi2`, which would SIGILL on the
    /// first AVX2-mixed VBMI2 kernel invocation. The selection must
    /// fall through to Scalar (or a non-AVX tier) in that case.
    #[cfg(all(target_arch = "x86_64", feature = "kernel_vbmi2"))]
    #[test]
    fn select_x86_kernel_vbmi2_without_avx2_does_not_pick_vbmi2() {
        let tag = select_x86_kernel(
            /* avx512vbmi2 */ true, /* avx512f */ true, /* avx512vl */ true,
            /* avx512bw */ true, /* bmi2 */ true, /* avx2 */ false,
            /* sse2 */ true,
        );
        assert_ne!(
            tag,
            CpuKernelTag::Vbmi2,
            "selecting Vbmi2 without AVX2 would call AVX2 instructions and SIGILL"
        );
    }

    /// Sanity: when every flag is present the selector returns Vbmi2.
    #[cfg(all(target_arch = "x86_64", feature = "kernel_vbmi2"))]
    #[test]
    fn select_x86_kernel_full_x86_v4_picks_vbmi2() {
        let tag = select_x86_kernel(true, true, true, true, true, true, true);
        assert_eq!(tag, CpuKernelTag::Vbmi2);
    }

    /// Sanity: AVX2 + BMI2 without AVX-512 → Avx2.
    #[cfg(all(target_arch = "x86_64", feature = "kernel_avx2"))]
    #[test]
    fn select_x86_kernel_avx2_baseline_picks_avx2() {
        let tag = select_x86_kernel(false, false, false, false, true, true, true);
        assert_eq!(tag, CpuKernelTag::Avx2);
    }

    /// SSE2-only (no BMI2/AVX2) → Sse2, the x86_64 floor above Scalar.
    #[cfg(all(target_arch = "x86_64", feature = "kernel_sse2"))]
    #[test]
    fn select_x86_kernel_sse2_only_picks_sse2() {
        let tag = select_x86_kernel(false, false, false, false, false, false, true);
        assert_eq!(tag, CpuKernelTag::Sse2);
    }

    /// No SIMD flags at all → Scalar (off-x86_64 / pre-SSE2 x86).
    #[cfg(target_arch = "x86_64")]
    #[test]
    fn select_x86_kernel_no_features_picks_scalar() {
        let tag = select_x86_kernel(false, false, false, false, false, false, false);
        assert_eq!(tag, CpuKernelTag::Scalar);
    }

    #[test]
    fn detect_returns_consistent_tag() {
        let first = detect_cpu_kernel();
        let second = detect_cpu_kernel();
        assert_eq!(
            first, second,
            "cached detect must return same tag on repeated calls"
        );
    }

    #[test]
    fn active_kernel_name_is_known_lowercase_tier() {
        // The diagnostic name must be one of the stable lowercase tier
        // strings the dashboard parses, and must match whatever tier
        // detection resolves to on this host (no `unknown` / empty leak).
        const KNOWN: &[&str] = &["scalar", "sse2", "bmi2", "avx2", "vbmi2", "neon", "sve"];
        let name = active_cpu_kernel_name();
        assert!(
            KNOWN.contains(&name),
            "active kernel name {name:?} is not a recognised tier"
        );
        assert_eq!(
            name,
            name.to_ascii_lowercase(),
            "tier name must be lowercase for stable dashboard parsing"
        );
    }

    #[test]
    fn every_kernel_tag_maps_to_its_lowercase_name() {
        // `active_cpu_kernel_name` only exercises whichever arm the running
        // CPU resolves to, so map each constructible tag directly to cover
        // every branch on this build's feature set.
        assert_eq!(CpuKernelTag::Scalar.name(), "scalar");
        #[cfg(all(target_arch = "x86_64", feature = "kernel_sse2"))]
        assert_eq!(CpuKernelTag::Sse2.name(), "sse2");
        #[cfg(all(target_arch = "x86_64", feature = "kernel_bmi2"))]
        assert_eq!(CpuKernelTag::Bmi2.name(), "bmi2");
        #[cfg(all(target_arch = "x86_64", feature = "kernel_avx2"))]
        assert_eq!(CpuKernelTag::Avx2.name(), "avx2");
        #[cfg(all(target_arch = "x86_64", feature = "kernel_vbmi2"))]
        assert_eq!(CpuKernelTag::Vbmi2.name(), "vbmi2");
        #[cfg(all(target_arch = "aarch64", feature = "kernel_neon"))]
        assert_eq!(CpuKernelTag::Neon.name(), "neon");
        #[cfg(all(
            target_arch = "aarch64",
            feature = "kernel_sve",
            any(feature = "std", target_feature = "sve"),
        ))]
        assert_eq!(CpuKernelTag::Sve.name(), "sve");
    }

    #[test]
    fn active_kernel_name_is_stable_across_calls() {
        // Backed by the cached `detect_cpu_kernel`, so repeated calls must
        // return the identical static string.
        assert_eq!(active_cpu_kernel_name(), active_cpu_kernel_name());
    }
}