Skip to main content

blake3_servil_core/
each.rs

1//! [`hash_each`]: a collection of messages of any lengths, each hashed,
2//! with short messages' chunks side by side in the SIMD lanes.
3//!
4//! Chunk k of every message has chunk counter k, so the full chunks k of
5//! different messages hash in one call of the many-inputs kernel, at counter
6//! k for every lane. Messages of up to a chunk share lanes by their block
7//! counts (`hash_by_blocks`); NEON with SHA-3 includes their last blocks in
8//! the same pass. Messages of 16 chunks or more fill the lanes alone; a
9//! longer message's last partial chunk hashes on its own. Each message's
10//! chunk chaining values then merge into its root as BLAKE3's tree places them.
11
12use crate::many::TABLE;
13use crate::platform::Platform;
14use crate::throughput::Block;
15use crate::{CHUNK_END, CHUNK_LEN, CHUNK_START, CVBytes, CVWords, ChunkState, Hash, Hasher, IncrementCounter, Mode, OUT_LEN};
16
17// Many messages arriving at once, such as a server's uploads, each with
18// its own Hasher: one call takes the pieces that have arrived for all of
19// them, which hash faster together than one Hasher::update each.
20
21/// Feed each piece to its hasher: `(i, bytes)` does
22/// `hashers[i].update(bytes)`, each hasher's pieces in their order in
23/// `pieces`. Call it once with all the pieces your program has in hand
24/// (one turn of its event loop): never slower than one
25/// [`update`](Hasher::update) each: many messages arriving at once, such
26/// as a server's uploads, each with its own [`Hasher`]. Requires each `i < hashers.len()`:
27/// a turn that panics on one that is not leaves its hashers as
28/// [after a panic](Hasher#after-a-panic).
29/// Finish the messages with [`finalize_each`]: plain messages of up to 1024
30/// bytes wait whole in their stage (on both x86-64 and AArch64), so those
31/// that finish together hash side by side there. Because a staged plain
32/// first chunk has not yet compressed into `ChunkState`, calling a
33/// non-consuming `Hasher::finalize()` mid-chunk rehashes that staged prefix
34/// afresh; callers that finish each message once via `finalize_each` avoid
35/// that cost.
36///
37/// # Panics
38///
39/// Panics on an out-of-range index, on a message exceeding `2^64 - 1` bytes,
40/// or on a poisoned hasher ([after a panic](Hasher#after-a-panic)); a turn
41/// that panics part-way may leave earlier pieces incorporated and later ones
42/// not.
43///
44/// # Or the Pipeline
45///
46/// A program with threads to give, whose messages keep arriving, has a
47/// faster way in the crate `blake3-servil` (this library with its thread
48/// pool): its `throughput::Pipeline` splits across worker cores (historically
49/// beating pre-batching `update_each` on 1,024 open 1 KiB messages on Ryzen
50/// 9700X / EPYC 9255, November 22, 2026, BLAKE3 #470, and taking a third of
51/// the time for 64 open messages of 1 MiB). It holds a room of 64 KiB for
52/// each open message. This call stays the right one:
53///
54/// - on one thread;
55/// - for more open messages than the program has 64 KiB each for (a
56///   `Hasher` is 26 KiB, and touches only what it uses);
57/// - where a message's running state is wanted: a clone, a `finalize`
58///   part-way;
59/// - for a small burst after a gap, about 256 KiB a turn, where the
60///   Pipeline's workers must first wake: there it read from 6% faster to
61///   20% slower than this call on the same two machines.
62///
63/// # Key-dependent timing
64///
65/// Hashers may use different secret keys. Grouping, kernel selection, and
66/// temporary storage sizes are independent of key values and key equality.
67/// See the [key-independence contract](crate#key-dependent-timing).
68///
69/// ```
70/// # blake3_servil_core::initialize();
71/// use blake3_servil_core::{convenience::Hasher, throughput};
72/// let mut hashers = vec![Hasher::new(blake3_servil_core::Mode::Plain, None), Hasher::new(blake3_servil_core::Mode::Plain, None)];
73/// throughput::update_each(&mut hashers, &[(0, b"ab"), (1, b"xyz"), (0, b"c")]);
74/// let mut out = [[0u8; 32]; 2];
75/// throughput::finalize_each(&mut hashers, &[0, 1], &mut out);
76/// let hash = blake3_servil_core::convenience::hash;
77/// assert_eq!((&out[0], &out[1]), (hash(b"abc").as_bytes(), hash(b"xyz").as_bytes()));
78/// ```
79pub fn update_each(hashers: &mut [Hasher], pieces: &[(usize, &[u8])]) {
80    update_turn(hashers, pieces);
81}
82
83/// RAII guard for `finalize_each`: records how many hashers in `which[..count]`
84/// have been marked `finishing`, and clears those marks on unwind (whether a
85/// bad/duplicate index fails preflight or an internal panic occurs mid-finish).
86struct Marked<'a> {
87    hashers: &'a mut [Hasher],
88    which: &'a [usize],
89    count: usize,
90    active: bool,
91}
92
93impl Drop for Marked<'_> {
94    fn drop(&mut self) {
95        if self.active {
96            for &i in &self.which[..self.count] {
97                self.hashers[i].clear_finishing();
98            }
99        }
100    }
101}
102
103/// The hash of each message `which` names: `out[k]` is what
104/// `hashers[which[k]].finalize()` would give, and that hasher is then
105/// reset for its next message (no length hint). Requires
106/// `out.len() == which.len()`, each index `< hashers.len()`, and distinct
107/// indices: it panics on an index named twice, in every build. A call
108/// that is refused hashes nothing and leaves every hasher as it was.
109/// Messages that finish in one call hash side by side where the CPU has
110/// the lanes (with at least two eligible hashers in a 128-hasher window):
111/// on x86-64, staged plain 1 KiB chunks via `hash_many_rounded` (ceiling
112/// 32 lanes on Zen 5 / 16 on AVX-512 / 8 on AVX2 / 4 on SSE4.1), staged
113/// plain multi-block `65..=1023 B` messages on AVX2/AVX-512 via
114/// `hash_by_blocks` (equal-prefix-length blocks batched in SIMD, and on Linux
115/// x86-64 AVX-512/AVX2 their final blocks compressed in `output16`/`output8`
116/// SIMD lanes for chunks of four or more; SSE4.1 finishes staged `< 1 KiB`
117/// messages individually), and `output16`/`output8` for every 4+ eligible
118/// counter-zero final blocks packed from remaining hashers on Linux
119/// AVX-512/AVX2; on AArch64, staged plain messages of up to 1024 bytes via
120/// `hash_by_blocks` and counter-zero final blocks via NEON `output8`.
121///
122/// # Panics
123///
124/// Panics if `out.len() != which.len()`, an index is out of range, an index
125/// is repeated, or any named hasher was poisoned
126/// ([after a panic](Hasher#after-a-panic)). A refused call hashes nothing,
127/// leaves `out` untouched, and leaves every hasher as it was.
128///
129/// # Key-dependent timing
130///
131/// Selected hashers may use different secret keys. Key values and key equality
132/// select neither the finalization path nor its amount of work.
133/// See the [key-independence contract](crate#key-dependent-timing).
134pub fn finalize_each(hashers: &mut [Hasher], which: &[usize], out: &mut [[u8; OUT_LEN]]) {
135    assert_eq!(which.len(), out.len(), "one digest per message named");
136    let mut marked = Marked { hashers, which, count: 0, active: true };
137    for &i in which {
138        assert!(i < marked.hashers.len(), "finalize_each names hasher {i} of {}", marked.hashers.len());
139        assert!(!marked.hashers[i].mark_finishing(), "each finalized index is distinct");
140        marked.count += 1;
141    }
142    let hashers = &mut *marked.hashers;
143    if which.is_empty() {
144        marked.active = false;
145        return;
146    }
147    if which.len() == 1 {
148        let i = which[0];
149        out[0] = *hashers[i].take_root_hash().as_bytes();
150        hashers[i].reset();
151        marked.active = false;
152        return;
153    }
154    // Delegate multi-hasher batching to an out-of-line architecture helper so
155    // empty and singleton calls never reserve the 128-slot batch stack frame.
156    #[cfg(target_arch = "x86_64")]
157    crate::ffi_partial::finalize_each(hashers, which, out);
158    #[cfg(target_arch = "aarch64")]
159    crate::ffi_output::finalize_each(hashers, which, out);
160    marked.active = false;
161}
162
163#[inline]
164pub(crate) fn finalize_indices_serial(hashers: &mut [Hasher], w_chunk: &[usize], slots: &[u8], o_chunk: &mut [[u8; OUT_LEN]]) {
165    for &k in slots {
166        let k = usize::from(k);
167        o_chunk[k] = *hashers[w_chunk[k]].take_root_hash().as_bytes();
168    }
169}
170
171/// Hash each held stage's 16 leaf chunks serially per stage on `platform` into
172/// `level`, using each hasher's own domain key and flags.
173pub(crate) fn hash_held_leaves_serial(hashers: &[Hasher], held: &[usize], platform: Platform, level: &mut [[u8; OUT_LEN]]) {
174    const PER: usize = crate::STAGE_LEN / CHUNK_LEN;
175    for (k, &i) in held.iter().enumerate() {
176        let h = &hashers[i];
177        let (counter, bytes) = h.held_group().expect("a held group");
178        let refs: [&[u8; CHUNK_LEN]; PER] = core::array::from_fn(|j| bytes[j * CHUNK_LEN..(j + 1) * CHUNK_LEN].try_into().unwrap());
179        let domain = h.domain();
180        platform.hash_many(
181            &refs,
182            domain.key(),
183            counter,
184            IncrementCounter::Yes,
185            domain.flags(),
186            CHUNK_START,
187            CHUNK_END,
188            level[k * PER..(k + 1) * PER].as_flattened_mut(),
189        );
190    }
191}
192
193/// Commit the four-level held-group reduction back into each `Hasher`: when
194/// `counter == 0`, four swaps leave the final root parent's two child CVs in
195/// `next[2 * k..2 * k + 2]`; otherwise the subtree CV is in `level[k]`.
196pub(crate) fn commit_held_groups(hashers: &mut [Hasher], held: &[usize], level: &[[u8; OUT_LEN]], next: &[[u8; OUT_LEN]]) {
197    for (k, &i) in held.iter().enumerate() {
198        let (counter, _) = hashers[i].held_group().unwrap();
199        let mut result = [0u8; crate::BLOCK_LEN];
200        if counter == 0 {
201            result.copy_from_slice(next[2 * k..2 * k + 2].as_flattened());
202        } else {
203            result[..OUT_LEN].copy_from_slice(&level[k]);
204        }
205        hashers[i].take_held(&result);
206    }
207}
208
209/// A turn of pieces for many hashers, in caller order: each piece
210/// gathered into its hasher's stage; a stage that fills a whole group is
211/// held, and its hasher's later bytes (the rest of that piece, and its
212/// later pieces) wait, in order, until the held groups hash together, up
213/// to TABLE of them in one pass (one SME2 call for all; elsewhere a call
214/// per group, then each parent level in one call). A full table, a full
215/// waiting list, or the turn's end hashes what is held and gathers what
216/// waited, pass after pass, until nothing waits. Outside a drain every
217/// waiting piece's hasher is held (it entered waiting because the hasher
218/// was held, or as the rest of the piece that filled the stage; only a
219/// drain un-holds, and a drain leaves nothing waiting), so a hasher that
220/// is not held has no earlier bytes waiting, and takes its piece now. Both
221/// lists live on the stack: a turn allocates nothing.
222fn update_turn(hashers: &mut [Hasher], pieces: &[(usize, &[u8])]) {
223    /// The stages a turn holds, hashed however the turn ends. A turn that
224    /// panics part-way (an index that names no hasher) unwinds through
225    /// here: a full stage that no list named
226    /// any more would have no room for its hasher's next update, and its
227    /// next turn would wait for ever for a pass to hash it. `flush_held`
228    /// detaches the list before hashing so an unwind out of `hash_held`
229    /// itself cannot make `Drop` retry the failing call.
230    struct Held<'h> {
231        hashers: &'h mut [Hasher],
232        held: crate::stack_vec::StackVec<usize, TABLE>,
233    }
234    impl Drop for Held<'_> {
235        fn drop(&mut self) {
236            flush_held(self.hashers, &mut self.held);
237        }
238    }
239    let mut turn = Held { hashers, held: crate::stack_vec::StackVec::new() };
240    let mut waiting = crate::stack_vec::StackVec::<(usize, &[u8]), TABLE>::new();
241    for &(i, bytes) in pieces {
242        if waiting.is_full() || turn.held.is_full() {
243            drain(turn.hashers, &mut turn.held, &mut waiting);
244        }
245        if turn.hashers[i].held_group().is_some() {
246            waiting.push((i, bytes));
247            continue;
248        }
249        gather(turn.hashers, i, bytes, &mut turn.held, &mut waiting);
250    }
251    drain(turn.hashers, &mut turn.held, &mut waiting);
252}
253
254/// `bytes` into hasher `i`, which is not held: as much as fills its stage;
255/// a filled stage is held and the rest of the piece waits.
256fn gather<'a>(
257    hashers: &mut [Hasher],
258    i: usize,
259    bytes: &'a [u8],
260    held: &mut crate::stack_vec::StackVec<usize, TABLE>,
261    waiting: &mut crate::stack_vec::StackVec<(usize, &'a [u8]), TABLE>,
262) {
263    // Debug-only: `gather` is called only for unheld hashers (checked by callers in `each`).
264    debug_assert!(hashers[i].held_group().is_none(), "a held hasher's bytes wait");
265    let rest = hashers[i].gather_part(bytes, None, true);
266    assert!(rest.len() < bytes.len() || bytes.is_empty(), "a turn's pass gathered nothing");
267    if hashers[i].held_group().is_some() {
268        held.push(i);
269        if !rest.is_empty() {
270            waiting.push((i, rest));
271        }
272    }
273}
274
275/// Hash the held groups, then gather what waited, in order, pass after
276/// pass, until nothing waits. Each pass starts with every hasher free, so
277/// the first waiting piece of each hasher gathers and shrinks the bytes
278/// in play; a hasher filled again in the pass sends its later pieces back
279/// to wait. A pass holds at most one group per hasher and keeps at most
280/// as many pieces waiting as it took, so neither list overflows.
281fn drain<'a>(hashers: &mut [Hasher], held: &mut crate::stack_vec::StackVec<usize, TABLE>, waiting: &mut crate::stack_vec::StackVec<(usize, &'a [u8]), TABLE>) {
282    loop {
283        flush_held(hashers, held);
284        if waiting.is_empty() {
285            return;
286        }
287        let batch = core::mem::take(waiting);
288        for &(i, bytes) in &batch {
289            if hashers[i].held_group().is_some() {
290                waiting.push((i, bytes));
291            } else {
292                gather(hashers, i, bytes, held, waiting);
293            }
294        }
295        assert!(waiting.len() < batch.len() || !held.is_empty(), "drain made no progress");
296    }
297}
298
299/// The fewest held stages that take the independent parent lanes. Two
300/// keyed hashers each hash alone at full width instead: on an Ice Lake
301/// Xeon the lanes cost a pair 3.5% of a whole cycle (16 and 32 KiB
302/// messages in 4 KiB pieces, November 10, 2026), and from eight up they
303/// gain 2-3% there and 7-11% on an EPYC 9255. The count is public; no
304/// key decides the route.
305const INDEPENDENT_MIN: usize = 3;
306
307/// Hash every queued stage after detaching the table so an unwind inside
308/// `hash_held` cannot make `Held::drop` retry the same failing call.
309fn flush_held(hashers: &mut [Hasher], held: &mut crate::stack_vec::StackVec<usize, TABLE>) {
310    if held.is_empty() {
311        return;
312    }
313    let list = core::mem::take(held);
314    hash_held(hashers, &list);
315}
316
317#[cfg(test)]
318std::thread_local! {
319    // Actual cohorts passed to the shared-key or independent-parent body.
320    static HELD_GROUPS: core::cell::RefCell<Vec<Vec<usize>>> = const { core::cell::RefCell::new(Vec::new()) };
321}
322
323/// On x86-64 Linux and AArch64, hash the held stages with an independent key
324/// per parent lane (and on SME2, one multi-group keyed leaf entry), when any
325/// of them is keyed and there are enough of them, and say so. The mode, the
326/// count and the platform, all public, choose; key values never determine
327/// grouping, allocation or dispatch. Every other target compiles `hash_held`
328/// as it was.
329fn independent_lanes(hashers: &mut [Hasher], held: &[usize]) -> bool {
330    let Some(&first) = held.first() else { return false };
331    let platform = hashers[first].platform();
332    #[cfg(target_arch = "x86_64")]
333    if !matches!(platform, Platform::AVX2 | Platform::AVX512) {
334        return false;
335    }
336    // Public plain mode fixes every key to the IV: those share one pass.
337    if held.len() < INDEPENDENT_MIN || held.iter().all(|&i| hashers[i].is_plain()) {
338        return false;
339    }
340    crate::ffi_output::held_groups(hashers, held, platform);
341    #[cfg(test)]
342    let _ = HELD_GROUPS.try_with(|groups| groups.borrow_mut().push(held.to_vec()));
343    crate::counted(crate::Counted::HeldPass);
344    true
345}
346
347#[cfg(test)]
348std::thread_local! {
349    /// Most recent `hash_cohort::<N>` workspace tier used on this thread.
350    static LAST_COHORT_TIER: core::cell::Cell<usize> = const { core::cell::Cell::new(0) };
351}
352
353/// Hash the whole groups `held` names, one in each of those hashers'
354/// stages, and pass each group's subtree to its hasher's core. The plain
355/// hashers' groups hash together; a keyed or key-derivation hasher's group
356/// hashes alone, since its key is secret and must not decide the work
357/// (BLAKE3 #312): the mode alone, public, groups them.
358fn hash_held(hashers: &mut [Hasher], held: &[usize]) {
359    if independent_lanes(hashers, held) {
360        return;
361    }
362    // Plain's key is the IV, the same for every plain hasher. Tile larger
363    // cohorts in 16-stage L1D-hot blocks (`HeldWorkspace<16>`, ~15 KiB stack)
364    // under one shared `Sme2Turn` so even 17..=128 plain hashers fit inside a
365    // 64 KiB worker stack without reserving a 116 KiB `TABLE`-sized frame.
366    const PLAIN_TILE: usize = 16;
367    let mut plain = crate::stack_vec::StackVec::<usize, TABLE>::new();
368    plain.extend(held.iter().copied().filter(|&i| hashers[i].is_plain()));
369    if !plain.is_empty() {
370        #[cfg(test)]
371        let _ = HELD_GROUPS.try_with(|groups| groups.borrow_mut().push(plain.as_slice().to_vec()));
372        #[cfg(test)]
373        crate::counted(crate::Counted::HeldPass);
374        let turn = crate::platform::Sme2Turn::take(hashers[plain[0]].platform(), true);
375        let platform = turn.platform();
376        if plain.len() == 1 {
377            hash_cohort_on::<1>(hashers, &plain, platform);
378        } else {
379            for tile in plain.as_slice().chunks(PLAIN_TILE) {
380                hash_cohort_on::<PLAIN_TILE>(hashers, tile, platform);
381            }
382        }
383    }
384    for &i in held {
385        if !hashers[i].is_plain() {
386            hash_cohort::<1>(hashers, &[i]);
387        }
388    }
389}
390
391/// Parent blocks supplied by a full staged message's pairs of CVs.
392const STAGE_PARENTS: usize = ALONE_CHUNKS / 2;
393
394/// Contiguous parent inputs retain the kernels' direct path. Both CV
395/// levels live on the stack; ping-pong leaves the final two children in
396/// the other buffer. Block supplies the existing 64-byte alignment.
397pub(crate) struct HeldWorkspace<const N: usize> {
398    level: crate::stack_vec::StackVec<[Block; STAGE_PARENTS], N>,
399    next: crate::stack_vec::StackVec<[Block; STAGE_PARENTS / 2], N>,
400}
401
402impl<const N: usize> HeldWorkspace<N> {
403    /// Empty buffers, ready to initialize in their final place.
404    #[inline(always)]
405    pub(crate) fn new() -> Self {
406        const {
407            assert!(ALONE_CHUNKS == 16 && crate::STAGE_LEN == ALONE_CHUNKS * CHUNK_LEN);
408        }
409        Self { level: crate::stack_vec::StackVec::new(), next: crate::stack_vec::StackVec::new() }
410    }
411
412    /// Call once, with 1 <= count <= N: initialize through a borrow of the
413    /// workspace's final place, then borrow its two CV levels.
414    pub(crate) fn buffers(&mut self, count: usize) -> (&mut [CVBytes], &mut [CVBytes]) {
415        assert!(count > 0 && count <= N && self.level.is_empty() && self.next.is_empty(), "one fresh HeldWorkspace per cohort");
416        self.level.extend(core::iter::repeat_n([Block::ZERO; STAGE_PARENTS], count));
417        self.next.extend(core::iter::repeat_n([Block::ZERO; STAGE_PARENTS / 2], count));
418        let (level, _) = Block::bytes_mut(self.level.as_mut_slice().as_flattened_mut()).as_chunks_mut::<OUT_LEN>();
419        let (next, _) = Block::bytes_mut(self.next.as_mut_slice().as_flattened_mut()).as_chunks_mut::<OUT_LEN>();
420        (level, next)
421    }
422}
423
424/// Hash 1..=N distinct held stages: plain hashers together, or one keyed
425/// or derive-key hasher. Acquires an SME2 turn for the cohort and records
426/// test pass counters, then delegates to [`hash_cohort_on`].
427#[inline(never)]
428fn hash_cohort<const N: usize>(hashers: &mut [Hasher], alike: &[usize]) {
429    let first = alike[0];
430    #[cfg(test)]
431    let _ = HELD_GROUPS.try_with(|groups| groups.borrow_mut().push(alike.to_vec()));
432    #[cfg(test)]
433    crate::counted(crate::Counted::HeldPass);
434    let turn = crate::platform::Sme2Turn::take(hashers[first].platform(), true);
435    hash_cohort_on::<N>(hashers, alike, turn.platform());
436}
437
438/// Hash one tile of 1..=N distinct held stages on `platform` (with any SME2
439/// turn held by the caller across tiles). Keeps chunks and each parent level
440/// in a bounded `HeldWorkspace<N>` on the stack.
441// Keep the workspace frame out of empty turns and the other mode's caller.
442#[inline(never)]
443fn hash_cohort_on<const N: usize>(hashers: &mut [Hasher], alike: &[usize], platform: Platform) {
444    use crate::{BLOCK_LEN, PARENT};
445    let first = alike[0];
446    #[cfg(test)]
447    let _ = LAST_COHORT_TIER.try_with(|t| t.set(N));
448    let domain = hashers[first].domain();
449    let flags = domain.flags();
450    // Plain cohorts hash under the constant IV directly (fault isolation),
451    // while a keyed or derive-key hasher hashes alone here under its own key.
452    let key = if domain.is_plain() { *crate::IV } else { *domain.key() };
453    let mut work = HeldWorkspace::<N>::new();
454    let (mut level, mut next) = work.buffers(alike.len());
455    #[cfg(target_arch = "aarch64")]
456    let on_sme2 = matches!(platform, Platform::SME2);
457    #[cfg(not(target_arch = "aarch64"))]
458    let on_sme2 = false;
459    {
460        let mut refs = crate::stack_vec::StackVec::<[&[u8; CHUNK_LEN]; ALONE_CHUNKS], N>::new();
461        refs.extend(alike.iter().map(|&i| {
462            let hasher = &hashers[i];
463            // The shared key serves plain hashers only. Check the public
464            // mode as we take each stage, without comparing key bytes.
465            assert!(alike.len() == 1 || hasher.is_plain(), "only plain hashers share a cohort");
466            let stage = hasher.held_group().expect("a held group").1;
467            core::array::from_fn(|j| stage[j * CHUNK_LEN..(j + 1) * CHUNK_LEN].try_into().unwrap())
468        }));
469        let refs = refs.as_slice().as_flattened();
470        let mut counters = crate::stack_vec::StackVec::<u64, N>::new();
471        counters.extend(alike.iter().map(|&i| hashers[i].held_group().unwrap().0));
472        if on_sme2 {
473            #[cfg(target_arch = "aarch64")]
474            // Sound: the turn detects SME2. Borrowed stages and stack output
475            // are disjoint, with one counter per full 16-chunk stage.
476            unsafe {
477                crate::sme2::hash_groups_at(refs, &counters, &key, flags, CHUNK_START, CHUNK_END, level.as_flattened_mut())
478            };
479        } else {
480            for (k, &counter) in counters.iter().enumerate() {
481                platform.hash_many(
482                    &refs[k * ALONE_CHUNKS..(k + 1) * ALONE_CHUNKS],
483                    &key,
484                    counter,
485                    IncrementCounter::Yes,
486                    flags,
487                    CHUNK_START,
488                    CHUNK_END,
489                    level[k * ALONE_CHUNKS..(k + 1) * ALONE_CHUNKS].as_flattened_mut(),
490                );
491            }
492        }
493    }
494    let parent_flags = flags | PARENT;
495    let mut per = ALONE_CHUNKS;
496    while per > 1 {
497        let count = alike.len() * per / 2;
498        let bytes = level[..2 * count].as_flattened();
499        if on_sme2 {
500            // SME2's parent kernel reads a group of sixteen blocks through
501            // one pointer: the level goes to it as the run of memory it
502            // is, not as a table of sixteen borrows.
503            #[cfg(target_arch = "aarch64")]
504            // Sound: the turn's platform is SME2 only where detection
505            // found it.
506            unsafe {
507                crate::sme2::hash_block_run(bytes, &key, parent_flags, next[..count].as_flattened_mut())
508            };
509        } else {
510            // Eight parent blocks per full stage. Derive descriptor rows
511            // from that layout, including its readable final padding.
512            let (full, tail) = bytes.as_chunks::<BLOCK_LEN>().0.as_chunks::<STAGE_PARENTS>();
513            let mut rows = crate::stack_vec::StackVec::<_, N>::new();
514            rows.extend(full.iter().map(|row| row.each_ref()));
515            if let Some(first) = tail.first() {
516                rows.push(core::array::from_fn(|i| tail.get(i).unwrap_or(first)));
517            }
518            platform.hash_many(&rows.as_slice().as_flattened()[..count], &key, 0, IncrementCounter::No, parent_flags, 0, 0, next[..count].as_flattened_mut());
519        }
520        core::mem::swap(&mut level, &mut next);
521        per /= 2;
522    }
523    commit_held_groups(hashers, alike, level, next);
524}
525
526/// Messages of this many chunks or more fill the lanes alone.
527const ALONE_CHUNKS: usize = 16;
528
529/// The hash of each message, of any lengths, on the calling thread:
530/// `out[i]` is [`hash`](crate::throughput::hash)`(mode, items[i].0,
531/// items[i].1)`, each item a message of `items[i].1` bytes starting its
532/// blocks (the bytes past its end ignored). Short messages hash together,
533/// so a collection of small items (a directory's files, a repository's
534/// objects) takes less time than one call each. Requires `out.len() ==
535/// items.len()`.
536///
537/// ```
538/// # blake3_servil_core::initialize();
539/// use blake3_servil_core::{Mode, convenience, throughput::{self, Block}};
540/// let blocks: Vec<Vec<Block>> = (0..100).map(|i| vec![Block([i as u8; 64]); (100 * i as usize).div_ceil(64)]).collect();
541/// let items: Vec<(&[Block], usize)> = blocks.iter().enumerate().map(|(i, b)| (&b[..], 100 * i)).collect();
542/// let mut out = vec![[0u8; 32]; items.len()];
543/// throughput::hash_each(Mode::Plain, &items, &mut out);
544/// assert_eq!(&out[42], convenience::hash(&[42u8; 4200]).as_bytes());
545/// ```
546pub fn hash_each(mode: Mode, items: &[(&[Block], usize)], out: &mut [[u8; OUT_LEN]]) {
547    assert_eq!(items.len(), out.len(), "one digest per item");
548    let mut room = core::mem::MaybeUninit::uninit();
549    let (key, flags) = mode.key(&mut room);
550    hash_each_on(key, flags, items, out, Platform::detect(), |item| crate::hash_serial(item, key, flags));
551}
552
553/// The most items [`hash_by_blocks`] sorts at once: a stream task's
554/// members, or with SME2 its message kernel's table.
555#[cfg(target_arch = "aarch64")]
556pub(crate) const BY_BLOCKS_AT_ONCE: usize = TABLE;
557#[cfg(not(target_arch = "aarch64"))]
558pub(crate) const BY_BLOCKS_AT_ONCE: usize = 64;
559
560/// The digest of each of `items`, every one of up to a chunk, of any
561/// lengths, by their blocks: those with as many whole blocks before their
562/// last (k) side by side on the platform's hash_many, up to sixteen at a
563/// time. On NEON with SHA-3 their last blocks run in the same lanes,
564/// each with its own length (the l kernels). Other platforms hash the
565/// prefix with CHUNK_START on the first block and no end, leaving each its
566/// chaining value; then each one's last block (1 to 64 bytes, zero-padded;
567/// an empty message's is empty) compressed on its own with CHUNK_END and
568/// ROOT, CHUNK_START too where k is 0. Up to BY_BLOCKS_AT_ONCE items are
569/// sorted at once, on the stack. Requires AVX2 or AVX-512 on x86-64; NEON on AArch64.
570pub(crate) fn hash_by_blocks(items: &[&[u8]], key: &CVWords, flags: u8, out: &mut [[u8; OUT_LEN]], platform: Platform) {
571    hash_chunks_by_blocks(items, key, 0, flags, CHUNK_END | crate::ROOT, out, platform);
572}
573
574fn hash_chunks_by_blocks(items: &[&[u8]], key: &CVWords, counter: u64, flags: u8, flags_end: u8, out: &mut [[u8; OUT_LEN]], platform: Platform) {
575    assert_eq!(items.len(), out.len(), "one digest per item");
576    assert!(items.iter().all(|i| i.len() <= CHUNK_LEN), "items of up to a chunk");
577    for (items, out) in items.chunks(BY_BLOCKS_AT_ONCE).zip(out.chunks_mut(BY_BLOCKS_AT_ONCE)) {
578        by_blocks_at_once(items, key, counter, flags, flags_end, out, platform);
579    }
580}
581
582fn by_blocks_at_once(items: &[&[u8]], key: &CVWords, counter: u64, flags: u8, flags_end: u8, out: &mut [[u8; OUT_LEN]], platform: Platform) {
583    const GROUP: usize = 16;
584    const BINS: usize = 16;
585    const { assert!(BINS * crate::BLOCK_LEN == crate::CHUNK_LEN) };
586    const { assert!(BY_BLOCKS_AT_ONCE <= u8::MAX as usize) };
587    let n = items.len();
588    if n == 0 {
589        return;
590    }
591    // On SME2, a table of messages of one length, whole blocks, at counter 0,
592    // with at least the work that pays for the SME2 turn: one call of the message
593    // kernel for all of them (a turn's 1 KiB messages finishing together:
594    // the NEON lanes took 30-64% longer on an Apple M4 Max, jobs 2016 and
595    // 2019). A table of one-block messages never reaches the threshold
596    // (BY_BLOCKS_AT_ONCE of 64 bytes is under SME2_SIZED_LEN).
597    #[cfg(target_arch = "aarch64")]
598    {
599        let len = items[0].len();
600        if counter == 0
601            && matches!(platform, Platform::SME2)
602            && items.len() * len >= crate::SME2_SIZED_LEN
603            && len % crate::BLOCK_LEN == 0
604            && items.iter().all(|item| item.len() == len)
605        {
606            let turn = crate::platform::Sme2Turn::take(platform, true);
607            if matches!(turn.platform(), Platform::SME2) {
608                let mut lanes: crate::stack_vec::StackVec<*const u8, BY_BLOCKS_AT_ONCE> = items.iter().map(|item| item.as_ptr()).collect();
609                let last = *lanes.last().unwrap();
610                while lanes.len() % GROUP != 0 {
611                    lanes.push(last);
612                }
613                crate::counted(crate::Counted::ByBlocksCall);
614                // Sound: detection and the turn provide SME2. Every item has
615                // equal whole-block length `len`; spare lanes repeat a valid
616                // input pointer and write no output.
617                unsafe {
618                    crate::sme2::hash_messages_raw(&lanes, len / crate::BLOCK_LEN, key, flags, CHUNK_START, flags_end, crate::BLOCK_LEN, out.as_flattened_mut())
619                };
620                return;
621            }
622        }
623    }
624    let whole = |item: &[u8]| item.len().saturating_sub(1) / crate::BLOCK_LEN;
625    let mut order = [0u8; BY_BLOCKS_AT_ONCE];
626    if items.is_sorted_by_key(|item| whole(item)) {
627        for (slot, i) in order[..n].iter_mut().zip(0u8..) {
628            *slot = i;
629        }
630    } else {
631        let mut ends = [0u8; BINS];
632        for item in items {
633            ends[whole(item)] += 1;
634        }
635        let mut sum = 0u8;
636        for end in &mut ends {
637            sum += *end;
638            *end = sum;
639        }
640        let n_u8 = u8::try_from(n).expect("chunk <= BY_BLOCKS_AT_ONCE");
641        for i in (0..n_u8).rev() {
642            let bin = whole(items[usize::from(i)]);
643            ends[bin] -= 1;
644            order[usize::from(ends[bin])] = i;
645        }
646    }
647    let order = &order[..n];
648    // With SHA-3 the last block stays in the lanes too; other AArch64
649    // CPUs keep the prefix kernels followed by scalar last blocks.
650    #[cfg(target_arch = "aarch64")]
651    let last_lanes = crate::neon_hybrid::sha3_detected();
652    #[cfg(not(target_arch = "aarch64"))]
653    let last_lanes = false;
654    let mut cvs = [*key; BY_BLOCKS_AT_ONCE];
655    // chunk_by always advances and returns nonempty groups, even if a
656    // changed predicate groups the wrong items; no mutable loop bound.
657    for same_blocks in order.chunk_by(|&a, &b| whole(items[usize::from(a)]) == whole(items[usize::from(b)])) {
658        let k = whole(items[usize::from(same_blocks[0])]);
659        #[cfg(target_arch = "aarch64")]
660        if last_lanes {
661            for group in same_blocks.chunks(GROUP) {
662                let inputs: crate::stack_vec::StackVec<*const u8, GROUP> = group.iter().map(|&i| items[usize::from(i)].as_ptr()).collect();
663                let mut last_blocks = [[0u8; crate::BLOCK_LEN]; GROUP];
664                let mut lengths = [0u32; GROUP];
665                for ((&i, block), len) in group.iter().zip(&mut last_blocks).zip(&mut lengths) {
666                    let tail = &items[usize::from(i)][k * crate::BLOCK_LEN..];
667                    block[..tail.len()].copy_from_slice(tail);
668                    *len = u32::from(u8::try_from(tail.len()).expect("tail block <= 64"));
669                }
670                let lasts: crate::stack_vec::StackVec<*const u8, GROUP> = last_blocks[..group.len()].iter().map(|b| b.as_ptr()).collect();
671                let mut digests = [0u8; GROUP * OUT_LEN];
672                crate::counted(crate::Counted::ByBlocksCall);
673                // Sound: SHA-3 is present; these items share k whole blocks
674                // before their separately padded last block, 0 to 64 bytes.
675                unsafe {
676                    crate::neon_hybrid::hash_last_lanes(
677                        &inputs,
678                        &lasts,
679                        &lengths[..group.len()],
680                        k + 1,
681                        key,
682                        counter,
683                        flags,
684                        CHUNK_START,
685                        flags_end,
686                        &mut digests[..group.len() * OUT_LEN],
687                    );
688                }
689                for (&i, digest) in group.iter().zip(digests.chunks_exact(OUT_LEN)) {
690                    out[usize::from(i)].copy_from_slice(digest);
691                }
692            }
693            continue;
694        }
695        if k > 0 {
696            for group in same_blocks.chunks(GROUP) {
697                #[cfg_attr(not(target_arch = "x86_64"), allow(unused_mut))]
698                let mut inputs: crate::stack_vec::StackVec<*const u8, GROUP> = group.iter().map(|&i| items[usize::from(i)].as_ptr()).collect();
699                #[cfg(target_arch = "x86_64")]
700                let padded = crate::ffi_output::pad_by_blocks_inputs(&mut inputs, platform);
701                let mut lanes = [0u8; GROUP * OUT_LEN];
702                crate::counted(crate::Counted::ByBlocksCall);
703                // Sound: each item has at least `k * 64` readable prefix bytes
704                // (`k = len.saturating_sub(1) / 64`), and the caller selected
705                // this platform's block-group path.
706                #[cfg(target_arch = "x86_64")]
707                unsafe {
708                    crate::pair::hash_many_blocks(platform, &inputs, k, key, counter, false, flags, CHUNK_START, 0, &mut lanes[..padded * OUT_LEN])
709                };
710                // Sound: each item has at least `k * 64` readable prefix bytes;
711                // `inputs` holds `group.len()` readable pointers and `lanes`
712                // provides `group.len()` distinct 32-byte output slots.
713                #[cfg(target_arch = "aarch64")]
714                unsafe {
715                    crate::neon_hybrid::hash_messages_raw(
716                        inputs.as_ptr(),
717                        group.len(),
718                        k,
719                        key,
720                        counter,
721                        flags,
722                        CHUNK_START,
723                        0,
724                        crate::BLOCK_LEN,
725                        &mut lanes[..group.len() * OUT_LEN],
726                    )
727                };
728                for (n, &i) in group.iter().enumerate() {
729                    cvs[usize::from(i)] = crate::platform::words_from_le_bytes_32(lanes[n * OUT_LEN..][..OUT_LEN].try_into().unwrap());
730                }
731            }
732        }
733    }
734    if last_lanes {
735        return;
736    }
737    #[cfg(target_arch = "x86_64")]
738    let serial_start = crate::ffi_output::finish_last_blocks_order(&order, items, &cvs, counter, flags, flags_end, out, platform);
739    #[cfg(not(target_arch = "x86_64"))]
740    let serial_start = 0usize;
741    for &i in &order[serial_start..] {
742        let i = usize::from(i);
743        let item = items[i];
744        let k = whole(item);
745        let mut cv = cvs[i];
746        let mut block = [0u8; crate::BLOCK_LEN];
747        let last = item.len() - k * crate::BLOCK_LEN;
748        block[..last].copy_from_slice(&item[k * crate::BLOCK_LEN..]);
749        let start = if k == 0 { CHUNK_START } else { 0 };
750        platform.compress_in_place(&mut cv, &block, u8::try_from(last).expect("last block <= 64"), counter, flags | start | flags_end);
751        out[i] = crate::hasher::le_bytes(&cv);
752    }
753}
754
755/// An item of a collection, as hash_each_on reads it: its bytes. The
756/// public calls' items are messages in blocks; the pool's ranges, bytes.
757pub(crate) trait Item {
758    fn bytes(&self) -> &[u8];
759}
760
761impl Item for &[u8] {
762    #[inline(always)]
763    fn bytes(&self) -> &[u8] {
764        self
765    }
766}
767
768impl Item for (&[Block], usize) {
769    #[inline(always)]
770    fn bytes(&self) -> &[u8] {
771        &Block::bytes(self.0)[..self.1]
772    }
773}
774
775/// [`hash_each`] in the mode of `key` and `flags`, the lanes on
776/// `platform`, each message that fills the lanes alone (or is a chunk or
777/// less) through `alone`.
778pub(crate) fn hash_each_on<I: Item>(key: &CVWords, flags: u8, items: &[I], out: &mut [[u8; OUT_LEN]], platform: Platform, alone: impl Fn(&[u8]) -> Hash) {
779    let key = *key;
780    // Items of up to a chunk, two or more, by their blocks (hash_by_blocks).
781    #[cfg(target_arch = "x86_64")]
782    let platform_takes = crate::pair::takes_platform(platform);
783    // Every supported AArch64 platform has NEON; the kernel family
784    // selects SHA-3 or plain instructions itself.
785    #[cfg(target_arch = "aarch64")]
786    let platform_takes = true;
787    let by_blocks = platform_takes && items.iter().filter(|i| i.bytes().len() <= CHUNK_LEN).take(2).count() == 2;
788    if by_blocks {
789        // BY_BLOCKS_AT_ONCE of them at a time, their indices on the stack:
790        // a collection of small items allocates nothing and returns before
791        // borrowing SHARED or scanning items again.
792        let mut small_done = 0usize;
793        let mut small = (0..items.len()).filter(|&i| items[i].bytes().len() <= CHUNK_LEN).peekable();
794        while small.peek().is_some() {
795            let part: crate::stack_vec::StackVec<usize, BY_BLOCKS_AT_ONCE> = small.by_ref().take(BY_BLOCKS_AT_ONCE).collect();
796            small_done += part.len();
797            let bytes: crate::stack_vec::StackVec<&[u8], BY_BLOCKS_AT_ONCE> = part.iter().map(|&i| items[i].bytes()).collect();
798            let mut digests = [[0u8; OUT_LEN]; BY_BLOCKS_AT_ONCE];
799            hash_by_blocks(&bytes, &key, flags, &mut digests[..part.len()], platform);
800            for (&i, digest) in part.iter().zip(&digests) {
801                out[i] = *digest;
802            }
803        }
804        if small_done == items.len() {
805            return;
806        }
807    }
808    if items.is_empty() {
809        return;
810    }
811    // The messages of 2 to ALONE_CHUNKS - 1 chunks share the lanes, their
812    // k-th whole chunks side by side across the whole collection (the more
813    // messages a round holds, the fuller its lanes). Their places and chunk
814    // values live in this thread's storage, kept between calls (SHARED),
815    // falling back to call-local storage during thread-local teardown.
816    if SHARED
817        .try_with(|shared| {
818            let mut shared = shared.try_borrow_mut().expect("one collection at a time on a thread");
819            hash_each_middle(&mut shared, &key, flags, items, out, platform, by_blocks, platform_takes, &alone);
820        })
821        .is_err()
822    {
823        let mut local = Shared { messages: Vec::new(), cvs: Vec::new() };
824        hash_each_middle(&mut local, &key, flags, items, out, platform, by_blocks, platform_takes, &alone);
825    }
826}
827
828/// Shared-lane rounds for a nonempty collection (handles single/large items
829/// through `alone` and `2..ALONE_CHUNKS`-chunk items through `shared`).
830#[allow(clippy::too_many_arguments)]
831fn hash_each_middle<I: Item>(
832    shared: &mut Shared,
833    key: &CVWords,
834    flags: u8,
835    items: &[I],
836    out: &mut [[u8; OUT_LEN]],
837    platform: Platform,
838    by_blocks: bool,
839    platform_takes: bool,
840    alone: &impl Fn(&[u8]) -> Hash,
841) {
842    let Shared { messages, cvs } = shared;
843    messages.clear();
844    #[cfg(target_arch = "aarch64")]
845    let last_lanes = crate::neon_hybrid::sha3_detected();
846    #[cfg(not(target_arch = "aarch64"))]
847    let last_lanes = false;
848    let min_k = usize::from(!last_lanes);
849    let mut slots = 0;
850    let mut most_full = 0;
851    let mut max_chunks = 0usize;
852    let mut partial_any = [false; ALONE_CHUNKS];
853    let mut partial_seen = [0u16; ALONE_CHUNKS];
854    let mut partial_shared = [false; ALONE_CHUNKS];
855    for (i, item) in items.iter().map(Item::bytes).enumerate() {
856        let chunks = item.len().div_ceil(CHUNK_LEN);
857        if chunks <= 1 && by_blocks {
858            continue;
859        }
860        if chunks <= 1 || chunks >= ALONE_CHUNKS {
861            out[i] = *alone(item).as_bytes();
862        } else {
863            let full = item.len() / CHUNK_LEN;
864            most_full = most_full.max(full);
865            max_chunks = max_chunks.max(chunks);
866            if full != chunks {
867                partial_any[full] = true;
868                let tail = &item[full * CHUNK_LEN..];
869                let k = (tail.len() - 1) / crate::BLOCK_LEN;
870                if k >= min_k {
871                    let bit = 1u16 << k;
872                    if (partial_seen[full] & bit) != 0 {
873                        partial_shared[full] = true;
874                    }
875                    partial_seen[full] |= bit;
876                }
877            }
878            messages.push((i, slots));
879            slots += chunks;
880        }
881    }
882    if messages.is_empty() {
883        return;
884    }
885    cvs.clear();
886    cvs.resize(slots, [0u8; OUT_LEN]);
887    // Partial last chunks (1,025..=15,360 B middle messages) run before taking
888    // an SME2 turn (NEON `hash_last_lanes` and x86 `hash_many_blocks` do not
889    // use SME2, and each partial chunk writes only `cvs[at + c]`, disjoint from
890    // full chunks `cvs[at..at + c]`). Batch through `hash_chunks_by_blocks`
891    // only when at least two tails at counter `c` share a SIMD-eligible
892    // prefix-block length, avoiding sort/scatter overhead on incompatible pairs.
893    for c in 1..ALONE_CHUNKS {
894        if !partial_any[c] {
895            continue;
896        }
897        if platform_takes && partial_shared[c] {
898            let mut slices = crate::stack_vec::StackVec::<&[u8], BY_BLOCKS_AT_ONCE>::new();
899            let mut owners = crate::stack_vec::StackVec::<usize, BY_BLOCKS_AT_ONCE>::new();
900            let mut flush_partial = |slices: &mut crate::stack_vec::StackVec<&[u8], BY_BLOCKS_AT_ONCE>,
901                                     owners: &mut crate::stack_vec::StackVec<usize, BY_BLOCKS_AT_ONCE>| {
902                let mut digests = [[0u8; OUT_LEN]; BY_BLOCKS_AT_ONCE];
903                hash_chunks_by_blocks(slices, key, c as u64, flags, CHUNK_END, &mut digests[..slices.len()], platform);
904                for (&slot, digest) in owners.iter().zip(&digests) {
905                    cvs[slot] = *digest;
906                }
907                slices.clear();
908                owners.clear();
909            };
910            for &(i, at) in messages.iter() {
911                let item = items[i].bytes();
912                let full = item.len() / CHUNK_LEN;
913                if full == c && item.len() > c * CHUNK_LEN {
914                    slices.push(&item[c * CHUNK_LEN..]);
915                    owners.push(at + c);
916                    if slices.is_full() {
917                        flush_partial(&mut slices, &mut owners);
918                    }
919                }
920            }
921            if !slices.is_empty() {
922                flush_partial(&mut slices, &mut owners);
923            }
924        } else {
925            for &(i, at) in messages.iter() {
926                let item = items[i].bytes();
927                let full = item.len() / CHUNK_LEN;
928                if full == c && item.len() > c * CHUNK_LEN {
929                    cvs[at + c] = ChunkState::new(key, c as u64, flags, platform).update(&item[c * CHUNK_LEN..]).output().chaining_value();
930                }
931            }
932        }
933    }
934    // Acquire one best-effort SME2 turn across the shared full-chunk rounds and
935    // batched Merkle parent/root rounds whenever either the chunk/root rounds
936    // (`messages.len() >= 16`) or the first non-root parent round
937    // (`first_parent_pairs >= 16`) can reach an SME2 group of 16 lanes.
938    #[cfg(target_arch = "aarch64")]
939    let turn = crate::sme2::turn_for_each_middle(platform, items, messages);
940    #[cfg(target_arch = "aarch64")]
941    let round_platform = turn.platform();
942    #[cfg(not(target_arch = "aarch64"))]
943    let round_platform = platform;
944    for k in 0..most_full {
945        crate::counted(crate::Counted::EachRound);
946        // A round's lanes go to the kernels LANES_AT_ONCE at a time,
947        // their chunks and places on the stack.
948        let mut refs = crate::stack_vec::StackVec::<&[u8; CHUNK_LEN], LANES_AT_ONCE>::new();
949        let mut owners = crate::stack_vec::StackVec::<usize, LANES_AT_ONCE>::new();
950        let mut flush = |refs: &mut crate::stack_vec::StackVec<&[u8; CHUNK_LEN], LANES_AT_ONCE>,
951                         owners: &mut crate::stack_vec::StackVec<usize, LANES_AT_ONCE>| {
952            let mut lane_out = [0u8; LANES_AT_ONCE * OUT_LEN];
953            let lanes = &mut lane_out[..refs.len() * OUT_LEN];
954            round_platform.hash_many(refs, key, k as u64, IncrementCounter::No, flags, CHUNK_START, CHUNK_END, lanes);
955            for (j, &slot) in owners.iter().enumerate() {
956                cvs[slot].copy_from_slice(&lanes[j * OUT_LEN..(j + 1) * OUT_LEN]);
957            }
958            refs.clear();
959            owners.clear();
960        };
961        for &(i, at) in messages.iter() {
962            if let Some(chunk) = items[i].bytes().get(k * CHUNK_LEN..(k + 1) * CHUNK_LEN) {
963                refs.push(chunk.try_into().unwrap());
964                owners.push(at + k);
965                if refs.is_full() {
966                    flush(&mut refs, &mut owners);
967                }
968            }
969        }
970        if !refs.is_empty() {
971            flush(&mut refs, &mut owners);
972        }
973    }
974    if messages.len() == 1 {
975        let (i, at) = messages[0];
976        let chunks = items[i].bytes().len().div_ceil(CHUNK_LEN);
977        out[i] = *root(&cvs[at..at + chunks], key, flags, platform).as_bytes();
978    } else {
979        // Reduce every message's chunk CVs bottom-up in place with no pair
980        // assembly/copy in `each.rs`: left-to-right adjacent pairing never
981        // crosses BLAKE3's power-of-two left-subtree boundary, and each pair
982        // sits contiguously as a 64-byte parent block in `cvs`. For
983        // `max_chunks` in 2..=15, `parent_rounds` (0..=3) leaves every message
984        // with its 2 root-input CVs at `cvs[at..at + 2]`. After `round`
985        // reductions of `chunks` CVs, the live count is `((chunks - 1) >> round) + 1`.
986        let parent_flags = flags | crate::PARENT;
987        let parent_rounds = usize::BITS - (max_chunks - 1).leading_zeros() - 1;
988        for round in 0..parent_rounds {
989            let mut jobs = crate::stack_vec::StackVec::<(usize, usize), LANES_AT_ONCE>::new();
990            let mut flushed = false;
991            let mut flush_parents = |jobs: &mut crate::stack_vec::StackVec<(usize, usize), LANES_AT_ONCE>, cvs: &mut [CVBytes]| {
992                flushed = true;
993                let mut lane_out = [0u8; LANES_AT_ONCE * OUT_LEN];
994                {
995                    let mut refs = crate::stack_vec::StackVec::<&[u8; crate::BLOCK_LEN], LANES_AT_ONCE>::new();
996                    for &(src, _) in jobs.iter() {
997                        refs.push(cvs[src..src + 2].as_flattened().try_into().unwrap());
998                    }
999                    round_platform.hash_many(&refs, key, 0, IncrementCounter::No, parent_flags, 0, 0, &mut lane_out[..refs.len() * OUT_LEN]);
1000                }
1001                for (j, &(_, dst)) in jobs.iter().enumerate() {
1002                    cvs[dst].copy_from_slice(&lane_out[j * OUT_LEN..(j + 1) * OUT_LEN]);
1003                }
1004                jobs.clear();
1005            };
1006            for &(i, at) in messages.iter() {
1007                let chunks = items[i].bytes().len().div_ceil(CHUNK_LEN);
1008                let n = ((chunks - 1) >> round) + 1;
1009                if n <= 2 {
1010                    continue;
1011                }
1012                for j in 0..(n / 2) {
1013                    jobs.push((at + 2 * j, at + j));
1014                    if jobs.is_full() {
1015                        flush_parents(&mut jobs, cvs);
1016                    }
1017                }
1018            }
1019            if !jobs.is_empty() {
1020                flush_parents(&mut jobs, cvs);
1021            }
1022            assert!(flushed, "each scheduled parent round reduces at least one pair");
1023            for &(i, at) in messages.iter() {
1024                let chunks = items[i].bytes().len().div_ceil(CHUNK_LEN);
1025                let n = ((chunks - 1) >> round) + 1;
1026                if n <= 2 {
1027                    continue;
1028                }
1029                if (n & 1) == 1 {
1030                    let pairs = n / 2;
1031                    cvs[at + pairs] = cvs[at + 2 * pairs];
1032                }
1033            }
1034        }
1035        let root_flags = flags | crate::PARENT | crate::ROOT;
1036        for chunk in messages.chunks(LANES_AT_ONCE) {
1037            let mut refs = crate::stack_vec::StackVec::<&[u8; crate::BLOCK_LEN], LANES_AT_ONCE>::new();
1038            for &(_, at) in chunk {
1039                refs.push(cvs[at..at + 2].as_flattened().try_into().unwrap());
1040            }
1041            let mut lane_out = [0u8; LANES_AT_ONCE * OUT_LEN];
1042            round_platform.hash_many(&refs, key, 0, IncrementCounter::No, root_flags, 0, 0, &mut lane_out[..refs.len() * OUT_LEN]);
1043            for (j, &(i, _)) in chunk.iter().enumerate() {
1044                out[i].copy_from_slice(&lane_out[j * OUT_LEN..(j + 1) * OUT_LEN]);
1045            }
1046        }
1047    }
1048    #[cfg(target_arch = "aarch64")]
1049    drop(turn);
1050    messages.clear();
1051    cvs.clear();
1052}
1053
1054/// The lanes of one call to the kernels within a round of [`hash_each_on`].
1055pub(crate) const LANES_AT_ONCE: usize = TABLE;
1056
1057/// What [`hash_each_on`] keeps on a thread between calls, for a
1058/// collection's messages of 2 to ALONE_CHUNKS - 1 chunks: each one's index
1059/// and where its chunk values start (16 bytes a message), and the chunk
1060/// values (32 bytes a chunk). It grows at the thread's first such
1061/// collection and at a larger one, and a repeated collection allocates
1062/// nothing (BLAKE3 #325; each call took and freed them before).
1063struct Shared {
1064    messages: Vec<(usize, usize)>,
1065    cvs: Vec<CVBytes>,
1066}
1067
1068std::thread_local! {
1069    static SHARED: core::cell::RefCell<Shared> = const { core::cell::RefCell::new(Shared { messages: Vec::new(), cvs: Vec::new() }) };
1070}
1071
1072/// The messages and chunk values a pool thread's middle-message scratch
1073/// holds from its start: one cut range of a pooled collection is cut at
1074/// `lanes::MAX_PIECE_LEN` (128 KiB) of items, so in the worst ratio it can
1075/// take up to 127 two-chunk items of 1,025 bytes (130,175 bytes, 254 CVs)
1076/// plus one 15-chunk overshooting item (128 messages, 269 CVs). Rounding
1077/// up to 144 messages and 288 CVs keeps every pooled cut range's
1078/// middle-message scratch allocation-free on a prepared thread (separate
1079/// from caller piece scratch in `lanes` and the no-spare-pool fallback).
1080const PREPARED_MESSAGES: usize = 144;
1081const PREPARED_CVS: usize = 288;
1082
1083/// This thread's storage for the collections it hashes, made now: the
1084/// pool's threads at their start, and the thread that initializes the pool.
1085pub fn prepare_thread() {
1086    let _ = SHARED.try_with(|shared| {
1087        let mut shared = shared.borrow_mut();
1088        shared.messages.clear();
1089        shared.cvs.clear();
1090        shared.messages.reserve(PREPARED_MESSAGES);
1091        shared.cvs.reserve(PREPARED_CVS);
1092    });
1093}
1094
1095/// The root of a message of two or more chunks, from its chunk values: the
1096/// left subtree takes the largest power of two of chunks below the count.
1097fn root(cvs: &[CVBytes], key: &CVWords, flags: u8, platform: Platform) -> Hash {
1098    let split = crate::tree::left_chunks(cvs.len());
1099    let left = subtree(&cvs[..split], key, flags, platform);
1100    let right = subtree(&cvs[split..], key, flags, platform);
1101    crate::hasher::parent_output(&left, &right, key, flags, platform).root_hash()
1102}
1103
1104/// A non-root subtree's chaining value.
1105fn subtree(cvs: &[CVBytes], key: &CVWords, flags: u8, platform: Platform) -> CVBytes {
1106    if cvs.len() == 1 {
1107        return cvs[0];
1108    }
1109    let split = crate::tree::left_chunks(cvs.len());
1110    let left = subtree(&cvs[..split], key, flags, platform);
1111    let right = subtree(&cvs[split..], key, flags, platform);
1112    crate::hasher::parent_output(&left, &right, key, flags, platform).chaining_value()
1113}
1114
1115#[cfg(test)]
1116mod test {
1117    use super::*;
1118
1119    #[test]
1120    #[should_panic(expected = "only plain hashers share a cohort")]
1121    fn a_shared_cohort_refuses_a_keyed_stage() {
1122        crate::initialize();
1123        let key = [7; crate::KEY_LEN];
1124        let mut hashers = [Hasher::new(Mode::Plain, None), Hasher::new(Mode::Keyed(&key), None)];
1125        for h in &mut hashers {
1126            h.stage(&[0; crate::STAGE_LEN]);
1127        }
1128        hash_cohort::<2>(&mut hashers, &[0, 1]);
1129    }
1130
1131    /// Plain hashers always carry IV by `Domain` construction, and keyed or
1132    /// derive-key hashers beside them in the same turn never leak their keys
1133    /// into the plain cohort.
1134    #[test]
1135    fn a_plain_cohort_keeps_iv_beside_keyed_hashers() {
1136        crate::initialize();
1137        let mut input = vec![0u8; 4 * crate::STAGE_LEN];
1138        crate::test::paint_test_input(&mut input);
1139        let key = [0x5a; 32];
1140        let mut hashers = [
1141            Hasher::new(Mode::Plain, None),
1142            Hasher::new(Mode::Keyed(&key), None),
1143            Hasher::new(Mode::Plain, None),
1144            Hasher::new(Mode::DeriveKey("cohort separation"), None),
1145        ];
1146        assert_eq!(hashers[0].domain().key(), crate::IV);
1147        assert_eq!(hashers[2].domain().key(), crate::IV);
1148        for piece in input.chunks(4096) {
1149            update_each(&mut hashers, &[(0, piece), (1, piece), (2, piece), (3, piece)]);
1150        }
1151        assert_eq!(hashers[0].clone().finalize(), crate::test::official::hash(Mode::Plain, &input));
1152        assert_eq!(hashers[1].clone().finalize(), crate::test::official::hash(Mode::Keyed(&key), &input));
1153        assert_eq!(hashers[2].clone().finalize(), crate::test::official::hash(Mode::Plain, &input));
1154        assert_eq!(hashers[3].clone().finalize(), crate::test::official::hash(Mode::DeriveKey("cohort separation"), &input));
1155        // Exercise `hash_cohort` directly on a shared plain cohort as well
1156        // (independent lanes handle mixed x86 AVX2/AVX-512 turns above).
1157        let mut plain_cohort = [Hasher::new(Mode::Plain, None), Hasher::new(Mode::Plain, None)];
1158        for h in &mut plain_cohort {
1159            h.stage(&input[..crate::STAGE_LEN]);
1160        }
1161        hash_cohort::<2>(&mut plain_cohort, &[0, 1]);
1162        for h in &plain_cohort {
1163            assert_eq!(h.clone().finalize(), crate::test::official::hash(Mode::Plain, &input[..crate::STAGE_LEN]));
1164        }
1165    }
1166
1167    #[test]
1168    fn prepare_thread_reserves_collection_storage() {
1169        // nextest gives this test a fresh thread-local store.
1170        SHARED.with(|s| assert_eq!((s.borrow().messages.capacity(), s.borrow().cvs.capacity()), (0, 0)));
1171        prepare_thread();
1172        SHARED.with(|s| {
1173            let s = s.borrow();
1174            assert!(s.messages.capacity() >= PREPARED_MESSAGES);
1175            assert!(s.cvs.capacity() >= PREPARED_CVS);
1176            assert!(s.messages.is_empty() && s.cvs.is_empty());
1177        });
1178    }
1179
1180    #[cfg(target_arch = "x86_64")]
1181    #[test]
1182    fn finalize_each_groups_only_full_output_lanes() {
1183        crate::initialize();
1184        let expected = crate::test::official::hash(Mode::Plain, b"output selector");
1185        let width = crate::ffi_output::lanes(Platform::detect());
1186        for n in [0, 1, 2, 3, 4, 7, 8, 9, 15, 16, 17, 31, 32, 33] {
1187            let mut hashers: Vec<_> = (0..n)
1188                .map(|_| {
1189                    let mut h = Hasher::new(Mode::Plain, None);
1190                    h.update(b"output selector");
1191                    h
1192                })
1193                .collect();
1194            let which: Vec<_> = (0..n).collect();
1195            let mut out = vec![[0u8; OUT_LEN]; n];
1196            crate::COUNTED.with(|c| c[crate::Counted::OutputGroupTurn as usize].set(0));
1197            finalize_each(&mut hashers, &which, &mut out);
1198            let turns = crate::COUNTED.with(|c| c[crate::Counted::OutputGroupTurn as usize].get());
1199            let expected_turns = u64::from(width != 0 && n >= 4);
1200            assert_eq!(turns, expected_turns, "output group dispatch n={n}");
1201            assert!(out.iter().all(|digest| *digest == expected));
1202            assert!(hashers.iter().all(|h| h.count() == 0));
1203        }
1204        // Pin prefix_padded_count boundaries and observe real (blocks, padded)
1205        // calls at pair::hash_many_blocks plus exact output16/output8 call counts
1206        // across every platform (including count=2, 2+ groups, and AVX2 13..=15 -> 16).
1207        for (n, w, want) in [
1208            (2, 0, 2),
1209            (5, 0, 5),
1210            (4, 8, 4),
1211            (5, 8, 8),
1212            (7, 8, 8),
1213            (8, 8, 8),
1214            (12, 8, 12),
1215            (13, 8, 16),
1216            (15, 8, 16),
1217            (16, 8, 16),
1218            (4, 16, 4),
1219            (5, 16, 8),
1220            (8, 16, 8),
1221            (9, 16, 16),
1222            (15, 16, 16),
1223            (16, 16, 16),
1224        ] {
1225            assert_eq!(crate::ffi_output::prefix_padded_count(n, w), want, "prefix_padded_count({n}, {w})");
1226        }
1227        let lens = [0usize, 1, 24, 48, 63, 64, 65, 96, 128, 192, 255, 384, 512, 768, 1000, 1024];
1228        for plat in crate::test::every_platform() {
1229            let pw = crate::ffi_output::lanes(plat);
1230            // Verify actual prefix padding passed to pair::hash_many_blocks.
1231            for n in [2usize, 4, 5, 7, 8, 9, 12, 13, 15, 16] {
1232                let bufs: Vec<Vec<u8>> = (0..n).map(|i| vec![(i as u8).wrapping_mul(17); 256]).collect();
1233                let slices: Vec<&[u8]> = bufs.iter().map(Vec::as_slice).collect();
1234                let mut out = vec![[0u8; OUT_LEN]; n];
1235                crate::pair::BLOCKS_CALLS.with(|c| c.borrow_mut().clear());
1236                hash_by_blocks(&slices, crate::IV, 0, &mut out, plat);
1237                let calls = crate::pair::BLOCKS_CALLS.with(|c| c.borrow().clone());
1238                assert_eq!(calls, vec![(3, crate::ffi_output::prefix_padded_count(n, pw))], "prefix padding {plat:?} n={n}");
1239                for (i, buf) in bufs.iter().enumerate() {
1240                    assert_eq!(out[i], *blake3::hash(buf).as_bytes(), "prefix {plat:?} n={n} item {i}");
1241                }
1242            }
1243            for count in [2usize, 3, 4, 7, 8, 9, 12, 13, 15, 16, 19, 24, 33] {
1244                let bufs: Vec<Vec<u8>> = (0..count)
1245                    .map(|i| {
1246                        let len = lens[i % lens.len()];
1247                        (0..len).map(|j| ((i * 37 + j * 13 + len) & 0xff) as u8).collect()
1248                    })
1249                    .collect();
1250                let slices: Vec<&[u8]> = bufs.iter().map(Vec::as_slice).collect();
1251                let mut out = vec![[0u8; OUT_LEN]; count];
1252                crate::ffi_output::OUTPUT_CALLS.with(|c| c.borrow_mut().clear());
1253                hash_by_blocks(&slices, crate::IV, 0, &mut out, plat);
1254                let calls = crate::ffi_output::OUTPUT_CALLS.with(|c| c.borrow().clone());
1255                let mut want_calls = Vec::new();
1256                if pw > 0 {
1257                    let mut rem = count;
1258                    while rem >= 4 {
1259                        let c = rem.min(pw);
1260                        want_calls.push(if c <= 8 { 8 } else { 16 });
1261                        rem -= c;
1262                    }
1263                }
1264                assert_eq!(calls, want_calls, "hash_by_blocks output calls {plat:?} count={count}");
1265                for (i, buf) in bufs.iter().enumerate() {
1266                    assert_eq!(out[i], *blake3::hash(buf).as_bytes(), "{plat:?} count={count} item {i}");
1267                }
1268            }
1269            // Non-zero counter (partial last chunks from hash_each_middle) must
1270            // NOT enter counter-zero output16/output8 kernels.
1271            let bufs: Vec<Vec<u8>> = (0..8).map(|i| vec![i as u8; 200]).collect();
1272            let slices: Vec<&[u8]> = bufs.iter().map(Vec::as_slice).collect();
1273            let mut out = [[0u8; OUT_LEN]; 8];
1274            crate::ffi_output::OUTPUT_CALLS.with(|c| c.borrow_mut().clear());
1275            by_blocks_at_once(&slices, crate::IV, 3, 0, CHUNK_END, &mut out, plat);
1276            assert!(crate::ffi_output::OUTPUT_CALLS.with(|c| c.borrow().is_empty()), "counter != 0 skips output16/output8");
1277        }
1278
1279        // Exercise finalize_output_slots directly across every supported platform
1280        // (including SSE4.1 -> width 0 and AVX2 -> width 8 on AVX-512 hosts).
1281        for p in crate::test::every_platform() {
1282            let w = crate::ffi_output::lanes(p);
1283            for n in [2usize, 3, 4, 7, 8, 9, 15, 16, 19, 20, 24, 25, 32] {
1284                let mut hashers: Vec<_> = (0..n)
1285                    .map(|i| {
1286                        let mut h = Hasher::new(if i % 3 == 1 { Mode::Keyed(&[0x55; 32]) } else { Mode::Plain }, None);
1287                        h.update(&vec![i as u8; 32 + (i % 32)]);
1288                        h
1289                    })
1290                    .collect();
1291                let which: Vec<usize> = (0..n).collect();
1292                let slots: Vec<u8> = (0..n).map(|i| i as u8).collect();
1293                let mut out = vec![[0u8; OUT_LEN]; n];
1294                crate::ffi_output::OUTPUT_CALLS.with(|c| c.borrow_mut().clear());
1295                let done = crate::ffi_output::finalize_output_slots(&hashers, &which, &slots, &mut out, p);
1296                for &k in &slots[done..] {
1297                    let ku = usize::from(k);
1298                    out[ku] = *hashers[ku].take_root_hash().as_bytes();
1299                }
1300                let calls = crate::ffi_output::OUTPUT_CALLS.with(|c| c.borrow().clone());
1301                let mut want = Vec::new();
1302                let mut want_done = 0usize;
1303                if w > 0 {
1304                    let mut rem = n;
1305                    if w == 16 {
1306                        while rem >= 16 {
1307                            want.push(16);
1308                            rem -= 16;
1309                            want_done += 16;
1310                        }
1311                        if rem >= 9 {
1312                            want.push(16);
1313                            want_done += rem;
1314                            rem = 0;
1315                        }
1316                    }
1317                    while rem >= 8 {
1318                        want.push(8);
1319                        rem -= 8;
1320                        want_done += 8;
1321                    }
1322                    if rem >= 4 {
1323                        want.push(8);
1324                        want_done += rem;
1325                    }
1326                }
1327                assert_eq!((done, calls), (want_done, want), "finalize_output_slots w={w} n={n}");
1328                for i in 0..n {
1329                    let mode = if i % 3 == 1 { Mode::Keyed(&[0x55; 32]) } else { Mode::Plain };
1330                    assert_eq!(out[i], crate::test::official::hash(mode, &vec![i as u8; 32 + (i % 32)]), "w={w} n={n} item {i}");
1331                }
1332            }
1333        }
1334    }
1335
1336    #[test]
1337    #[should_panic(expected = "each finalized index is distinct")]
1338    fn finalize_each_rejects_repeated_indices() {
1339        crate::initialize();
1340        let mut hashers = [Hasher::new(Mode::Plain, None)];
1341        finalize_each(&mut hashers, &[0, 0], &mut [[0; OUT_LEN]; 2]);
1342    }
1343
1344    /// Every path out of a finish clears the mark: a hasher can be named
1345    /// again in the next call, and one left marked would panic there.
1346    #[test]
1347    fn finalize_each_leaves_no_hasher_marked() {
1348        crate::initialize();
1349        for n in [1, 2, 3, 15, 16, 17, 33] {
1350            for len in [0, 1, 64, 1024, 1025, 5000, 40_000] {
1351                let mut hashers: Vec<_> = (0..n).map(|k| Hasher::new(if k % 3 == 2 { Mode::Keyed(&[7; 32]) } else { Mode::Plain }, None)).collect();
1352                let which: Vec<_> = (0..n).rev().collect();
1353                let mut out = vec![[0u8; OUT_LEN]; n];
1354                for round in 0..2 {
1355                    let message = vec![round as u8; len];
1356                    let pieces: Vec<(usize, &[u8])> = (0..n).map(|i| (i, &message[..])).collect();
1357                    update_each(&mut hashers, &pieces);
1358                    finalize_each(&mut hashers, &which, &mut out);
1359                    assert!(
1360                        hashers.iter_mut().all(|h| {
1361                            let was = h.mark_finishing();
1362                            h.clear_finishing();
1363                            !was
1364                        }),
1365                        "n={n} len={len}"
1366                    );
1367                    assert_eq!(out[n - 1], *crate::convenience::hash(&message).as_bytes(), "n={n} len={len}");
1368                }
1369            }
1370        }
1371    }
1372
1373    #[test]
1374    #[should_panic(expected = "each finalized index is distinct")]
1375    fn finalize_each_rejects_repeats_across_groups() {
1376        crate::initialize();
1377        let mut hashers: Vec<_> = (0..16).map(|_| Hasher::new(Mode::Plain, None)).collect();
1378        let which: Vec<_> = (0..16).chain(0..16).collect();
1379        finalize_each(&mut hashers, &which, &mut [[0; OUT_LEN]; 32]);
1380    }
1381
1382    #[test]
1383    #[should_panic(expected = "finalize_each names hasher 9 of 2")]
1384    fn finalize_each_refuses_an_index_that_names_no_hasher() {
1385        crate::initialize();
1386        let mut hashers = [Hasher::new(Mode::Plain, None), Hasher::new(Mode::Plain, None)];
1387        finalize_each(&mut hashers, &[0, 9], &mut [[0; OUT_LEN]; 2]);
1388    }
1389
1390    /// A refused call leaves no mark: a program that catches the panic
1391    /// may name the same hashers in its next call.
1392    #[test]
1393    fn a_refused_finalize_each_leaves_no_hasher_marked() {
1394        crate::initialize();
1395        for refused in [&[0usize, 1, 0][..], &[0, 1, 9]] {
1396            let mut hashers = [Hasher::new(Mode::Plain, None), Hasher::new(Mode::Plain, None)];
1397            update_each(&mut hashers, &[(0, b"abc"), (1, b"xyz")]);
1398            let call = std::panic::catch_unwind(core::panic::AssertUnwindSafe(|| finalize_each(&mut hashers, refused, &mut [[0; OUT_LEN]; 3])));
1399            assert!(call.is_err(), "{refused:?} was accepted");
1400            assert!(
1401                hashers.iter_mut().all(|h| {
1402                    let was = h.mark_finishing();
1403                    h.clear_finishing();
1404                    !was
1405                }),
1406                "{refused:?} left a mark"
1407            );
1408            let mut out = [[0; OUT_LEN]; 2];
1409            finalize_each(&mut hashers, &[1, 0], &mut out);
1410            assert_eq!(out, [*crate::convenience::hash(b"xyz").as_bytes(), *crate::convenience::hash(b"abc").as_bytes()]);
1411        }
1412    }
1413
1414    /// A turn that panics part-way leaves no hasher holding a full stage:
1415    /// the hasher's next update has room, and its next turn ends.
1416    #[test]
1417    fn a_turn_that_unwinds_leaves_no_stage_held() {
1418        crate::initialize();
1419        let bytes: Vec<u8> = (0..2 * crate::STAGE_LEN).map(|i| (i % 251) as u8).collect();
1420        let half = crate::STAGE_LEN / 2;
1421        let then = |hashers: &mut [Hasher; 2], after: &str| {
1422            assert!(hashers[0].held_group().is_none(), "{after}: hasher 0 is left holding a full stage");
1423            // What the turn fed hasher 0 before it stopped is in: the
1424            // stage that filled, and not the byte that waited behind it.
1425            assert_eq!(hashers[0].count(), crate::STAGE_LEN as u64, "{after}");
1426            hashers[0].update(b"y");
1427            hashers[1].reset();
1428            update_each(hashers, &[(0, b"z"), (1, b"abc")]);
1429            let mut fed = bytes[..crate::STAGE_LEN].to_vec();
1430            fed.extend_from_slice(b"yz");
1431            assert_eq!(hashers[0].finalize(), crate::convenience::hash(&fed), "{after}");
1432            assert_eq!(hashers[1].finalize(), crate::convenience::hash(b"abc"), "{after}");
1433        };
1434
1435        // An index that names no hasher, after hasher 0's stage has filled.
1436        let mut hashers = [Hasher::new(Mode::Plain, None), Hasher::new(Mode::Plain, None)];
1437        let turn = [(0, &bytes[..half]), (0, &bytes[half..2 * half + 1]), (7, &bytes[..1])];
1438        let call = std::panic::catch_unwind(core::panic::AssertUnwindSafe(|| update_each(&mut hashers, &turn)));
1439        assert!(call.is_err(), "an index that names no hasher was accepted");
1440        then(&mut hashers, "an index out of range");
1441    }
1442
1443    // Expected routes are independent of the implementation's predicate:
1444    // all supported ARM platforms, AVX2 and AVX-512, but not SSE4.1.
1445    fn block_groups_expected(platform: Platform) -> bool {
1446        #[cfg(target_arch = "x86_64")]
1447        return !matches!(platform, Platform::SSE41);
1448        #[cfg(not(target_arch = "x86_64"))]
1449        {
1450            let _ = platform;
1451            true
1452        }
1453    }
1454
1455    /// A collection of small items of mixed lengths (empty to a chunk, more
1456    /// than BY_BLOCKS_AT_ONCE of them, a long one among them): those of up
1457    /// to a chunk by their blocks where the platform takes them (a
1458    /// hash_many call counted), every digest hash()'s, held to a golden
1459    /// fold.
1460    #[test]
1461    fn test_hash_each_small_items_by_blocks() {
1462        let mut golden = crate::test::Golden::new("hash_each_small_items");
1463        let mut x = 0x9e37_79b9u64;
1464        for count in [2usize, 7, 63, 64, 65, 200] {
1465            let mut lens: Vec<usize> = (0..count)
1466                .map(|_| {
1467                    x ^= x << 13;
1468                    x ^= x >> 7;
1469                    x ^= x << 17;
1470                    (x % (CHUNK_LEN as u64 + 1)) as usize
1471                })
1472                .collect();
1473            lens[count / 2] = 5 * CHUNK_LEN + 77;
1474            let data: Vec<Vec<u8>> = lens.iter().enumerate().map(|(m, &n)| (0..n).map(|i| ((m * 37 + i) % 249) as u8).collect()).collect();
1475            let items: Vec<&[u8]> = data.iter().map(|d| &d[..]).collect();
1476            let mut out = vec![[0u8; OUT_LEN]; count];
1477            for platform in crate::test::every_platform() {
1478                crate::COUNTED.with(|c| c[crate::Counted::ByBlocksCall as usize].set(0));
1479                hash_each_on(crate::IV, 0, &items, &mut out, platform, |item| crate::hash_serial(item, crate::IV, 0));
1480                let calls = crate::COUNTED.with(|c| c[crate::Counted::ByBlocksCall as usize].get());
1481                // A call where two or more items are of up to a chunk and one of
1482                // them has a whole block before its last.
1483                let small: Vec<usize> = lens.iter().copied().filter(|&n| n <= CHUNK_LEN).collect();
1484                #[cfg(target_arch = "aarch64")]
1485                let last_lanes = crate::neon_hybrid::sha3_detected();
1486                #[cfg(not(target_arch = "aarch64"))]
1487                let last_lanes = false;
1488                let calls_expected: u64 = if block_groups_expected(platform) && small.len() >= 2 {
1489                    small
1490                        .chunks(BY_BLOCKS_AT_ONCE)
1491                        .map(|part| {
1492                            let mut buckets = [0u64; 16];
1493                            for &len in part {
1494                                buckets[len.saturating_sub(1) / crate::BLOCK_LEN] += 1;
1495                            }
1496                            buckets.into_iter().enumerate().filter(|&(k, _)| last_lanes || k > 0).map(|(_, n)| n.div_ceil(16)).sum::<u64>()
1497                        })
1498                        .sum()
1499                } else {
1500                    0
1501                };
1502                assert_eq!(calls, calls_expected, "{count} items on {platform:?}: exact block-group calls");
1503                let expected: Vec<[u8; OUT_LEN]> = items.iter().map(|i| *crate::convenience::hash(i).as_bytes()).collect();
1504                assert_eq!(out, expected, "{count} items");
1505            }
1506            golden.add(out.as_flattened(), || items.iter().flat_map(|i| crate::test::official::hash(Mode::Plain, i)).collect());
1507        }
1508        golden.check(0x8fa73f9dac40c559);
1509    }
1510
1511    /// hash_each_on sends a message to `alone` exactly when it has
1512    /// ALONE_CHUNKS or more, or one chunk or fewer where the platform takes
1513    /// no items by their blocks (elsewhere two or more such go
1514    /// by their blocks), and gives the others' lanes as many rounds as the
1515    /// longest of them has whole chunks. Every other choice gives the same
1516    /// digests, so only the counts tell (BLAKE3 #219).
1517    #[test]
1518    fn test_hash_each_on_counts_its_alone_messages_and_rounds() {
1519        let input = vec![5u8; (ALONE_CHUNKS + 1) * CHUNK_LEN];
1520        let lens = [
1521            0,
1522            1,
1523            CHUNK_LEN,
1524            CHUNK_LEN + 1,
1525            2 * CHUNK_LEN,
1526            (ALONE_CHUNKS - 1) * CHUNK_LEN,
1527            (ALONE_CHUNKS - 1) * CHUNK_LEN + 1,
1528            ALONE_CHUNKS * CHUNK_LEN,
1529            ALONE_CHUNKS * CHUNK_LEN + 1,
1530        ];
1531        let items: Vec<&[u8]> = lens.iter().map(|&n| &input[..n]).collect();
1532        let alone = core::cell::RefCell::new(Vec::new());
1533        let mut out = vec![[0u8; OUT_LEN]; items.len()];
1534        crate::COUNTED.with(|c| c[crate::Counted::EachRound as usize].set(0));
1535        hash_each_on(crate::IV, 0, &items, &mut out, Platform::detect(), |item| {
1536            alone.borrow_mut().push(item.len());
1537            crate::hash_serial(item, crate::IV, 0)
1538        });
1539        let rounds = crate::COUNTED.with(|c| c[crate::Counted::EachRound as usize].get());
1540        let long = [(ALONE_CHUNKS - 1) * CHUNK_LEN + 1, ALONE_CHUNKS * CHUNK_LEN, ALONE_CHUNKS * CHUNK_LEN + 1];
1541        let expected: Vec<usize> = if block_groups_expected(Platform::detect()) { long.to_vec() } else { [0, 1, CHUNK_LEN].into_iter().chain(long).collect() };
1542        assert_eq!(alone.into_inner(), expected);
1543        // The shared: 1, 2 and ALONE_CHUNKS - 1 whole chunks.
1544        assert_eq!(rounds, (ALONE_CHUNKS - 1) as u64);
1545        for (item, out) in items.iter().zip(&out) {
1546            assert_eq!(out, crate::convenience::hash(item).as_bytes(), "{} bytes", item.len());
1547        }
1548    }
1549
1550    /// A round with more lanes than one call to the kernels takes
1551    /// (LANES_AT_ONCE) goes in several calls, and every chunk value lands
1552    /// in its message's place: 2 * LANES_AT_ONCE + 10 messages of 2 to
1553    /// ALONE_CHUNKS - 1 chunks, short and long ones between them, hashed
1554    /// twice over (the thread's storage, used again), match the one-message
1555    /// hash, in as many rounds as the longest has whole chunks.
1556    #[test]
1557    fn test_hash_each_on_takes_a_round_of_many_lanes_in_several_calls() {
1558        crate::initialize();
1559        let mut input = vec![0u8; (ALONE_CHUNKS + 1) * CHUNK_LEN];
1560        crate::test::paint_test_input(&mut input);
1561        let shared_lens = [2 * CHUNK_LEN, 3 * CHUNK_LEN + 5, CHUNK_LEN + 1, 7 * CHUNK_LEN, (ALONE_CHUNKS - 1) * CHUNK_LEN - 3];
1562        let mut lens = Vec::new();
1563        for j in 0..2 * LANES_AT_ONCE + 10 {
1564            lens.push(shared_lens[j % shared_lens.len()]);
1565            if j % 7 == 0 {
1566                lens.extend([33, ALONE_CHUNKS * CHUNK_LEN + 9]);
1567            }
1568        }
1569        let items: Vec<&[u8]> = lens.iter().map(|&n| &input[..n]).collect();
1570        for pass in 0..2 {
1571            let mut out = vec![[0xAAu8; OUT_LEN]; items.len()];
1572            crate::COUNTED.with(|c| c[crate::Counted::EachRound as usize].set(0));
1573            hash_each_on(crate::IV, 0, &items, &mut out, Platform::detect(), |item| crate::hash_serial(item, crate::IV, 0));
1574            let rounds = crate::COUNTED.with(|c| c[crate::Counted::EachRound as usize].get());
1575            assert_eq!(rounds, (ALONE_CHUNKS - 2) as u64, "the longest holds fourteen whole chunks (pass {pass})");
1576            for (item, out) in items.iter().zip(&out) {
1577                assert_eq!(out, crate::convenience::hash(item).as_bytes(), "{} bytes (pass {pass})", item.len());
1578            }
1579        }
1580    }
1581
1582    /// Turns in which several hashers hold a group each, under two keys
1583    /// whose flags agree, beyond their first group and at it (nonzero
1584    /// counters, and zero), on each platform: each held group's bytes
1585    /// land in its own hasher.
1586    #[test]
1587    fn test_update_each_holds_groups_together() {
1588        for platform in crate::test::every_platform() {
1589            holds_groups_together(platform);
1590        }
1591    }
1592
1593    fn holds_groups_together(platform: crate::platform::Platform) {
1594        let mut input = vec![0u8; 3 * crate::STAGE_LEN];
1595        crate::test::paint_test_input(&mut input);
1596        let keys = [[1u8; 32], [2u8; 32]];
1597        let on = |mut h: Hasher| {
1598            h.set_platform_for_test(platform);
1599            h
1600        };
1601        let mut hashers: Vec<Hasher> = (0..6).map(|i| on(Hasher::new(crate::Mode::Keyed(&keys[i % 2]), None))).collect();
1602        // Each hasher a group in, its message at a different offset into the
1603        // input; then one turn of two pieces each, which stage its second
1604        // group from its start and fill it (held), and 7 bytes more.
1605        let start = |i: usize| i * 1000;
1606        let group = crate::STAGE_LEN;
1607        for (i, h) in hashers.iter_mut().enumerate() {
1608            h.update(&input[start(i)..start(i) + group]);
1609        }
1610        let turn: Vec<(usize, &[u8])> = (0..6)
1611            .flat_map(|i| [(i, &input[start(i) + group..start(i) + group + 100]), (i, &input[start(i) + group + 100..start(i) + 2 * group + 7])])
1612            .collect();
1613        crate::throughput::update_each(&mut hashers, &turn);
1614        for (i, h) in hashers.iter().enumerate() {
1615            let message = &input[start(i)..start(i) + 2 * crate::STAGE_LEN + 7];
1616            assert_eq!(h.clone().finalize(), crate::convenience::hash_with(crate::Mode::Keyed(&keys[i % 2]), message), "hasher {i}, {platform:?}");
1617        }
1618        // And each hasher's first group (chunk counter zero, which hands
1619        // its core the group's two halves), six at once: a first piece
1620        // longer than a chunk, so it is staged from offset zero.
1621        let mut fresh: Vec<Hasher> = (0..6).map(|i| on(Hasher::new(crate::Mode::Keyed(&keys[i % 2]), None))).collect();
1622        let turn: Vec<(usize, &[u8])> =
1623            (0..6).flat_map(|i| [(i, &input[start(i)..start(i) + 1100]), (i, &input[start(i) + 1100..start(i) + group + 7])]).collect();
1624        crate::throughput::update_each(&mut fresh, &turn);
1625        for (i, h) in fresh.iter().enumerate() {
1626            assert_eq!(
1627                h.clone().finalize(),
1628                crate::convenience::hash_with(crate::Mode::Keyed(&keys[i % 2]), &input[start(i)..start(i) + group + 7]),
1629                "fresh hasher {i}, {platform:?}"
1630            );
1631        }
1632    }
1633
1634    /// A turn of many hashers keeps a fresh plain hasher's first chunk in its
1635    /// stage everywhere (for `finalize_each` SIMD batching), while a keyed
1636    /// hasher's first chunk goes to the core on x86-64 (for `output16`) and
1637    /// stays staged on AArch64; a single `update` stages everywhere.
1638    #[test]
1639    fn a_turn_stages_a_first_chunk_on_aarch64_and_an_update_everywhere() {
1640        crate::initialize();
1641        let bytes = [7u8; 300];
1642        let key = [0x42u8; 32];
1643        let mut hashers = vec![Hasher::new(Mode::Plain, None), Hasher::new(Mode::Plain, None), Hasher::new(Mode::Keyed(&key), None)];
1644        update_each(&mut hashers, &[(0, &bytes[..100]), (0, &bytes[100..]), (2, &bytes[..100]), (2, &bytes[100..])]);
1645        hashers[1].update(&bytes);
1646        assert_eq!((hashers[0].staged_len(), hashers[0].count() - hashers[0].staged_len() as u64), (300, 0), "a plain turn's first chunk stays staged");
1647        assert_eq!((hashers[1].staged_len(), hashers[1].count() - hashers[1].staged_len() as u64), (300, 0), "an update's first chunk waits in the stage");
1648        let keyed_in_turn = if cfg!(target_arch = "aarch64") { (300, 0) } else { (0, 300) };
1649        assert_eq!((hashers[2].staged_len(), hashers[2].count() - hashers[2].staged_len() as u64), keyed_in_turn, "a keyed turn's first chunk");
1650        assert_eq!(hashers[0].finalize(), crate::test::official::hash(Mode::Plain, &bytes));
1651        assert_eq!(hashers[1].finalize(), crate::test::official::hash(Mode::Plain, &bytes));
1652        assert_eq!(hashers[2].finalize(), crate::test::official::hash(Mode::Keyed(&key), &bytes));
1653    }
1654
1655    /// x86-64 `finalize_each` exact dispatch boundaries for staged plain full
1656    /// chunks (`== 1024 B` -> `hash_many_rounded` when `>= 2`), staged plain
1657    /// multi-block short messages (`65..=1023 B` -> `hash_by_blocks` on AVX2/AVX-512
1658    /// when `>= 4` or `>= 2` with length `> 128 B`), `<= 64 B` remaining in `rest`,
1659    /// and 128-index window boundaries.
1660    #[cfg(target_arch = "x86_64")]
1661    #[test]
1662    fn x86_finalize_each_batches_staged_plain_chunks_and_short_blocks() {
1663        crate::initialize();
1664        let run_case = |lens: &[usize]| -> (u64, u64, bool) {
1665            let data: Vec<Vec<u8>> = lens.iter().enumerate().map(|(i, &n)| (0..n).map(|j| ((i * 41 + j * 13) & 0xff) as u8).collect()).collect();
1666            let mut hashers: Vec<_> = (0..lens.len()).map(|_| Hasher::new(Mode::Plain, None)).collect();
1667            for offset in (0..1024).step_by(256) {
1668                let pieces: Vec<_> =
1669                    data.iter().enumerate().filter(|(_, d)| offset < d.len()).map(|(i, d)| (i, &d[offset..(offset + 256).min(d.len())])).collect();
1670                if !pieces.is_empty() {
1671                    update_each(&mut hashers, &pieces);
1672                }
1673            }
1674            let which: Vec<usize> = (0..lens.len()).collect();
1675            let mut out = vec![[0u8; OUT_LEN]; lens.len()];
1676            crate::COUNTED.with(|c| {
1677                c[crate::Counted::HashManyCall as usize].set(0);
1678                c[crate::Counted::ByBlocksCall as usize].set(0);
1679            });
1680            crate::ROUNDED_WIDTH.with(|w| w.set(0));
1681            finalize_each(&mut hashers, &which, &mut out);
1682            for (d, got) in data.iter().zip(&out) {
1683                assert_eq!(*got, crate::test::official::hash(Mode::Plain, d), "len={}", d.len());
1684            }
1685            assert!(hashers.iter().all(|h| h.count() == 0));
1686            let rounded = crate::ROUNDED_WIDTH.with(|w| w.get()) != 0;
1687            (
1688                crate::COUNTED.with(|c| c[crate::Counted::HashManyCall as usize].get()),
1689                crate::COUNTED.with(|c| c[crate::Counted::ByBlocksCall as usize].get()),
1690                rounded,
1691            )
1692        };
1693        let block_lanes = matches!(Platform::detect(), Platform::AVX2 | Platform::AVX512);
1694        assert_eq!(run_case(&[1024]), (0, 0, false), "1 full chunk takes scalar root");
1695        assert_eq!(run_case(&[1024, 1024]), (1, 0, false), "2 full chunks call hash_many_rounded without padding");
1696        assert_eq!(run_case(&[1024; 3]), (1, 0, true), "3 full chunks round up via hash_many_rounded");
1697        assert_eq!(run_case(&[1024; 35]), (2, 0, true), "35 full chunks split into 32 + 3");
1698        assert_eq!(run_case(&[512]), (0, 0, false), "1 short plain message skips hash_by_blocks");
1699        assert_eq!(run_case(&[64, 128]), (0, 0, false), "64 B stays in rest so single 128 B skips hash_by_blocks");
1700        assert_eq!(run_case(&[64, 64, 64, 65]), (0, 0, false), "64 B stays in rest so lone 65 B skips hash_by_blocks");
1701        assert_eq!(run_case(&[65, 65]), (0, 0, false), "pair of 1-prefix-block 65 B messages stays scalar");
1702        assert_eq!(run_case(&[128, 128]), (0, 0, false), "pair of 128 B messages stays scalar");
1703        assert_eq!(run_case(&[65; 4]), (0, u64::from(block_lanes), false), "4 x 65 B batches via hash_by_blocks");
1704        assert_eq!(run_case(&[129, 129]), (0, u64::from(block_lanes), false), "pair of 129 B (2 prefix blocks) batches");
1705        assert_eq!(run_case(&[512, 512]), (0, u64::from(block_lanes), false), "pair of 512 B batches via hash_by_blocks");
1706        assert_eq!(run_case(&[1023, 1023]), (0, u64::from(block_lanes), false), "high endpoint 1023 B batches via hash_by_blocks");
1707        assert_eq!(run_case(&[65, 129, 512, 1023]), (0, if block_lanes { 4 } else { 0 }, false), "4 distinct prefix buckets batch each bucket");
1708        assert_eq!(run_case(&[512; 65]), (0, if block_lanes { 5 } else { 0 }, false), "65 short plain messages split across BY_BLOCKS_AT_ONCE");
1709        // Straddling the 128-index window: 128 full chunks (4 x 32) + 3 rounded full chunks in window 2.
1710        assert_eq!(run_case(&[1024; 131]), (5, 0, true), "131 full chunks cross the 128-index window and round window 2");
1711        // Straddling with a singleton in window 2 (128 full + 1 full): window 2 finishes scalar.
1712        assert_eq!(run_case(&[1024; 129]), (4, 0, false), "129 full chunks finish the 129th scalar in window 2");
1713    }
1714
1715    /// Messages fed by turns and finished together match the official
1716    /// implementation at every length around a block, a chunk and a
1717    /// group, in every mode, in pieces short and long, and their hashers
1718    /// are reset: a second finish gives the empty message's hash.
1719    #[test]
1720    fn messages_fed_by_turns_finish_together_and_reset() {
1721        crate::initialize();
1722        let key = [37; 32];
1723        for n in [2, 16, 17, 64, 128, 130] {
1724            for len in [0, 1, 63, 64, 65, 255, 1023, 1024, 1025, 2048, 16385] {
1725                for width in [17, 256] {
1726                    for mode in [Mode::Plain, Mode::Keyed(&key), Mode::DeriveKey("grouped first chunk")] {
1727                        let data: Vec<Vec<u8>> = (0..n).map(|i| (0..len).map(|j| (i * 37 + j * 13) as u8).collect()).collect();
1728                        let mut hashers: Vec<_> = (0..n).map(|_| Hasher::new(mode, None)).collect();
1729                        for start in (0..len).step_by(width) {
1730                            let pieces: Vec<_> = data.iter().enumerate().map(|(i, d)| (i, &d[start..(start + width).min(len)])).collect();
1731                            update_each(&mut hashers, &pieces);
1732                        }
1733                        assert!(hashers.iter().all(|h| h.count() == len as u64));
1734                        let which: Vec<_> = (0..n).rev().collect();
1735                        let mut out = vec![[0; 32]; n];
1736                        finalize_each(&mut hashers, &which, &mut out);
1737                        for (&i, got) in which.iter().zip(&out) {
1738                            assert_eq!(*got, crate::test::official::hash(mode, &data[i]), "n={n}, len={len}, width={width}");
1739                        }
1740                        assert!(hashers.iter().all(|h| h.count() == 0));
1741                        finalize_each(&mut hashers, &which, &mut out);
1742                        assert!(out.iter().all(|got| *got == crate::test::official::hash(mode, &[])));
1743                    }
1744                }
1745            }
1746        }
1747    }
1748
1749    /// AArch64: of the hashers one finish names, the plain messages of up
1750    /// to a chunk still whole in their stages go by their blocks together,
1751    /// whatever stands between them: a keyed message, a longer one, one
1752    /// that a single `update` sent to the core. Each of those finishes
1753    /// alone, every digest lands in its own place, and every hasher is
1754    /// reset. One such message alone takes no block-group call.
1755    #[cfg(target_arch = "aarch64")]
1756    #[test]
1757    fn a_finish_takes_the_staged_first_chunks_from_among_the_others() {
1758        crate::initialize();
1759        let key = [91u8; 32];
1760        // The first and third messages (plain, in every count below) hold
1761        // whole blocks before their last, so they take a group call on a
1762        // CPU without SHA-3 too, whose shortest messages take none.
1763        let lens = [511usize, 1, 1024, 64, 65, 0, 63];
1764        for n in [3usize, 17, 128, 200] {
1765            let data: Vec<Vec<u8>> =
1766                (0..n).map(|i| (0..if i % 5 == 3 { 3000 } else { lens[i % lens.len()] }).map(|j| (i * 37 + j * 13) as u8).collect()).collect();
1767            let mode = |i: usize| if i % 5 == 1 { Mode::Keyed(&key) } else { Mode::Plain };
1768            let mut hashers: Vec<_> = (0..n).map(|i| Hasher::new(mode(i), None)).collect();
1769            for (i, d) in data.iter().enumerate() {
1770                if i % 5 == 4 {
1771                    hashers[i].update(d);
1772                }
1773            }
1774            for from in (0..3000).step_by(17) {
1775                let pieces: Vec<_> =
1776                    data.iter().enumerate().filter(|(i, _)| i % 5 != 4).map(|(i, d)| (i, &d[from.min(d.len())..(from + 17).min(d.len())])).collect();
1777                update_each(&mut hashers, &pieces);
1778            }
1779            let which: Vec<_> = (0..n).rev().collect();
1780            let mut out = vec![[0; 32]; n];
1781            crate::COUNTED.with(|c| c[crate::Counted::ByBlocksCall as usize].set(0));
1782            finalize_each(&mut hashers, &which, &mut out);
1783            for (&i, got) in which.iter().zip(&out) {
1784                assert_eq!(*got, crate::test::official::hash(mode(i), &data[i]), "n={n}, message {i}");
1785            }
1786            assert!(crate::COUNTED.with(|c| c[crate::Counted::ByBlocksCall as usize].get()) > 0, "the staged first chunks went by their blocks");
1787            assert!(hashers.iter().all(|h| h.count() == 0));
1788        }
1789        // One staged first chunk beside a long message: nothing to group.
1790        let mut hashers = vec![Hasher::new(Mode::Plain, None), Hasher::new(Mode::Plain, None)];
1791        let long = [5u8; 3000];
1792        update_each(&mut hashers, &[(0, &long[..700]), (1, &long)]);
1793        let mut out = [[0; 32]; 2];
1794        crate::COUNTED.with(|c| c[crate::Counted::ByBlocksCall as usize].set(0));
1795        finalize_each(&mut hashers, &[0, 1], &mut out);
1796        assert_eq!(out, [crate::test::official::hash(Mode::Plain, &long[..700]), crate::test::official::hash(Mode::Plain, &long)]);
1797        assert_eq!(crate::COUNTED.with(|c| c[crate::Counted::ByBlocksCall as usize].get()), 0, "one message of up to a chunk finishes alone");
1798    }
1799
1800    /// On SME2, a table of messages of one length, whole blocks, with
1801    /// SME2_SIZED_LEN of work or more, takes the message kernel in one
1802    /// call; a shorter table, or one with a message of another length,
1803    /// keeps the NEON lanes. The digests match the official implementation
1804    /// in every mode.
1805    #[cfg(target_arch = "aarch64")]
1806    #[test]
1807    fn a_sized_table_of_whole_block_messages_takes_the_sme2_message_kernel() {
1808        if !crate::platform::sme2_detected() {
1809            return;
1810        }
1811        crate::initialize();
1812        let secret = [0x9du8; crate::KEY_LEN];
1813        let entry = crate::sme2::ffi::blake3_servil_sme2_hash16_messages_512 as *const () as usize;
1814        let ran = || crate::RAN_ENTRIES.with(|r| r.borrow().contains(&entry));
1815        for mode in [Mode::Plain, Mode::Keyed(&secret), Mode::DeriveKey("a table of whole blocks")] {
1816            let mut room = core::mem::MaybeUninit::uninit();
1817            let (key, flags) = mode.key(&mut room);
1818            // Every whole-block length of up to a chunk (1..=16 blocks).
1819            for len in (64usize..=1024).step_by(64) {
1820                for count in [1usize, 15, 16, 17, 31, 32, 63, 64, 127, 128] {
1821                    let data: Vec<Vec<u8>> = (0..count).map(|i| (0..len).map(|j| (i * 37 + j * 11) as u8).collect()).collect();
1822                    let items: Vec<&[u8]> = data.iter().map(|d| &d[..]).collect();
1823                    let expected: Vec<_> = items.iter().map(|i| crate::test::official::hash(mode, i)).collect();
1824                    let mut out = vec![[0u8; OUT_LEN]; count];
1825                    crate::RAN_ENTRIES.with(|r| r.borrow_mut().clear());
1826                    hash_by_blocks(&items, key, flags, &mut out, Platform::SME2);
1827                    assert_eq!(out, expected, "{count} x {len}");
1828                    assert_eq!(ran(), count * len >= crate::SME2_SIZED_LEN, "the message kernel at {count} x {len}");
1829                }
1830            }
1831            // One message a byte short: the table is no longer of one length.
1832            let mut data: Vec<Vec<u8>> = (0..128).map(|i| (0..1024).map(|j| (i * 37 + j * 11) as u8).collect()).collect();
1833            data[1].pop();
1834            let items: Vec<&[u8]> = data.iter().map(|d| &d[..]).collect();
1835            let expected: Vec<_> = items.iter().map(|i| crate::test::official::hash(mode, i)).collect();
1836            let mut out = vec![[0u8; OUT_LEN]; 128];
1837            crate::RAN_ENTRIES.with(|r| r.borrow_mut().clear());
1838            hash_by_blocks(&items, key, flags, &mut out, Platform::SME2);
1839            assert_eq!(out, expected);
1840            assert!(!ran(), "the message kernel takes messages of one length");
1841        }
1842    }
1843
1844    /// A piece that outlasts its hasher's stage waits for the turn's flush
1845    /// instead of forcing one: 256 plain hashers, each holding part of a
1846    /// chunk, each given a 16 KiB piece in caller order (the benchmark's
1847    /// interleaved cell), fill 256 stages that hash in two full passes of
1848    /// the table, with the rest of each piece gathered after. A flush at
1849    /// each outlasting piece would take a pass per hasher. The digests
1850    /// agree with the official implementation.
1851    #[test]
1852    fn outlasting_pieces_wait_for_a_full_table() {
1853        crate::initialize();
1854        const N: usize = 256;
1855        let mut input = vec![0u8; 1448 + crate::STAGE_LEN];
1856        crate::test::paint_test_input(&mut input);
1857        let mut hashers: Vec<Hasher> = (0..N).map(|_| Hasher::new(Mode::Plain, None)).collect();
1858        let first: Vec<(usize, &[u8])> = (0..N).map(|i| (i, &input[..1448])).collect();
1859        update_each(&mut hashers, &first);
1860        let second: Vec<(usize, &[u8])> = (0..N).map(|i| (i, &input[1448..])).collect();
1861        crate::COUNTED.with(|c| c[crate::Counted::HeldPass as usize].set(0));
1862        update_each(&mut hashers, &second);
1863        let passes = crate::COUNTED.with(|c| c[crate::Counted::HeldPass as usize].get());
1864        assert_eq!(passes, (N / TABLE) as u64, "every stage hashed in full passes of the table");
1865        for h in &hashers {
1866            assert_eq!(h.clone().finalize(), crate::test::official::hash(Mode::Plain, &input));
1867        }
1868        // Two pieces of one hasher in one turn apply in order: the second
1869        // waits while the first's rest does.
1870        let mut pair = vec![Hasher::new(Mode::Plain, None), Hasher::new(Mode::Plain, None)];
1871        let (a, b) = input.split_at(crate::STAGE_LEN + 100);
1872        update_each(&mut pair, &[(0, a), (1, &input[..7]), (0, b), (1, &input[7..])]);
1873        assert_eq!(pair[0].clone().finalize(), crate::test::official::hash(Mode::Plain, &input));
1874        assert_eq!(pair[1].clone().finalize(), crate::test::official::hash(Mode::Plain, &input));
1875    }
1876
1877    /// Public mode and independent-parent availability choose the held
1878    /// passes; equal and distinct secret keys always take the same work.
1879    #[test]
1880    fn held_groups_pass_by_mode_not_key() {
1881        crate::initialize();
1882        let mut input = vec![0u8; crate::STAGE_LEN];
1883        crate::test::paint_test_input(&mut input);
1884        let (a, b, c) = ([1u8; 32], [2u8; 32], [3u8; 32]);
1885        let passes = |modes: &[Mode]| {
1886            let mut hashers: Vec<Hasher> = modes.iter().map(|&m| Hasher::new(m, None)).collect();
1887            // Pieces shorter than a group, so each hasher's group fills in
1888            // its stage and is held for the turn.
1889            let pieces: Vec<(usize, &[u8])> = input.chunks(4096).flat_map(|piece| (0..modes.len()).map(move |i| (i, piece))).collect();
1890            crate::COUNTED.with(|c| c[crate::Counted::HeldPass as usize].set(0));
1891            update_each(&mut hashers, &pieces);
1892            let passes = crate::COUNTED.with(|c| c[crate::Counted::HeldPass as usize].get());
1893            for (h, &m) in hashers.iter().zip(modes) {
1894                assert_eq!(h.clone().finalize(), crate::test::official::hash(m, &input));
1895            }
1896            passes
1897        };
1898        let independent = crate::ffi_output::lanes(Platform::detect()) != 0;
1899        assert_eq!(passes(&[Mode::Plain; 3]), 1, "plain hashers hash together");
1900        assert_eq!(passes(&[Mode::Plain, Mode::Keyed(&a), Mode::Plain]), if independent { 1 } else { 2 }, "public mixed-mode route");
1901        let same = passes(&[Mode::Keyed(&a); 3]);
1902        assert_eq!(same, passes(&[Mode::Keyed(&a), Mode::Keyed(&b), Mode::Keyed(&c)]), "equal keys take the passes distinct keys take");
1903        assert_eq!(same, if independent { 1 } else { 3 });
1904        // Two held hashers stay below the lanes' count: each keyed one alone.
1905        assert_eq!(passes(&[Mode::Keyed(&a), Mode::Keyed(&b)]), 2, "a pair of keyed hashers, on either route");
1906        assert_eq!(passes(&[Mode::Keyed(&a); 2]), 2, "equal keys take the same two passes");
1907        let derived = passes(&[Mode::DeriveKey("shared context"); 3]);
1908        assert_eq!(derived, passes(&[Mode::DeriveKey("context a"), Mode::DeriveKey("context b"), Mode::DeriveKey("context c")]));
1909        assert_eq!(derived, if independent { 1 } else { 3 }, "derived-key equality stays private");
1910        // Public routing and the ready-table bound fix the pass count.
1911        let bounded = 600usize.div_ceil(TABLE) as u64;
1912        assert_eq!(passes(&[Mode::Keyed(&a); 600]), if independent { bounded } else { 600 }, "600 keyed hashers, bounded public route");
1913        assert_eq!(passes(&[Mode::Plain; 600]), bounded, "600 plain hashers, bounded passes");
1914    }
1915
1916    /// Parent rows cross messages and the ready-table boundary. Distinct
1917    /// input bytes make a pointer borrowed from the wrong message visible.
1918    #[test]
1919    fn held_workspace_preserves_distinct_message_rows() {
1920        crate::initialize();
1921        for n in [2usize, 15, 16, 17, 31, 32, 33, 127, 128, 129, 257] {
1922            let count = n.min(TABLE);
1923            let mut workspace = HeldWorkspace::<TABLE>::new();
1924            let (level, next) = workspace.buffers(count);
1925            assert_eq!((level.len(), next.len()), (16 * count, 8 * count), "workspace CV capacities");
1926            let inputs: Vec<Vec<u8>> =
1927                (0..n).map(|i| (0..2 * crate::STAGE_LEN + i % 71).map(|j| ((i * 37 + j * 17 + (j >> 8)) % 251) as u8).collect()).collect();
1928            let keys: Vec<[u8; 32]> = (0..n).map(|i| core::array::from_fn(|j| (i * 37 + j * 11) as u8)).collect();
1929            for flavor in 0..4 {
1930                let mode = |i: usize| match flavor {
1931                    0 => Mode::Plain,
1932                    1 => Mode::Keyed(&keys[0]),
1933                    2 => Mode::Keyed(&keys[i]),
1934                    _ => match i % 3 {
1935                        0 => Mode::Plain,
1936                        1 => Mode::Keyed(&keys[i]),
1937                        _ => Mode::DeriveKey("distinct held rows"),
1938                    },
1939                };
1940                let mut hashers: Vec<_> = (0..n).map(|i| Hasher::new(mode(i), None)).collect();
1941                let mut pieces = Vec::with_capacity(n);
1942                for start in (0..2 * crate::STAGE_LEN).step_by(4096) {
1943                    pieces.clear();
1944                    pieces.extend(inputs.iter().enumerate().map(|(i, b)| (i, &b[start..start + 4096])));
1945                    update_each(&mut hashers, &pieces);
1946                    assert!(hashers.iter().all(|h| h.held_group().is_none()), "each turn completes its held stages");
1947                }
1948                for (i, (h, input)) in hashers.iter_mut().zip(&inputs).enumerate() {
1949                    h.update(&input[2 * crate::STAGE_LEN..]);
1950                    assert_eq!(h.clone().finalize(), crate::test::official::hash(mode(i), input), "n={n} flavor={flavor} row={i}");
1951                }
1952            }
1953        }
1954    }
1955
1956    /// With public shape fixed, changing key equality or the number of
1957    /// matching leading words changes neither cohorts nor kernel entries.
1958    /// This checks dispatch, not instruction-level constant-time execution.
1959    #[test]
1960    fn held_dispatch_ignores_key_equality_and_prefixes() {
1961        crate::initialize();
1962        let input = vec![42u8; 2 * crate::STAGE_LEN];
1963        for platform in crate::test::every_platform() {
1964            for n in [3usize, 8, 16, 17, 33] {
1965                for mixed in [false, true] {
1966                    let mut reference = None;
1967                    // Eight words means identical keys. Otherwise exactly
1968                    // `prefix` leading words match between every pair.
1969                    for prefix in (0..=8).rev() {
1970                        let keys: Vec<[u8; 32]> = (0..n)
1971                            .map(|i| {
1972                                let mut key = [0x6du8; 32];
1973                                if prefix < 8 {
1974                                    key[4 * prefix..4 * prefix + 4].copy_from_slice(&(i as u32 + 1).to_le_bytes());
1975                                }
1976                                key
1977                            })
1978                            .collect();
1979                        let mode = |i: usize| {
1980                            if !mixed || i % 3 == 1 {
1981                                Mode::Keyed(&keys[i])
1982                            } else if i % 3 == 0 {
1983                                Mode::Plain
1984                            } else {
1985                                Mode::DeriveKey("held key-prefix regression")
1986                            }
1987                        };
1988                        let mut hashers: Vec<_> = (0..n)
1989                            .map(|i| {
1990                                let mut h = Hasher::new(mode(i), None);
1991                                h.set_platform_for_test(platform);
1992                                h
1993                            })
1994                            .collect();
1995                        HELD_GROUPS.with(|g| g.borrow_mut().clear());
1996                        crate::RAN_ENTRIES.with(|e| e.borrow_mut().clear());
1997                        crate::COUNTED.with(|c| c[crate::Counted::HeldPass as usize].set(0));
1998                        for piece in input.chunks(4096) {
1999                            let pieces: Vec<_> = (0..n).map(|i| (i, piece)).collect();
2000                            update_each(&mut hashers, &pieces);
2001                        }
2002                        // Capture before finalization and the official oracle.
2003                        let groups = HELD_GROUPS.with(|g| g.borrow().clone());
2004                        let entries = crate::RAN_ENTRIES.with(|e| e.borrow().clone());
2005                        let passes = crate::COUNTED.with(|c| c[crate::Counted::HeldPass as usize].get());
2006                        assert_eq!(groups.iter().map(Vec::len).sum::<usize>(), 2 * n, "both held stages observed");
2007                        let work = (groups, entries, passes);
2008                        if let Some(expected) = &reference {
2009                            assert_eq!(
2010                                &work, expected,
2011                                "dispatch work independent of key equality and prefix: {platform:?} n={n} mixed={mixed} prefix={prefix}"
2012                            );
2013                        } else {
2014                            reference = Some(work);
2015                        }
2016                        for (i, h) in hashers.iter().enumerate() {
2017                            assert_eq!(h.clone().finalize(), crate::test::official::hash(mode(i), &input));
2018                        }
2019                    }
2020                }
2021            }
2022        }
2023    }
2024
2025    /// Keyed and mixed-mode turns use independent parent lanes; plain
2026    /// turns share the fixed IV. Key values never select a different route.
2027    #[test]
2028    fn test_held_key_groups_take_one_partition_pass() {
2029        let entry = |width| if width == 8 { crate::ffi_output::entry8() } else { crate::ffi_output::entry() };
2030        for platform in crate::test::every_platform() {
2031            let width = crate::ffi_output::lanes(platform);
2032            if width == 0 {
2033                continue;
2034            }
2035            for n in [2usize, 7, 8, 9, 15, 16, 17, 31, 32, 33] {
2036                for flavor in 0..4 {
2037                    let keys: Vec<[u8; 32]> = (0..n).map(|i| core::array::from_fn(|j| (i * 37 + j * 11) as u8)).collect();
2038                    let modes: Vec<Mode<'_>> = (0..n)
2039                        .map(|i| match flavor {
2040                            0 => Mode::Plain,
2041                            1 => Mode::Keyed(&keys[0]),
2042                            2 => Mode::Keyed(&keys[i]),
2043                            _ => match i % 3 {
2044                                0 => Mode::Plain,
2045                                1 => Mode::Keyed(&keys[i]),
2046                                _ => Mode::DeriveKey("held parent lanes"),
2047                            },
2048                        })
2049                        .collect();
2050                    let offsets: Vec<_> = (0..n).map(|i| (i % 3) * crate::STAGE_LEN).collect();
2051                    let data: Vec<Vec<u8>> =
2052                        (0..n).map(|i| (0..offsets[i] + crate::STAGE_LEN + 97).map(|j| ((i * 37 + j * 17) % 251) as u8).collect()).collect();
2053                    let mut hashers: Vec<_> = (0..n)
2054                        .map(|i| {
2055                            let mut h = Hasher::new(modes[i], None);
2056                            h.set_platform_for_test(platform);
2057                            h.update(&data[i][..offsets[i]]);
2058                            h
2059                        })
2060                        .collect();
2061                    crate::COUNTED.with(|c| c[crate::Counted::HeldPass as usize].set(0));
2062                    crate::RAN_ENTRIES.with(|r| r.borrow_mut().clear());
2063                    for start in (0..crate::STAGE_LEN).step_by(4096) {
2064                        let pieces: Vec<_> = (0..n).map(|i| (i, &data[i][offsets[i] + start..offsets[i] + start + 4096])).collect();
2065                        update_each(&mut hashers, &pieces);
2066                    }
2067                    let parent_entries = crate::RAN_ENTRIES.with(|r| r.borrow().clone());
2068                    for i in 0..n {
2069                        let end = offsets[i] + crate::STAGE_LEN;
2070                        assert_eq!(hashers[i].staged_len(), 0);
2071                        assert_eq!(hashers[i].count(), end as u64);
2072                        assert_eq!(
2073                            *hashers[i].clone().finalize().as_bytes(),
2074                            crate::test::official::hash(modes[i], &data[i][..end]),
2075                            "{platform:?} n={n} lane={i} flavor={flavor}"
2076                        );
2077                        hashers[i].update(&data[i][end..]);
2078                        assert_eq!(*hashers[i].clone().finalize().as_bytes(), crate::test::official::hash(modes[i], &data[i]));
2079                        let mut reader = hashers[i].clone().finalize_xof();
2080                        reader.set_position(13);
2081                        let mut out = [0u8; 129];
2082                        reader.fill(&mut out);
2083                        assert_eq!(out.as_slice(), crate::test::official::xof(modes[i], &data[i], 13, out.len()));
2084                    }
2085                    let partitions = crate::COUNTED.with(|c| c[crate::Counted::HeldPass as usize].get());
2086                    // Below INDEPENDENT_MIN a keyed hasher hashes alone, and the plain ones together.
2087                    let lanes = flavor != 0 && n >= INDEPENDENT_MIN;
2088                    assert_eq!(partitions, if flavor != 0 && !lanes { n as u64 } else { 1 }, "held partitions: {platform:?} n={n} flavor={flavor}");
2089                    #[cfg(target_arch = "x86_64")]
2090                    {
2091                        assert_eq!(parent_entries.contains(&(entry(width) as usize)), lanes, "independent parent entry: {platform:?} n={n}");
2092                        if lanes && platform == crate::platform::Platform::AVX512 && crate::platform::avx2_detected() {
2093                            let eight_needed = (1..=4).any(|shift| ((n * (crate::STAGE_LEN / crate::CHUNK_LEN)) >> shift) % 16 >= 8);
2094                            assert_eq!(
2095                                parent_entries.contains(&(entry(8) as usize)),
2096                                eight_needed,
2097                                "eight-wide parent remainder: {platform:?} n={n} flavor={flavor}"
2098                            );
2099                        }
2100                    }
2101                    #[cfg(target_arch = "aarch64")]
2102                    {
2103                        if matches!(platform, crate::platform::Platform::SME2) {
2104                            assert_eq!(
2105                                parent_entries.contains(&(crate::ffi_output::entry_chunks_keyed() as usize)),
2106                                lanes,
2107                                "SME2 chunks_keyed entry: n={n} flavor={flavor}"
2108                            );
2109                        }
2110                        assert_eq!(parent_entries.contains(&(entry(8) as usize)), lanes, "NEON output8 parent entry: {platform:?} n={n} flavor={flavor}");
2111                    }
2112                }
2113            }
2114        }
2115    }
2116
2117    /// Large same-key and distinct-key turns take the same passes. A
2118    /// platform without independent parent lanes uses public-mode cohorts.
2119    #[test]
2120    fn held_passes_do_not_depend_on_keys() {
2121        crate::initialize();
2122        let input = vec![42u8; crate::STAGE_LEN];
2123        let keys: Vec<[u8; 32]> = (0..600u64)
2124            .map(|i| {
2125                let mut key = [7u8; 32];
2126                key[..8].copy_from_slice(&i.to_le_bytes());
2127                key
2128            })
2129            .collect();
2130        for platform in crate::test::every_platform() {
2131            let independent = crate::ffi_output::lanes(platform) != 0;
2132            for n in [3, 600] {
2133                for flavor in 0..3 {
2134                    let mode = |i| match flavor {
2135                        0 => Mode::Plain,
2136                        1 => Mode::Keyed(&keys[0]),
2137                        _ => Mode::Keyed(&keys[i]),
2138                    };
2139                    let mut hashers: Vec<_> = (0..n)
2140                        .map(|i| {
2141                            let mut h = Hasher::new(mode(i), None);
2142                            h.set_platform_for_test(platform);
2143                            h
2144                        })
2145                        .collect();
2146                    crate::COUNTED.with(|c| c[crate::Counted::HeldPass as usize].set(0));
2147                    for piece in input.chunks(4096) {
2148                        let pieces: Vec<_> = (0..n).map(|i| (i, piece)).collect();
2149                        update_each(&mut hashers, &pieces);
2150                    }
2151                    let passes = crate::COUNTED.with(|c| c[crate::Counted::HeldPass as usize].get());
2152                    assert_eq!(
2153                        passes,
2154                        if independent || flavor == 0 { n.div_ceil(TABLE) as u64 } else { n as u64 },
2155                        "key-independent passes: {platform:?} n={n} flavor={flavor}"
2156                    );
2157                    for (i, h) in hashers.iter().enumerate() {
2158                        assert_eq!(h.clone().finalize(), crate::test::official::hash(mode(i), &input));
2159                    }
2160                }
2161            }
2162        }
2163    }
2164
2165    #[test]
2166    fn test_update_each() {
2167        let mut input = vec![0u8; 1 << 20];
2168        crate::test::paint_test_input(&mut input);
2169        let lens = [0, 1, 63, 64, 1023, 1024, 1025, 2048, 4470, 8191, 16384, 16385, 65536, 100_000, 300_000];
2170        let piece_lens = [1, 1448, 4096, 1448, 16384, 31, 65536];
2171        let key = [5u8; 32];
2172        // Every third hasher keyed: a turn's held groups in two kinds.
2173        let mut hashers: Vec<Hasher> =
2174            (0..lens.len()).map(|i| if i % 3 == 1 { Hasher::new(crate::Mode::Keyed(&key), None) } else { Hasher::new(crate::Mode::Plain, None) }).collect();
2175        let mut done = vec![0usize; lens.len()];
2176        let mut k = 0;
2177        while done.iter().zip(&lens).any(|(d, l)| d < l) {
2178            let mut pieces: Vec<(usize, &[u8])> = Vec::new();
2179            for _ in 0..23 {
2180                let i = k % lens.len();
2181                let n = piece_lens[k % piece_lens.len()].min(lens[i] - done[i]);
2182                pieces.push((i, &input[done[i]..done[i] + n]));
2183                done[i] += n;
2184                k += 1;
2185            }
2186            crate::throughput::update_each(&mut hashers, &pieces);
2187        }
2188        let which: Vec<usize> = (0..lens.len()).rev().collect();
2189        let mut out = vec![[0u8; OUT_LEN]; lens.len()];
2190        crate::throughput::finalize_each(&mut hashers, &which, &mut out);
2191        for (k, &i) in which.iter().enumerate() {
2192            let want = if i % 3 == 1 {
2193                crate::convenience::hash_with(crate::Mode::Keyed(&key), &input[..lens[i]])
2194            } else {
2195                crate::convenience::hash(&input[..lens[i]])
2196            };
2197            assert_eq!(&out[k], want.as_bytes(), "len {}", lens[i]);
2198        }
2199    }
2200
2201    /// Every length around chunk and lane boundaries, in every mode, mixed in
2202    /// one call, against `hash_with` on each.
2203    /// Keep: it detects, by hanging, mutants the clock then stops
2204    /// (tools/mutants/timeouts-x86_64.txt).
2205    #[test]
2206    fn test_hash_each_matches_hash_with() {
2207        let mut input = vec![0u8; 40 * CHUNK_LEN];
2208        crate::test::paint_test_input(&mut input);
2209        let mut lens = vec![
2210            0,
2211            1,
2212            63,
2213            64,
2214            65,
2215            1023,
2216            1024,
2217            1025,
2218            2047,
2219            2048,
2220            2049,
2221            3000,
2222            4096,
2223            5000,
2224            15 * CHUNK_LEN,
2225            15 * CHUNK_LEN + 1,
2226            16 * CHUNK_LEN - 1,
2227            16 * CHUNK_LEN,
2228            16 * CHUNK_LEN + 1,
2229            40 * CHUNK_LEN,
2230        ];
2231        for n in 2..16 {
2232            lens.push(n * CHUNK_LEN);
2233            lens.push(n * CHUNK_LEN - 7);
2234        }
2235        let items: Vec<&[u8]> = lens.iter().enumerate().map(|(j, &l)| &input[j % 3..j % 3 + l.min(input.len() - 2)]).collect();
2236        let key = [9u8; 32];
2237        for mode in [Mode::Plain, Mode::Keyed(&key), Mode::DeriveKey("hash_each test")] {
2238            let mut out = vec![[0u8; OUT_LEN]; items.len()];
2239            crate::throughput::hash_each(mode, &crate::test::items(&crate::test::messages(&items), &items), &mut out);
2240            for (item, digest) in items.iter().zip(&out) {
2241                assert_eq!(digest, crate::convenience::hash_with(mode, item).as_bytes(), "length {}", item.len());
2242            }
2243        }
2244    }
2245
2246    /// Calling `hash_each` (and `prepare_thread`) from an earlier-initialized
2247    /// thread-local destructor after `SHARED` has already been destroyed must
2248    /// not panic and must produce exact digests for both empty and multi-chunk
2249    /// collections.
2250    #[test]
2251    fn hash_each_works_during_thread_local_teardown() {
2252        use std::sync::Arc;
2253        use std::sync::atomic::{AtomicBool, Ordering};
2254        crate::initialize();
2255        let ran = Arc::new(AtomicBool::new(false));
2256        let ok = Arc::new(AtomicBool::new(false));
2257        struct OnExit {
2258            ran: Arc<AtomicBool>,
2259            ok: Arc<AtomicBool>,
2260        }
2261        impl Drop for OnExit {
2262            fn drop(&mut self) {
2263                self.ran.store(true, Ordering::SeqCst);
2264                let tree = crate::throughput::TreeHasher::new(Mode::Plain);
2265                // Empty collection during teardown.
2266                let mut empty: [[u8; OUT_LEN]; 0] = [];
2267                tree.hash_each(&[], &mut empty);
2268                // Middle-sized multi-chunk collection during teardown (forces
2269                // the `SHARED.try_with` fallback once `SHARED` is destroyed).
2270                let msg_a = [0x11u8; 2 * CHUNK_LEN + 7];
2271                let msg_b = [0x22u8; 3 * CHUNK_LEN + 13];
2272                let slices = [&msg_a[..], &msg_b[..]];
2273                let blocks = crate::test::messages(&slices);
2274                let items = crate::test::items(&blocks, &slices);
2275                let mut out = [[0u8; OUT_LEN]; 2];
2276                prepare_thread();
2277                tree.hash_each(&items, &mut out);
2278                let matched = out[0] == *blake3::hash(&msg_a).as_bytes() && out[1] == *blake3::hash(&msg_b).as_bytes();
2279                self.ok.store(matched, Ordering::SeqCst);
2280            }
2281        }
2282        std::thread_local! {
2283            static EARLIER: core::cell::RefCell<Option<OnExit>> = const { core::cell::RefCell::new(None) };
2284        }
2285        let ran_c = Arc::clone(&ran);
2286        let ok_c = Arc::clone(&ok);
2287        std::thread::spawn(move || {
2288            // Initialize EARLIER first so LIFO TLS teardown destroys SHARED
2289            // before EARLIER's Drop runs.
2290            EARLIER.with(|slot| *slot.borrow_mut() = Some(OnExit { ran: ran_c, ok: ok_c }));
2291            // Now initialize SHARED via a middle-sized hash_each call.
2292            let msg = [0x33u8; 2 * CHUNK_LEN];
2293            let slices = [&msg[..]];
2294            let blocks = crate::test::messages(&slices);
2295            let items = crate::test::items(&blocks, &slices);
2296            let mut out = [[0u8; OUT_LEN]; 1];
2297            crate::throughput::hash_each(Mode::Plain, &items, &mut out);
2298            assert_eq!(out[0], *blake3::hash(&msg).as_bytes());
2299        })
2300        .join()
2301        .expect("thread teardown with hash_each must not panic");
2302        assert!(ran.load(Ordering::SeqCst), "TLS destructor must have run");
2303        assert!(ok.load(Ordering::SeqCst), "TLS destructor digests must match");
2304    }
2305
2306    /// `hash_held` picks the smallest `hash_cohort_on::<N>` workspace tier (1
2307    /// for a singleton, 16-stage L1D-hot tiles for 2..=128) for plain cohorts
2308    /// across every `std` platform.
2309    #[test]
2310    fn hash_held_selects_smallest_cohort_tier() {
2311        crate::initialize();
2312        let data = std::vec![0x42u8; crate::STAGE_LEN + 17];
2313        let expected = *blake3::hash(&data).as_bytes();
2314        for (count, expected_tier) in [(1usize, 1usize), (2, 16), (16, 16), (17, 16), (33, 16)] {
2315            let mut hashers: std::vec::Vec<Hasher> = (0..count).map(|_| Hasher::new(Mode::Plain, None)).collect();
2316            LAST_COHORT_TIER.with(|t| t.set(0));
2317            for piece in data.chunks(4096) {
2318                let pieces: std::vec::Vec<(usize, &[u8])> = (0..count).map(|i| (i, piece)).collect();
2319                update_each(&mut hashers[..], &pieces);
2320            }
2321            assert_eq!(LAST_COHORT_TIER.with(|t| t.get()), expected_tier, "count={count}");
2322            assert_eq!(*hashers[0].finalize().as_bytes(), expected);
2323        }
2324    }
2325
2326    /// Feeding plain (including 17 and 33 hashers fed sixteen 1 KiB pieces plus
2327    /// a 97 B tail) or mixed keyed+plain (3, 16, 17, and 33 hashers fed four
2328    /// 4 KiB pieces plus a 97 B tail so index 0 holds a full stage and enters
2329    /// `held_groups` on AVX2/AVX-512; macOS uses a 4-stage tier for 3 mixed
2330    /// hashers and tiles larger turns by 16) cohorts of `Vec<Hasher>` through
2331    /// a 16 KiB stage in `update_each` uses bounded workspaces (~1.5–15 KiB)
2332    /// rather than a ~99 KiB 128-stage frame, so all succeed on a 64 KiB
2333    /// worker thread stack.
2334    #[cfg(any(target_arch = "x86_64", target_os = "macos"))]
2335    #[test]
2336    fn small_held_cohorts_fit_in_64kib_stack() {
2337        crate::initialize();
2338        let data = std::vec![0x42u8; crate::STAGE_LEN + 97];
2339        let expected_plain = *blake3::hash(&data).as_bytes();
2340        let key = [0x5Au8; 32];
2341        let expected_keyed = *blake3::keyed_hash(&key, &data).as_bytes();
2342        for (count, keyed_first, piece_len) in [
2343            (1usize, false, 4096usize),
2344            (2, false, 4096),
2345            (3, true, 4096),
2346            (16, true, 4096),
2347            (17, false, 1024),
2348            (17, true, 4096),
2349            (33, false, 1024),
2350            (33, true, 4096),
2351        ] {
2352            let data_c = data.clone();
2353            let mut hashers: std::vec::Vec<Hasher> =
2354                (0..count).map(|i| if keyed_first && i == 0 { Hasher::new(Mode::Keyed(&key), None) } else { Hasher::new(Mode::Plain, None) }).collect();
2355            let (first, last, saw_independent) = std::thread::Builder::new()
2356                .stack_size(64 * 1024)
2357                .spawn(move || {
2358                    HELD_GROUPS.with(|g| g.borrow_mut().clear());
2359                    for piece in data_c.chunks(piece_len) {
2360                        let pieces: std::vec::Vec<(usize, &[u8])> = (0..count).map(|i| (i, piece)).collect();
2361                        update_each(&mut hashers[..], &pieces);
2362                    }
2363                    let saw = HELD_GROUPS.with(|g| g.borrow().iter().any(|h| h.len() == count));
2364                    (*hashers[0].finalize().as_bytes(), *hashers[count - 1].finalize().as_bytes(), saw)
2365                })
2366                .expect("spawn 64 KiB thread")
2367                .join()
2368                .expect("held cohort must fit in 64 KiB stack");
2369            assert_eq!(first, if keyed_first { expected_keyed } else { expected_plain }, "cohort of {count} (keyed={keyed_first}) first");
2370            assert_eq!(last, expected_plain, "cohort of {count} (keyed={keyed_first}) last");
2371            #[cfg(target_arch = "x86_64")]
2372            if keyed_first && count >= INDEPENDENT_MIN && matches!(Platform::detect(), Platform::AVX2 | Platform::AVX512) {
2373                assert!(saw_independent, "mixed cohort of {count} must actually run held_groups (>16 tiled on 64 KiB stack)");
2374            }
2375            let _ = saw_independent;
2376        }
2377    }
2378
2379    /// Every middle chunk count (`2..=15`, exact and partial tails `1, 63, 64,
2380    /// 65, 512, 1023 B`), collection counts spanning singleton (`1`), small
2381    /// (`2`, `3`), and over-full (`LANES_AT_ONCE + 5`, exercising mid-round
2382    /// parent flushes and odd-leaf compaction), and all three `Mode`s match the
2383    /// reference implementation and exercise batched partial-chunk and
2384    /// parent/root rounds.
2385    #[test]
2386    fn hash_each_middle_all_chunk_counts_partial_tails_and_modes() {
2387        crate::initialize();
2388        let key = [0x3cu8; crate::KEY_LEN];
2389        let mut x = 0x9e37_79b9_7f4a_7c15u64;
2390        let mut fill = |n: usize| -> std::vec::Vec<u8> {
2391            (0..n)
2392                .map(|_| {
2393                    x ^= x << 13;
2394                    x ^= x >> 7;
2395                    x ^= x << 17;
2396                    x as u8
2397                })
2398                .collect()
2399        };
2400
2401        // Mixed collection with every chunk count 2..=15 (both exact and ragged
2402        // partial tails) plus empty, small (<= 1 KiB), and large (>= 16 KiB)
2403        // items, repeated past LANES_AT_ONCE so both partial-chunk flushes and
2404        // mid-round parent flushes with odd trailing leaves trigger.
2405        let tails = [0usize, 1, 63, 64, 65, 512, 1023];
2406        let mut raw: std::vec::Vec<std::vec::Vec<u8>> = std::vec![fill(0), fill(1), fill(64), fill(1024), fill(16 * CHUNK_LEN), fill(16 * CHUNK_LEN + 37)];
2407        for chunks in 2..ALONE_CHUNKS {
2408            for &tail in &tails {
2409                let len = if tail == 0 { chunks * CHUNK_LEN } else { (chunks - 1) * CHUNK_LEN + tail };
2410                raw.push(fill(len));
2411            }
2412        }
2413        // Extra 5-chunk ragged items past LANES_AT_ONCE to stress flush + odd compaction.
2414        while raw.len() < LANES_AT_ONCE + 20 {
2415            raw.push(fill(4 * CHUNK_LEN + 333));
2416        }
2417        let slices: std::vec::Vec<&[u8]> = raw.iter().map(|v| v.as_slice()).collect();
2418        let blocks = crate::test::messages(&slices);
2419        let items = crate::test::items(&blocks, &slices);
2420        for (m, mode) in [Mode::Plain, Mode::Keyed(&key), Mode::DeriveKey("each middle simd")].into_iter().enumerate() {
2421            let mut out = std::vec![[0u8; OUT_LEN]; items.len()];
2422            crate::throughput::hash_each(mode, &items, &mut out);
2423            for (i, s) in slices.iter().enumerate() {
2424                assert_eq!(out[i], crate::test::official::hash(mode, s), "mode={m} item {i} len={}", s.len());
2425            }
2426        }
2427
2428        // Singleton middle message (`messages.len() == 1`) and 15-chunk multi-round
2429        // reduction (`15 -> 8 -> 4 -> 2 -> 1`, 3 non-root parent rounds + 1 root round).
2430        #[cfg(target_arch = "x86_64")]
2431        let block_lanes = crate::pair::takes_platform(Platform::detect());
2432        #[cfg(target_arch = "aarch64")]
2433        let block_lanes = true;
2434        #[cfg(target_arch = "aarch64")]
2435        let last_lanes = crate::neon_hybrid::sha3_detected();
2436        #[cfg(not(target_arch = "aarch64"))]
2437        let last_lanes = false;
2438
2439        for count in [1usize, 2, 3, 17] {
2440            let bufs: std::vec::Vec<std::vec::Vec<u8>> = (0..count).map(|k| fill(14 * CHUNK_LEN + 100 + k * 7)).collect();
2441            let s: std::vec::Vec<&[u8]> = bufs.iter().map(|v| v.as_slice()).collect();
2442            let b = crate::test::messages(&s);
2443            let it = crate::test::items(&b, &s);
2444            let mut out = std::vec![[0u8; OUT_LEN]; count];
2445            crate::COUNTED.with(|c| {
2446                c[crate::Counted::ByBlocksCall as usize].set(0);
2447                c[crate::Counted::HashManyCall as usize].set(0);
2448            });
2449            crate::throughput::hash_each(Mode::Plain, &it, &mut out);
2450            for (i, msg) in s.iter().enumerate() {
2451                assert_eq!(out[i], crate::test::official::hash(Mode::Plain, msg), "15-chunk count={count} i={i}");
2452            }
2453            let by_blocks = crate::COUNTED.with(|c| c[crate::Counted::ByBlocksCall as usize].get());
2454            let hash_many = crate::COUNTED.with(|c| c[crate::Counted::HashManyCall as usize].get());
2455            if count == 1 {
2456                assert_eq!(by_blocks, 0, "single partial tail skips hash_chunks_by_blocks");
2457                assert_eq!(hash_many, 14, "single 15-chunk message runs 14 chunk rounds only");
2458            } else {
2459                // 14 full-chunk rounds + 3 parent rounds (15->8, 8->4, 4->2) + 1 root round.
2460                assert_eq!(hash_many, 18, "count={count} 15-chunk messages batch all 3 parent + 1 root rounds");
2461                if block_lanes {
2462                    assert!(by_blocks > 0, "count={count} >= 2 shared-prefix partial tails batch via hash_chunks_by_blocks");
2463                }
2464            }
2465        }
2466
2467        // Partial-tail boundary & exact group-width checks at counter 1 & 2:
2468        // - incompatible prefix lengths (1,127 B = k=1, 1,191 B = k=2) skip SIMD
2469        // - block-boundary pair (1024+511, 1024+512 -> both k=7) runs 1 SIMD call
2470        // - adjacent-boundary pair (1024+512 -> k=7, 1024+513 -> k=8) skips SIMD
2471        // - k=0 pair plus singleton k=1 (1024+32, 1024+32, 1024+103) skips SIMD on !last_lanes
2472        //   (kills `k > 0 -> k >= 0`) and runs 2 calls (k=0 + k=1) on SHA-3 NEON
2473        // - exact c-chunk message placed LAST alongside shared & single counter-c tails
2474        //   (exercises `item.len() > c * CHUNK_LEN` in both branches; `>=` panics OOB)
2475        // - BY_BLOCKS_AT_ONCE + 1 identical-k items at counter 1 exercises `slices.is_full()`
2476        //   (64/16 = 4 calls in first flush + 1 call in trailing flush = 5 calls).
2477        let partial_cases: &[(&str, &[usize], u64)] = &[
2478            ("incompatible k=1,2", &[CHUNK_LEN + 103, CHUNK_LEN + 167], 0),
2479            ("shared k=1 pair", &[CHUNK_LEN + 103, CHUNK_LEN + 103], if block_lanes { 1 } else { 0 }),
2480            ("shared k=7 at 511/512 boundary", &[CHUNK_LEN + 511, CHUNK_LEN + 512], if block_lanes { 1 } else { 0 }),
2481            ("split k=7/8 at 512/513 boundary", &[CHUNK_LEN + 512, CHUNK_LEN + 513], 0),
2482            ("k=0 pair + singleton k=1", &[CHUNK_LEN + 32, CHUNK_LEN + 32, CHUNK_LEN + 103], if block_lanes && last_lanes { 2 } else { 0 }),
2483            ("shared c=2 tails + trailing exact 2-chunk", &[2 * CHUNK_LEN + 512, 2 * CHUNK_LEN + 512, 2 * CHUNK_LEN], if block_lanes { 1 } else { 0 }),
2484            ("single c=2 tail + trailing exact 2-chunk", &[2 * CHUNK_LEN + 512, 2 * CHUNK_LEN], 0),
2485        ];
2486        for &(label, lens, want_calls) in partial_cases {
2487            let bufs: std::vec::Vec<std::vec::Vec<u8>> = lens.iter().map(|&n| fill(n)).collect();
2488            let s: std::vec::Vec<&[u8]> = bufs.iter().map(|v| v.as_slice()).collect();
2489            let b = crate::test::messages(&s);
2490            let it = crate::test::items(&b, &s);
2491            let mut out = std::vec![[0u8; OUT_LEN]; lens.len()];
2492            crate::COUNTED.with(|c| c[crate::Counted::ByBlocksCall as usize].set(0));
2493            crate::throughput::hash_each(Mode::Plain, &it, &mut out);
2494            for (i, msg) in s.iter().enumerate() {
2495                assert_eq!(out[i], crate::test::official::hash(Mode::Plain, msg), "{label} i={i}");
2496            }
2497            let got_calls = crate::COUNTED.with(|c| c[crate::Counted::ByBlocksCall as usize].get());
2498            assert_eq!(got_calls, want_calls, "{label}: exact ByBlocksCall count");
2499        }
2500
2501        // All-small collection returns before borrowing SHARED (catches `small_done` bugs).
2502        if block_lanes {
2503            let small_bufs = [fill(64), fill(128)];
2504            let s: std::vec::Vec<&[u8]> = small_bufs.iter().map(|v| v.as_slice()).collect();
2505            let b = crate::test::messages(&s);
2506            let it = crate::test::items(&b, &s);
2507            let mut out = [[0u8; OUT_LEN]; 2];
2508            SHARED.with(|shared| {
2509                let _held = shared.borrow_mut();
2510                crate::throughput::hash_each(Mode::Plain, &it, &mut out);
2511            });
2512            for (i, msg) in s.iter().enumerate() {
2513                assert_eq!(out[i], crate::test::official::hash(Mode::Plain, msg), "all-small fast exit i={i}");
2514            }
2515        }
2516
2517        // BY_BLOCKS_AT_ONCE + 1 items at the same counter (c = 1, k = 7 -> 64/16 + 1 = 5 calls).
2518        let over_full = BY_BLOCKS_AT_ONCE + 1;
2519        let bufs: std::vec::Vec<std::vec::Vec<u8>> = (0..over_full).map(|_| fill(CHUNK_LEN + 512)).collect();
2520        let s: std::vec::Vec<&[u8]> = bufs.iter().map(|v| v.as_slice()).collect();
2521        let b = crate::test::messages(&s);
2522        let it = crate::test::items(&b, &s);
2523        let mut out = std::vec![[0u8; OUT_LEN]; over_full];
2524        crate::COUNTED.with(|c| c[crate::Counted::ByBlocksCall as usize].set(0));
2525        crate::throughput::hash_each(Mode::Plain, &it, &mut out);
2526        for (i, msg) in s.iter().enumerate() {
2527            assert_eq!(out[i], crate::test::official::hash(Mode::Plain, msg), "over_full i={i}");
2528        }
2529        let got_calls = crate::COUNTED.with(|c| c[crate::Counted::ByBlocksCall as usize].get());
2530        let want_over_full = if block_lanes { (BY_BLOCKS_AT_ONCE as u64 / 16) + 1 } else { 0 };
2531        assert_eq!(got_calls, want_over_full, "BY_BLOCKS_AT_ONCE + 1 same-counter partial tails flush exactly");
2532    }
2533}