Skip to main content

blake3_servil_core/
throughput.rs

1//! The throughput API, for power users: every way this crate makes
2//! hashing fast (batches, collections, many hashers fed in turns). The program takes on more of the work, so the calls can be
3//! fast and simple:
4//!
5//! - **Inputs are [`Block`]s**: 64 bytes each on a 64-byte boundary, so
6//!   every message starts a cache line and no block straddles two; the
7//!   type holds it. A message is blocks and a length (`&[Block], len`),
8//!   the bytes past its end ignored. A batch is a [`Batch`]: messages of
9//!   one length, each in its own whole blocks, every byte past each one
10//!   zero, which the batch kernels read in place, side by side; a `Batch`
11//!   lets the program write only its messages' bytes, so those zeros
12//!   cannot go wrong. Bytes already in place become blocks with no copy
13//!   through [`Block::from_bytes`], and a batch through
14//!   [`Batch::from_blocks`] where its messages fill their blocks.
15//!   [`update_each`] and [`TreeHasher::hash`] take byte slices of any
16//!   length and alignment directly (without the caller copying them
17//!   into aligned [`Block`]s); `update_each` copies short pieces into a
18//!   [`Hasher`](crate::convenience::Hasher), and `TreeHasher::hash`
19//!   hashes caller-owned `&[u8]` slices on the hot path.
20//! - **Digests go where the program says**: into its slices and places.
21//! - **Every call takes a [`Mode`]**: `Mode::Plain` for the plain hash.
22//!
23//! For one call per hash, any slice, the result returned, see the
24//! [`convenience`](crate::convenience) API.
25
26pub use crate::block::Packed;
27pub use crate::block::{Batch, Block, Part, Prepared};
28pub use crate::each::{finalize_each, hash_each, update_each};
29
30use crate::{CHUNK_LEN, ContextKey, DERIVE_KEY_CONTEXT, Hash, IV, Mode, OUT_LEN};
31
32/// The hash in `mode` of the message of `len` bytes that starts `input`:
33/// a batch of one. The message starts a block, so on a cache line; the
34/// bytes past its end, in its last block and any after, are ignored.
35/// Tuned for call after call: for a hash now and then amid other work,
36/// [`convenience::hash`](crate::convenience::hash) is the faster call.
37///
38/// ```
39/// # blake3_servil_core::initialize();
40/// use blake3_servil_core::{Mode, convenience, throughput::{self, Batch}};
41/// let mut message = Batch::new(100, 1);
42/// message.set(0, &[7u8; 100]);
43/// assert_eq!(throughput::hash(Mode::Plain, message.blocks(), 100), convenience::hash(&[7u8; 100]));
44/// ```
45// Inlined, so a constant mode folds to its constants (as
46// convenience::hash is: no mode stored for the call to read). Always:
47// as the short path of the threads crate's hash_multithreaded it was
48// left a call (64 B there 5 to 7% slower, a Ryzen 9700X, instructions
49// level within the half percent the check reports).
50#[inline(always)]
51pub fn hash(mode: Mode, input: &[Block], len: usize) -> Hash {
52    let mut room = core::mem::MaybeUninit::uninit();
53    let (key, flags) = mode.key(&mut room);
54    crate::hash_serial(&Block::bytes(input)[..len], key, flags)
55}
56
57/// The hashes of a [`Batch`]'s messages, in `mode`, on the calling thread:
58/// `out[i]` becomes the [`hash`] of message `i`, one digest a message. This
59/// is the shape of a Merkle tree's layer: leaves of one size, or nodes of
60/// two 32-byte children, which the layer below writes straight into the
61/// next layer's batch (`Batch::digests_mut`).
62///
63/// Such a tree is one of your own design, not BLAKE3's own tree: each
64/// node here is the hash of a whole 64-byte message, where BLAKE3's
65/// parents are [`TreeHasher::parent_cvs`]'. In your design, hash the
66/// leaves and the nodes apart, with two modes (two
67/// [`Mode::DeriveKey`] contexts, say) or leaves that are never 64 bytes.
68/// Hashed alike, a 64-byte leaf made of two digests passes for a node,
69/// and a proof for one tree's leaf proves another tree's node.
70///
71/// ```
72/// # blake3_servil_core::initialize();
73/// use blake3_servil_core::{Mode, convenience, throughput::{self, Batch}};
74/// let mut leaves = Batch::new(256, 1000);
75/// for i in 0..1000 {
76///     leaves.set(i, &[7u8; 256]);
77/// }
78/// let mut hashes = vec![[0u8; 32]; 1000];
79/// throughput::hash_many(Mode::Plain, &leaves, &mut hashes);
80/// assert_eq!(hashes[3], *convenience::hash(&[7u8; 256]).as_bytes());
81/// ```
82///
83/// **Speed**: short messages hash several at a time, so a batch beats a
84/// loop of [`hash`]: on an Apple M4 Max, 64-byte messages take about 10 to
85/// 20 ns each in batches of 16 or more, against about 50 for one [`hash`]
86/// each. Messages longer than 15 KiB cost what [`hash`] costs. For the
87/// same hashes over several cores, the crate `blake3-servil` has
88/// `hash_many_multithreaded`.
89///
90/// A `Packed` of 16-, 32-, or 48-byte messages (or a borrowed `&[[u8; N]]`
91/// slice) is a batch too, hashed directly from
92/// contiguous caller memory on full SIMD groups with no copy into [`Block`]s:
93///
94/// ```
95/// # blake3_servil_core::initialize();
96/// use blake3_servil_core::{Mode, convenience, throughput::{self, Packed}};
97/// let mut leaves = Packed::<32>::new(1000);
98/// for (i, leaf) in leaves.iter_mut().enumerate() {
99///     leaf[0] = i as u8;
100/// }
101/// let mut digests = Packed::<32>::new(1000); // the next layer's input
102/// throughput::hash_many(Mode::Plain, &leaves, &mut digests);
103/// assert_eq!(digests[3], *convenience::hash(&leaves[3]).as_bytes());
104/// ```
105// Inlined, so a constant mode folds to its constants (as
106// convenience::hash is: no mode stored for the call to read).
107#[inline(always)]
108pub fn hash_many<P: Prepared + ?Sized>(mode: Mode, batch: &P, out: &mut [[u8; OUT_LEN]]) {
109    let mut room = core::mem::MaybeUninit::uninit();
110    let (key, flags) = mode.key(&mut room);
111    crate::hash_many_serial(batch.bytes(), batch.message_len(), batch.slot(), key, flags, out);
112}
113
114/// Hash `out.len()` single-block messages derived from `template` (`4..=64`
115/// bytes) in `mode`, replacing the 4-byte little-endian word at byte offset
116/// `counter_word * 4` with `start.wrapping_add(i)` (modulo 2^32) for
117/// `i in 0..out.len()`.
118///
119/// On AVX-512, AVX2, Apple/AArch64 SME2, and AArch64 NEON, full SIMD groups
120/// broadcast the template once into registers or L1 stack storage and advance
121/// only the counter word between groups, avoiding caller-side buffer stamping
122/// and input memory traffic in proof-of-work and counter-grinding loops; any
123/// remaining tail hashes serially.
124///
125/// Panics if `template.len() > BLOCK_LEN`, `counter_word >= 16`, or
126/// `counter_word * 4 + 4 > template.len()` (checked in every build, even
127/// when `out` is empty).
128///
129/// # Example
130///
131/// ```
132/// # blake3_servil_core::initialize();
133/// use blake3_servil_core::{Mode, convenience, throughput};
134/// let mut template = [0u8; 52];
135/// template[..48].fill(0xab);
136/// let mut digests = [[0u8; 32]; 16];
137/// throughput::hash_counter_range(Mode::Plain, &template, 12, 100, &mut digests);
138/// template[48..52].copy_from_slice(&103u32.to_le_bytes());
139/// assert_eq!(digests[3], *convenience::hash(&template).as_bytes());
140/// ```
141#[inline(always)]
142pub fn hash_counter_range(mode: Mode, template: &[u8], counter_word: usize, start: u32, out: &mut [[u8; OUT_LEN]]) {
143    // Validate template/word and enforce `initialize()` before checking empty
144    // output, and borrow via `mode.key()` so empty `Mode::DeriveKey` skips
145    // context hashing and nonempty calls avoid constructing a `TreeHasher`.
146    let validated = crate::ffi_counter::ValidatedTemplate::new(template, counter_word);
147    let platform = crate::Platform::detect();
148    if out.is_empty() {
149        return;
150    }
151    let mut derived = core::mem::MaybeUninit::uninit();
152    let (key, flags) = mode.key(&mut derived);
153    crate::ffi_counter::hash_counter_range_on(validated, start, key, flags, out, platform);
154}
155
156/// Hash `out.len()` single-block messages derived from `template` (`4..=64`
157/// bytes) in `mode`, replacing the 4-byte little-endian word at byte offset
158/// `counter_word * 4` with `start.wrapping_add(i)` (modulo 2^32) for
159/// `i in 0..out.len()`, writing the first 16 bytes of each BLAKE3 digest.
160///
161/// Identical to [`hash_counter_range`] truncated to 16 bytes, halving output
162/// memory traffic for 128-bit digest callers (such as WOTS/FORS leaf
163/// generation and hash-based signatures).
164///
165/// Panics if `template.len() > BLOCK_LEN`, `counter_word >= 16`, or
166/// `counter_word * 4 + 4 > template.len()` (checked in every build, even
167/// when `out` is empty).
168///
169/// # Example
170///
171/// ```
172/// # blake3_servil_core::initialize();
173/// use blake3_servil_core::{Mode, convenience, throughput};
174/// let mut template = [0u8; 36];
175/// template[..32].fill(0x5c);
176/// let mut digests = [[0u8; 16]; 18];
177/// throughput::hash_counter_range_trunc16(Mode::Plain, &template, 8, 50, &mut digests);
178/// template[32..36].copy_from_slice(&53u32.to_le_bytes());
179/// assert_eq!(digests[3], convenience::hash(&template).as_bytes()[..16]);
180/// ```
181#[inline(always)]
182pub fn hash_counter_range_trunc16(mode: Mode, template: &[u8], counter_word: usize, start: u32, out: &mut [[u8; 16]]) {
183    let validated = crate::ffi_counter::ValidatedTemplate::new(template, counter_word);
184    let platform = crate::Platform::detect();
185    if out.is_empty() {
186        return;
187    }
188    let mut derived = core::mem::MaybeUninit::uninit();
189    let (key, flags) = mode.key(&mut derived);
190    crate::ffi_counter::hash_counter_range_on(validated, start, key, flags, out, platform);
191}
192
193/// Search `count` consecutive single-block messages derived from `template`
194/// (`4..=64` bytes) in `mode`, replacing the 4-byte little-endian word at
195/// byte offset `counter_word * 4` with `start.wrapping_add(off as u32)` for
196/// `off in 0..count`, for digests whose first little-endian 32-bit word
197/// `word0 = u32::from_le_bytes(digest[..4])` satisfies
198/// `(word0 & mask) == target`.
199///
200/// Matching `(counter, digest)` pairs are written to `matches[..n]` in
201/// ascending search-offset order and the count `n <= matches.len()` is
202/// returned. On AVX-512, AVX2, Apple/AArch64 SME2, and AArch64 NEON,
203/// non-matching groups evaluate the predicate without writing digests to
204/// output RAM and exit early as soon as `matches` is filled. If `count > 2^32`,
205/// the 32-bit counter wraps and revisits earlier counter values.
206///
207/// **Timing note:** because this search stops early once `matches` is full, its
208/// runtime depends on which counters satisfy the predicate; use it for public
209/// nonce grinding and proof-of-work predicates rather than secret-dependent
210/// searches.
211///
212/// Panics if `template.len() > BLOCK_LEN`, `counter_word >= 16`, or
213/// `counter_word * 4 + 4 > template.len()` (checked in every build, even
214/// when `count == 0` or `matches` is empty).
215///
216/// # Example
217///
218/// ```
219/// # blake3_servil_core::initialize();
220/// use blake3_servil_core::{Mode, convenience, throughput};
221/// let mut template = [0u8; 52];
222/// template[..48].fill(0x2a);
223/// let mut hits = [(0u32, [0u8; 32]); 1];
224/// let found = throughput::find_counter_range(Mode::Plain, &template, 12, 0, 1024, 0x0000_000f, 0, &mut hits);
225/// assert_eq!(found, 1);
226/// template[48..52].copy_from_slice(&hits[0].0.to_le_bytes());
227/// assert_eq!(hits[0].1, *convenience::hash(&template).as_bytes());
228/// assert_eq!(u32::from_le_bytes(hits[0].1[..4].try_into().unwrap()) & 0xf, 0);
229/// ```
230#[inline(always)]
231#[allow(clippy::too_many_arguments)]
232pub fn find_counter_range(
233    mode: Mode,
234    template: &[u8],
235    counter_word: usize,
236    start: u32,
237    count: u64,
238    mask: u32,
239    target: u32,
240    matches: &mut [(u32, [u8; OUT_LEN])],
241) -> usize {
242    let validated = crate::ffi_counter::ValidatedTemplate::new(template, counter_word);
243    let platform = crate::Platform::detect();
244    if crate::ffi_counter::find_is_noop(count, matches.len(), mask, target) {
245        return 0;
246    }
247    let mut derived = core::mem::MaybeUninit::uninit();
248    let (key, flags) = mode.key(&mut derived);
249    crate::ffi_counter::find_counter_range_on(validated, start, count, mask, target, key, flags, matches, platform)
250}
251
252/// Evaluate `init.len()` independent 32-byte iterated hash chains in `mode`,
253/// advancing each chain by `steps` iterations and writing its final 16-byte
254/// state to `out[i]` (#584).
255///
256/// Each 32-byte input slot holds `[prefix12 || start_step_u32_le || state16]`.
257/// For each step `s in 0..steps`, `state_{s+1} = H_mode(prefix12 || (start_step + s) || state_s)[..16]`
258/// (modulo `2^32` on the step word). When `steps == 0`, `out[i]` receives
259/// `init[i][16..32]` unchanged.
260///
261/// Advances chains inside one fused kernel call across all `steps` iterations
262/// (18-lane 16-SME2 + 2-integer hybrid on Apple Silicon, 11-lane NEON `8+3`,
263/// 16-lane AVX-512, 8-lane AVX2), keeping state in registers on AVX-512 and
264/// SME2 vector lanes (or L1 stack slots on AVX2, NEON, and scalar lanes)
265/// without caller-buffer copies or per-step `smstart`/`smstop`. Work depends
266/// only on `init.len()` and `steps`, never on keys or chain values.
267///
268/// Panics if `init.len() != out.len()` (checked in every build, even when
269/// `steps == 0`).
270#[inline(always)]
271pub fn hash_chains_32_trunc16(mode: Mode, init: &[[u8; 32]], steps: u32, out: &mut [[u8; 16]]) {
272    assert_eq!(init.len(), out.len(), "one 16-byte output per chain");
273    let platform = crate::Platform::detect();
274    if init.is_empty() {
275        return;
276    }
277    let mut derived = core::mem::MaybeUninit::uninit();
278    let (key, flags) = mode.key(&mut derived);
279    hash_chains_32_trunc16_checked(init, steps, key, flags, out, platform);
280}
281
282#[inline(always)]
283fn hash_chains_32_trunc16_checked(init: &[[u8; 32]], steps: u32, key: &crate::CVWords, flags: u8, out: &mut [[u8; 16]], platform: crate::platform::Platform) {
284    crate::ffi_chain::hash_chains_32_trunc16_on(init, steps, key, flags, out, platform);
285}
286
287/// Variable-step counterpart to [`hash_chains_32_trunc16`] that advances chain
288/// `i` by `steps[i]` iterations in `mode` and writes its final 16-byte state
289/// to `out[i]` (uses stack storage up to 128 nonzero chains; allocates a
290/// call-local `Vec<usize>` above 128; #584).
291///
292/// Internally schedules a longest-processing-time-first (LPT) continuous
293/// lane-refilling work queue over fused multi-step SIMD bursts at the
294/// platform's native width, keeping SIMD lanes busy across heterogeneous
295/// verification chains without exposing ISA lane widths to callers. Uses stack
296/// storage when at most 128 chains have `steps[i] > 0`, and spills to a
297/// call-local `Vec<usize>` sized by the nonzero count (freed on return) above
298/// 128 nonzero chains. Work depends only on `init.len()` and `steps`, never on
299/// keys or chain values.
300///
301/// Panics if `init.len() != steps.len()` or `init.len() != out.len()`.
302#[inline(always)]
303pub fn hash_chains_varlen_32_trunc16(mode: Mode, init: &[[u8; 32]], steps: &[u32], out: &mut [[u8; 16]]) {
304    assert_eq!(init.len(), steps.len(), "one step count per chain");
305    assert_eq!(init.len(), out.len(), "one 16-byte output per chain");
306    let platform = crate::Platform::detect();
307    if init.is_empty() {
308        return;
309    }
310    let mut derived = core::mem::MaybeUninit::uninit();
311    let (key, flags) = mode.key(&mut derived);
312    hash_chains_varlen_32_trunc16_checked(init, steps, key, flags, out, platform);
313}
314
315#[inline(always)]
316fn hash_chains_varlen_32_trunc16_checked(
317    init: &[[u8; 32]],
318    steps: &[u32],
319    key: &crate::CVWords,
320    flags: u8,
321    out: &mut [[u8; 16]],
322    platform: crate::platform::Platform,
323) {
324    crate::ffi_chain::hash_chains_varlen_32_trunc16_on(init, steps, key, flags, out, platform);
325}
326
327/// Hash a key-derivation context string and return a [`ContextKey`].
328///
329/// This has the same security requirement as key derivation. **The context
330/// string should be hardcoded, globally unique, and application-specific.**
331///
332/// Its one use is [`Mode::DeriveKeyWith`]: a program that derives many
333/// keys from one context hashes the context once.
334///
335/// # Example
336///
337/// ```
338/// # blake3_servil_core::initialize();
339/// use blake3_servil_core::Mode;
340///
341/// let context_key = blake3_servil_core::throughput::context_key("foo");
342/// let derived = blake3_servil_core::convenience::hash_with(Mode::DeriveKeyWith(&context_key), b"bar");
343/// assert_eq!(derived, blake3_servil_core::convenience::hash_with(Mode::DeriveKey("foo"), b"bar"));
344/// ```
345pub fn context_key(context: &str) -> ContextKey {
346    crate::hash_serial(context.as_bytes(), IV, DERIVE_KEY_CONTEXT).0
347}
348
349const CHUNK: u64 = CHUNK_LEN as u64;
350
351/// The highest level of a whole subtree: 2^53 chunks, 2^63 bytes, the left
352/// half of the longest message.
353const MAX_LEVEL: u32 = 53;
354
355// A whole subtree's place in one word: its level plus one above its index.
356// The word of zeroed memory is then no place, so a slot that no call
357// filled is refused, whether a program wrote `Cv::unset()` or the
358// allocator's zeros are there.
359const LEVEL_SHIFT: u32 = 56;
360const INDEX_MASK: u64 = (1 << LEVEL_SHIFT) - 1;
361const UNSET: u64 = 0;
362
363/// The level of whole subtrees of `len` bytes: `len` is `1024 << level`.
364///
365/// Requires a power of two of chunks. In a `const`, another size stops the
366/// build; elsewhere it panics.
367///
368/// ```compile_fail,E0080
369/// use blake3_servil_core::throughput::level_of;
370/// const PART: u64 = 5 << 20; // 5 MiB is no subtree's size
371/// const LEVEL: u32 = level_of(PART);
372/// let _ = LEVEL;
373/// ```
374pub const fn level_of(len: u64) -> u32 {
375    assert!(len >= CHUNK && len % CHUNK == 0 && (len / CHUNK).is_power_of_two(), "a whole subtree holds a power of two of chunks");
376    (len / CHUNK).trailing_zeros()
377}
378
379/// A whole subtree's place, packed.
380const fn place(level: u32, index: u64) -> u64 {
381    assert!(level <= MAX_LEVEL, "a whole subtree's level is at most 53");
382    // It ends at byte (index + 1) << (level + 10), within a message's 2^64 - 1.
383    assert!(index < u64::MAX >> (level + 10), "the subtree ends beyond a message's last byte");
384    // The index is under 2^54, below the level's bits: the sum joins them.
385    ((level as u64 + 1) << LEVEL_SHIFT) + index
386}
387
388/// The place and size of the bytes a whole-subtree call was given.
389#[inline]
390fn subtree_place(level: u32, index: u64, len: usize) -> u64 {
391    let at = place(level, index);
392    assert!(len as u64 == CHUNK << level, "a whole subtree at level {level} holds {} bytes (found {len})", CHUNK << level);
393    at
394}
395
396/// The two halves of a valid whole subtree above level zero.
397const fn half_places(level: u32, index: u64) -> [u64; 2] {
398    let left = ((level as u64) << LEVEL_SHIFT) + 2 * index;
399    [left, left + 1]
400}
401
402/// The place of the parent of the whole subtree at `place` (an even index).
403const fn parent_place(place: u64) -> u64 {
404    (place & !INDEX_MASK) + (1 << LEVEL_SHIFT) + ((place & INDEX_MASK) >> 1)
405}
406
407/// The most bytes the last subtree that begins at `first_chunk` can hold:
408/// the whole subtree aligned there, as many chunks as the largest power of
409/// two that divides `first_chunk` (at chunk 0, a whole message), and no
410/// more than a message has left.
411const fn last_max(first_chunk: u64) -> u64 {
412    assert!(first_chunk <= u64::MAX / CHUNK, "the subtree starts beyond a message's last byte");
413    let room = u64::MAX - first_chunk * CHUNK;
414    if first_chunk == 0 {
415        return room;
416    }
417    // first_chunk is under 2^54, so its whole subtree is 2^63 bytes or less.
418    let whole = CHUNK << first_chunk.trailing_zeros();
419    if whole < room { whole } else { room }
420}
421
422/// The chaining value of a **whole** subtree, with its place: 2^level
423/// chunks (1024 bytes each), the `index`-th subtree of that size in the
424/// message. It is the only kind a left child can be.
425///
426/// A chaining value is the 32 bytes a BLAKE3 tree passes from a subtree up
427/// to its parent. It is not a hash of anything a program can check alone,
428/// and has its own type so that it is never taken for one: the root alone
429/// gives a [`struct@Hash`] ([`TreeHasher::root_hash`]).
430///
431/// Equality compares the place and, in constant time, the bytes. `Debug`
432/// shows the place alone, so that a refusal's message carries no chaining
433/// value of a keyed tree.
434///
435/// # Trait implementations
436///
437/// - `Clone` reproduces both the value and its place, including an unset
438///   slot.
439/// - `Copy` copies the bytes and place together.
440/// - `Debug` shows the place or the unset state without exposing chaining
441///   bytes.
442/// - `Eq` identifies values with equal bytes and place.
443/// - `PartialEq` compares the place and compares the chaining bytes in
444///   constant time.
445#[derive(Clone, Copy)]
446pub struct Cv {
447    /// The chaining value as the kernels take it: 32 bytes.
448    value: crate::CVBytes,
449    place: u64,
450}
451
452impl Cv {
453    /// A slot not yet filled, for an array that a call will fill: every
454    /// call that takes a `Cv` as a subtree's value refuses it
455    /// ([`as_bytes`](Cv::as_bytes) gives its 32 zero bytes). Zeroed memory
456    /// is the same value.
457    pub const fn unset() -> Self {
458        Cv { value: [0; OUT_LEN], place: UNSET }
459    }
460
461    /// A chaining value a program stored or received, for the whole
462    /// subtree at `level` and `index`. The place is the program's word:
463    /// bytes of another subtree give a wrong hash, as wrong input does.
464    ///
465    /// Requires a level of at most 53 and a subtree that ends
466    /// within a message's 2^64 - 1 bytes.
467    pub const fn at(level: u32, index: u64, bytes: [u8; OUT_LEN]) -> Self {
468        Cv { value: bytes, place: place(level, index) }
469    }
470
471    /// The chaining value's bytes.
472    #[inline]
473    pub const fn as_bytes(&self) -> &[u8; OUT_LEN] {
474        &self.value
475    }
476
477    /// The subtree holds 2^level chunks.
478    ///
479    /// Requires a value that was set.
480    #[inline]
481    pub const fn level(&self) -> u32 {
482        (self.set() >> LEVEL_SHIFT) as u32 - 1
483    }
484
485    /// The subtree is the `index`-th of its size.
486    ///
487    /// Requires a value that was set.
488    #[inline]
489    pub const fn index(&self) -> u64 {
490        self.set() & INDEX_MASK
491    }
492
493    /// The two values returned to a Hasher by its pool. Check their
494    /// places before the stack takes only the bytes.
495    pub(crate) fn halves_bytes([left, right]: [Self; 2], level: u32, index: u64) -> [crate::CVBytes; 2] {
496        let [a, b] = half_places(level, index);
497        assert!(left.place == a && right.place == b, "not the halves of level {level} index {index}: {left:?} and {right:?}");
498        [left.value, right.value]
499    }
500
501    /// The place, of a value that has one.
502    #[inline]
503    const fn set(&self) -> u64 {
504        assert!(self.place != UNSET, "a chaining value that was never set");
505        self.place
506    }
507}
508
509impl core::fmt::Debug for Cv {
510    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
511        if self.place == UNSET { write!(f, "a value never set") } else { write!(f, "the whole subtree at level {} index {}", self.level(), self.index()) }
512    }
513}
514
515impl PartialEq for Cv {
516    #[inline]
517    fn eq(&self, other: &Cv) -> bool {
518        (self.place == other.place) & crate::ct::eq_32(&self.value, &other.value)
519    }
520}
521
522impl Eq for Cv {}
523
524/// The chaining value of a message's **last** subtree, with its place and
525/// length: the right child at some level of the tree's right edge. It may
526/// be shorter than its left sibling, and is never a left child: no call
527/// takes one on the left, so a tree with a short subtree inside it does
528/// not compile.
529///
530/// ```compile_fail,E0308
531/// # blake3_servil_core::initialize();
532/// use blake3_servil_core::{Mode, throughput::TreeHasher};
533/// let tree = TreeHasher::new(Mode::Plain);
534/// let end = tree.last_cv(1, &[7u8; 100]);
535/// let next = tree.subtree_cv(0, 2, &[7u8; 1024]);
536/// let _ = tree.parent_cv(&end, &next); // a short subtree on the left
537/// ```
538///
539/// A whole subtree that ends the message becomes one by `LastCv::from`:
540/// the program says that the message ends there.
541///
542/// Equality and `Debug` are as [`Cv`]'s.
543///
544/// # Trait implementations
545///
546/// - `Clone` reproduces the value, starting chunk and length.
547/// - `Copy` copies those coordinates along with the chaining bytes.
548/// - `Debug` shows the starting chunk and length without exposing chaining
549///   bytes.
550/// - `Eq` identifies values with equal coordinates and bytes.
551/// - `From` (of a `Cv`) keeps a whole subtree's bytes and records its first
552///   chunk and full length, on the caller's word that the message ends
553///   there; it panics on a `Cv` that was never set.
554/// - `PartialEq` compares both coordinates and compares the chaining bytes
555///   in constant time.
556#[derive(Clone, Copy)]
557pub struct LastCv {
558    value: crate::CVBytes,
559    first_chunk: u64,
560    len: u64,
561}
562
563impl LastCv {
564    /// A chaining value a program stored or received, for the last
565    /// subtree: the message's last `len` bytes, which begin at its chunk
566    /// `first_chunk`.
567    ///
568    /// Requires what [`TreeHasher::last_cv`] does of the place and the
569    /// length.
570    pub const fn at(first_chunk: u64, len: u64, bytes: [u8; OUT_LEN]) -> Self {
571        assert!(len >= 1 && len <= last_max(first_chunk), "the last subtree holds from one byte to the whole subtree aligned at its first chunk");
572        LastCv { value: bytes, first_chunk, len }
573    }
574
575    /// The chaining value's bytes.
576    #[inline]
577    pub const fn as_bytes(&self) -> &[u8; OUT_LEN] {
578        &self.value
579    }
580
581    /// The message's chunk the subtree begins at.
582    #[inline]
583    pub const fn first_chunk(&self) -> u64 {
584        self.first_chunk
585    }
586
587    /// The subtree's bytes: one or more.
588    #[inline]
589    #[allow(clippy::len_without_is_empty)]
590    pub const fn len(&self) -> u64 {
591        self.len
592    }
593}
594
595impl core::fmt::Debug for LastCv {
596    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
597        write!(f, "the last subtree, {} bytes from chunk {}", self.len, self.first_chunk)
598    }
599}
600
601impl PartialEq for LastCv {
602    #[inline]
603    fn eq(&self, other: &LastCv) -> bool {
604        (self.first_chunk == other.first_chunk) & (self.len == other.len) & crate::ct::eq_32(&self.value, &other.value)
605    }
606}
607
608impl Eq for LastCv {}
609
610/// A whole subtree that ends the message: the program says so.
611impl From<Cv> for LastCv {
612    fn from(cv: Cv) -> LastCv {
613        let (level, index) = (cv.level(), cv.index());
614        LastCv { value: cv.value, first_chunk: index << level, len: CHUNK << level }
615    }
616}
617
618/// A [`Mode`] prepared for a program that builds or verifies a BLAKE3 tree
619/// itself (verified streaming, an outboard, a tree hashed in parts on
620/// other machines): the subtrees' chaining values, their parents, and the
621/// root. The mode's key is derived once, here; each call then costs its
622/// hashing alone.
623///
624/// A message of more than one chunk (1024 bytes) is a binary tree: its left
625/// subtree holds the largest power of two of chunks below its count
626/// ([`left_len`]), its right subtree the rest, and so on down. A message
627/// of one chunk or less is its root alone: [`hash`] or
628/// [`convenience::hash_with`](crate::convenience::hash_with).
629///
630/// **A tree that is not BLAKE3's has no way through these calls.** Every
631/// left child is a *whole* subtree: a power of two of chunks, starting at a
632/// multiple of its own size. Its right sibling begins where it ends and is
633/// no longer. The message's *last* subtree, the right child at every level
634/// down the tree's right edge, is the only one that may be shorter.
635///
636/// | Part of the rule | Kept by | When |
637/// |---|---|---|
638/// | A whole subtree's size is a power of two of chunks | its name, `level`: no other size can be said. For a size in bytes, [`level_of`] in a `const` | the build stops |
639/// | A whole subtree starts at a multiple of its size | its name, `index`, counted in subtrees of its size | cannot be written |
640/// | A left child is whole | two types: [`Cv`] is whole, [`LastCv`] is the last. A left child is a `Cv` | the build stops |
641/// | A root's right child ends the message | [`root_hash`](TreeHasher::root_hash) takes a `LastCv` on the right | the build stops |
642/// | The bytes handed over are the subtree named | [`subtree_cv`](TreeHasher::subtree_cv) takes exactly `1024 << level` bytes | panics, in every build |
643/// | The last subtree is no longer than its left sibling | [`last_cv`](TreeHasher::last_cv) takes from 1 byte to the whole subtree aligned at its first chunk | panics, in every build |
644/// | Two children are siblings, in order | each value carries its place, and every call that joins two compares the places | panics, in every build |
645/// | The tree holds the whole message | `root_hash` takes the message's length and compares it with what the two children hold | panics, in every build |
646///
647/// What no call can check: that the bytes handed over are the message's
648/// bytes at the place named. Wrong bytes give a wrong hash, as they do in
649/// any hash call. Nor that a value was made in this mode and under this
650/// key: a [`Cv`] carries its place and not its mode, so one kept from a
651/// `TreeHasher` of another mode or key joins at the same place without a
652/// panic, and the root is then not promised to be the message's hash under
653/// either. A
654/// program that keeps values (a cache of subtrees) keeps them by mode and
655/// key as well as by place.
656///
657/// A message hashed in parts of 4 KiB (the part size is checked when this
658/// compiles; parts of 5 MiB would stop the build):
659///
660/// ```
661/// # blake3_servil_core::initialize();
662/// use blake3_servil_core::{Mode, convenience, throughput::{TreeHasher, level_of}};
663/// const PART: usize = 4096;
664/// const LEVEL: u32 = level_of(PART as u64);
665/// let message = [7u8; 3 * PART + 100];
666/// let tree = TreeHasher::new(Mode::Plain);
667/// let part = |i: usize| &message[i * PART..message.len().min((i + 1) * PART)];
668/// let (p0, p1, p2) = (tree.subtree_cv(LEVEL, 0, part(0)), tree.subtree_cv(LEVEL, 1, part(1)), tree.subtree_cv(LEVEL, 2, part(2)));
669/// let end = tree.last_cv((3 * PART / 1024) as u64, part(3));
670/// let left = tree.parent_cv(&p0, &p1);
671/// let right = tree.last_parent_cv(&p2, &end);
672/// assert_eq!(tree.root_hash(&left, &right, message.len() as u64), convenience::hash(&message));
673/// ```
674///
675/// A root's right child is one that ends the message, so two whole
676/// subtrees are no root's children until the program says the second is
677/// the last (`right.into()`):
678///
679/// ```compile_fail,E0308
680/// # blake3_servil_core::initialize();
681/// use blake3_servil_core::{Mode, throughput::TreeHasher};
682/// let tree = TreeHasher::new(Mode::Plain);
683/// let (left, right) = (tree.subtree_cv(0, 0, &[7u8; 1024]), tree.subtree_cv(0, 1, &[7u8; 1024]));
684/// let _ = tree.root_hash(&left, &right, 2048);
685/// ```
686///
687/// ```
688/// # blake3_servil_core::initialize();
689/// use blake3_servil_core::{Mode, convenience, throughput::TreeHasher};
690/// let tree = TreeHasher::new(Mode::Plain);
691/// let (left, right) = (tree.subtree_cv(0, 0, &[7u8; 1024]), tree.subtree_cv(0, 1, &[7u8; 1024]));
692/// assert_eq!(tree.root_hash(&left, &right.into(), 2048), convenience::hash(&[7u8; 2048]));
693/// ```
694///
695/// # Key-dependent timing
696///
697/// A keyed `TreeHasher`'s work depends on the lengths it is given and on the
698/// kind of its mode, never on the key's value.
699/// See the [key-independence contract](crate#key-dependent-timing).
700///
701/// # Trait implementations
702///
703/// - `Clone` prepares an independent tree hasher with the same key, mode
704///   and core selection.
705#[derive(Clone)]
706pub struct TreeHasher {
707    domain: crate::Domain,
708    on_this_core: bool,
709}
710
711impl TreeHasher {
712    /// The tree of messages hashed in `mode`.
713    pub fn new(mode: Mode) -> Self {
714        Self { domain: crate::Domain::from_mode(mode), on_this_core: false }
715    }
716
717    /// The `TreeHasher` of an existing validated [`crate::Domain`], for its large
718    /// subtrees' callback (`Hasher::update_with`).
719    pub(crate) fn of_domain(domain: crate::Domain) -> Self {
720        Self { domain, on_this_core: false }
721    }
722
723    /// The kernels for this `TreeHasher`: the calling core's own when
724    /// `on_this_core` is set, otherwise the detected platform's.
725    #[inline]
726    fn platform(&self) -> crate::platform::Platform {
727        if self.on_this_core { crate::platform::Platform::own_core() } else { crate::platform::Platform::detect() }
728    }
729
730    /// Checked subtree CV on `platform`, shared by `subtree_cv` and `subtree_cv_under`.
731    #[inline]
732    fn subtree_cv_on_platform(&self, platform: crate::platform::Platform, level: u32, index: u64, input: &[u8]) -> Cv {
733        let place = subtree_place(level, index, input.len());
734        Cv { value: self.cv_on(platform, index << level, input), place }
735    }
736
737    /// [`subtree_cv`](TreeHasher::subtree_cv) using an already-acquired
738    /// [`Sme2Turn`](crate::thread_support::Sme2Turn): for `blake3-servil`'s
739    /// caller prefix, which holds one turn across its prefix pieces without
740    /// exposing `Platform` or adding thread-local turn state (#460).
741    /// Respects [`Self::on_this_core`]: a pinned `TreeHasher` stays on the
742    /// calling core's own kernels even if `turn` grants SME2.
743    #[doc(hidden)]
744    pub fn subtree_cv_under(&self, turn: &crate::platform::Sme2Turn, level: u32, index: u64, input: &[u8]) -> Cv {
745        let platform = if self.on_this_core { crate::platform::Platform::own_core() } else { turn.platform() };
746        self.subtree_cv_on_platform(platform, level, index, input)
747    }
748
749    /// A subtree's chaining value, on `platform`'s kernels.
750    #[inline]
751    fn cv_on(&self, platform: crate::platform::Platform, first_chunk: u64, input: &[u8]) -> crate::CVBytes {
752        if input.len() <= CHUNK_LEN {
753            return crate::ChunkState::new(self.domain.key(), first_chunk, self.domain.flags(), platform).update(input).output().chaining_value();
754        }
755        let [left, right] = self.halves_on(platform, first_chunk, input);
756        crate::hasher::parent_output(&left, &right, self.domain.key(), self.domain.flags(), platform).chaining_value()
757    }
758
759    /// The values of a subtree's children, not yet labelled.
760    #[inline]
761    fn halves_on(&self, platform: crate::platform::Platform, first_chunk: u64, input: &[u8]) -> [crate::CVBytes; 2] {
762        crate::tree::root_children(&crate::tree::PlatformKernels { key: self.domain.key(), flags: self.domain.flags(), platform }, input, 0, first_chunk)
763    }
764
765    /// This `TreeHasher`, its calls kept to the calling core's own kernels.
766    ///
767    /// On systems where this build selects SME2 (such as Apple M4 and
768    /// later, or 64-bit Arm Linux CPUs with 512-bit SME2), calls hashing
769    /// 16 KiB or more (or SME2-sized batches, e.g. 11 or more nonempty
770    /// one-block messages in `hash_many`) take a process-local, best-effort
771    /// turn on SME2; this option routes this `TreeHasher`'s calls to the
772    /// core's own NEON kernels instead. That helps in two situations:
773    ///
774    /// - **Several threads hashing at once:** avoiding contention on the
775    ///   shared matrix hardware.
776    /// - **Single-threaded workloads interleaving short batches with
777    ///   scalar hashes:** entering and leaving SME2 streaming mode (and
778    ///   any resulting core clock transitions) can cost more than hashing
779    ///   the batch on NEON directly. On Apple M4/M6 this crossover sits
780    ///   around ~135–155 one-block messages when calls alternate with
781    ///   scalar work (e.g. a 12-to-64-message batch interleaved with
782    ///   scalar hashes runs faster with `.on_this_core()`, while steady
783    ///   cold-cache batches from `ONE_BLOCK_PAD_MIN = 11` upward still
784    ///   benefit from SME2 by default).
785    ///
786    /// On builds or CPUs that do not select SME2, this changes nothing.
787    pub fn on_this_core(mut self) -> Self {
788        self.on_this_core = true;
789        self
790    }
791
792    /// The kernels for a call over `len` bytes: the detected platform's,
793    /// with the shared accelerator's turn where the call may take it.
794    #[inline]
795    fn turn(&self, len: usize) -> crate::platform::Sme2Turn {
796        self.turn_if(len >= crate::SME2_SIZED_LEN)
797    }
798
799    /// The kernels for a call that may take the shared accelerator's turn
800    /// when `sme2_sized` says its work is the accelerator's size.
801    #[inline]
802    fn turn_if(&self, sme2_sized: bool) -> crate::platform::Sme2Turn {
803        // `self.platform()` already returns `Platform::own_core()` (NEON) when
804        // `self.on_this_core` is set, and `Sme2Turn::take` is a no-op on NEON.
805        crate::platform::Sme2Turn::take(self.platform(), sme2_sized)
806    }
807
808    /// The hash of the whole message `input`: what
809    /// [`convenience::hash_with`](crate::convenience::hash_with) returns
810    /// for this `TreeHasher`'s mode, the mode's key not derived again.
811    ///
812    /// Unlike [`convenience::hash_with`](crate::convenience::hash_with),
813    /// this runs the hot throughput path (no cold-call code prefetch), and
814    /// unlike [`hash`], it takes any `&[u8]` slice directly without the
815    /// caller copying it into aligned [`Block`]s (partial trailing blocks
816    /// are still padded on the stack internally) — making it the direct
817    /// single-threaded call for repeated back-to-back hashing of
818    /// caller-owned `&[u8]` slices (and for deriving many hashes under one
819    /// key-derivation context, paid once in [`new`](TreeHasher::new)).
820    ///
821    /// ```
822    /// # blake3_servil_core::initialize();
823    /// use blake3_servil_core::{Mode, convenience, throughput::TreeHasher};
824    /// let tree = TreeHasher::new(Mode::DeriveKey("example.com 2026-11-16 session keys"));
825    /// assert_eq!(tree.hash(b"material"), convenience::hash_with(Mode::DeriveKey("example.com 2026-11-16 session keys"), b"material"));
826    /// ```
827    #[cfg_attr(target_arch = "aarch64", inline)]
828    pub fn hash(&self, input: &[u8]) -> Hash {
829        #[cfg(target_arch = "aarch64")]
830        {
831            if input.len() <= crate::BLOCK_LEN {
832                let _ = crate::platform::Platform::detect();
833                return crate::hash_one_block_root(input, self.domain.key(), self.domain.flags());
834            }
835            self.hash_long(input)
836        }
837        #[cfg(not(target_arch = "aarch64"))]
838        {
839            let turn = self.turn(input.len());
840            crate::hash_serial_on(input, self.domain.key(), self.domain.flags(), turn.platform())
841        }
842    }
843
844    #[cfg(target_arch = "aarch64")]
845    #[inline(never)]
846    fn hash_long(&self, input: &[u8]) -> Hash {
847        #[cfg(test)]
848        TREE_HASH_LONG_CALLS.with(|c| c.set(c.get() + 1));
849        let turn = self.turn(input.len());
850        crate::hash_serial_on(input, self.domain.key(), self.domain.flags(), turn.platform())
851    }
852
853    /// The hashes of a batch's messages, as [`hash_many`] gives them, in
854    /// this `TreeHasher`'s mode: `out[i]` becomes the hash of message `i`.
855    ///
856    /// Requires one output a message.
857    pub fn hash_many<P: Prepared + ?Sized>(&self, batch: &P, out: &mut [[u8; OUT_LEN]]) {
858        let turn = self.turn_if(crate::many::sme2_sized(batch.message_len(), batch.slot(), out.len()));
859        crate::many::hash_many_on(batch.bytes(), batch.message_len(), batch.slot(), self.domain.key(), self.domain.flags(), out, turn.platform());
860    }
861
862    /// Hash `out.len()` single-block messages derived from `template`
863    /// (`4..=64` bytes) in this `TreeHasher`'s mode, replacing the 4-byte
864    /// little-endian word at byte offset `counter_word * 4` with
865    /// `start.wrapping_add(i)` (modulo 2^32) for `i in 0..out.len()`.
866    ///
867    /// Respects [`Self::on_this_core`] on Apple/AArch64 SME2 hosts. Panics if
868    /// `template.len() > BLOCK_LEN`, `counter_word >= 16`, or
869    /// `counter_word * 4 + 4 > template.len()` (checked in every build, even
870    /// when `out` is empty).
871    pub fn hash_counter_range(&self, template: &[u8], counter_word: usize, start: u32, out: &mut [[u8; OUT_LEN]]) {
872        let validated = crate::ffi_counter::ValidatedTemplate::new(template, counter_word);
873        let platform = self.platform();
874        if out.is_empty() {
875            return;
876        }
877        crate::ffi_counter::hash_counter_range_on(validated, start, self.domain.key(), self.domain.flags(), out, platform);
878    }
879
880    /// Hash `out.len()` single-block messages derived from `template`
881    /// (`4..=64` bytes) in this `TreeHasher`'s mode, writing the first 16 bytes
882    /// of each digest. See [`hash_counter_range_trunc16`].
883    ///
884    /// Respects [`Self::on_this_core`] on Apple/AArch64 SME2 hosts.
885    pub fn hash_counter_range_trunc16(&self, template: &[u8], counter_word: usize, start: u32, out: &mut [[u8; 16]]) {
886        let validated = crate::ffi_counter::ValidatedTemplate::new(template, counter_word);
887        let platform = self.platform();
888        if out.is_empty() {
889            return;
890        }
891        crate::ffi_counter::hash_counter_range_on(validated, start, self.domain.key(), self.domain.flags(), out, platform);
892    }
893
894    /// Search `count` consecutive single-block messages derived from `template`
895    /// (`4..=64` bytes) in this `TreeHasher`'s mode for digests whose first
896    /// little-endian 32-bit word satisfies `(word0 & mask) == target`, writing
897    /// up to `matches.len()` pairs in ascending offset order and returning the
898    /// number found. See [`find_counter_range`].
899    ///
900    /// Respects [`Self::on_this_core`] on Apple/AArch64 SME2 hosts.
901    #[allow(clippy::too_many_arguments)]
902    pub fn find_counter_range(
903        &self,
904        template: &[u8],
905        counter_word: usize,
906        start: u32,
907        count: u64,
908        mask: u32,
909        target: u32,
910        matches: &mut [(u32, [u8; OUT_LEN])],
911    ) -> usize {
912        let validated = crate::ffi_counter::ValidatedTemplate::new(template, counter_word);
913        let platform = self.platform();
914        if crate::ffi_counter::find_is_noop(count, matches.len(), mask, target) {
915            return 0;
916        }
917        crate::ffi_counter::find_counter_range_on(validated, start, count, mask, target, self.domain.key(), self.domain.flags(), matches, platform)
918    }
919
920    /// Evaluate `init.len()` independent 32-byte iterated hash chains in this
921    /// `TreeHasher`'s mode, advancing each chain by `steps` iterations and
922    /// writing its final 16-byte state to `out[i]` (#584).
923    ///
924    /// See [`hash_chains_32_trunc16`] for the 32-byte `[prefix12 || step_u32_le || state16]`
925    /// layout. Respects [`Self::on_this_core`] on Apple/AArch64 SME2 hosts.
926    /// Panics if `init.len() != out.len()` (checked in every build).
927    pub fn hash_chains_32_trunc16(&self, init: &[[u8; 32]], steps: u32, out: &mut [[u8; 16]]) {
928        assert_eq!(init.len(), out.len(), "one 16-byte output per chain");
929        let platform = self.platform();
930        if init.is_empty() {
931            return;
932        }
933        hash_chains_32_trunc16_checked(init, steps, self.domain.key(), self.domain.flags(), out, platform);
934    }
935
936    /// Variable-step counterpart to [`Self::hash_chains_32_trunc16`]: advances
937    /// chain `i` by `steps[i]` iterations in this `TreeHasher`'s mode and
938    /// writes its final 16-byte state to `out[i]` (#584).
939    ///
940    /// Uses an LPT continuous lane-refilling scheduler over fused multi-step
941    /// SIMD bursts; respects [`Self::on_this_core`]. Panics if
942    /// `init.len() != steps.len()` or `init.len() != out.len()`.
943    pub fn hash_chains_varlen_32_trunc16(&self, init: &[[u8; 32]], steps: &[u32], out: &mut [[u8; 16]]) {
944        assert_eq!(init.len(), steps.len(), "one step count per chain");
945        assert_eq!(init.len(), out.len(), "one 16-byte output per chain");
946        let platform = self.platform();
947        if init.is_empty() {
948            return;
949        }
950        hash_chains_varlen_32_trunc16_checked(init, steps, self.domain.key(), self.domain.flags(), out, platform);
951    }
952
953    /// Try the whole-block lanes with separate readable inputs. Returns
954    /// false without writing if this group takes the one-message path.
955    #[doc(hidden)]
956    pub fn try_hash_group<'a>(&self, count: usize, input: impl Fn(usize) -> &'a [u8], output: impl FnMut(usize, [u8; OUT_LEN])) -> bool {
957        crate::many::try_whole_group(count, input, self.domain.key(), self.domain.flags(), self.platform(), output)
958    }
959
960    /// The hash of each message, of any lengths, as [`hash_each`] gives
961    /// them, in this `TreeHasher`'s mode: `out[i]` becomes the hash of the
962    /// message of `items[i].1` bytes that starts `items[i].0`.
963    ///
964    /// Requires `out.len() == items.len()`.
965    pub fn hash_each(&self, items: &[(&[Block], usize)], out: &mut [[u8; OUT_LEN]]) {
966        assert_eq!(items.len(), out.len(), "one digest per item");
967        crate::each::hash_each_on(self.domain.key(), self.domain.flags(), items, out, self.platform(), |item| self.hash(item));
968    }
969
970    /// The chaining value of the parent of two subtrees.
971    fn bare_parent_cv(&self, left: &crate::CVBytes, right: &crate::CVBytes) -> crate::CVBytes {
972        crate::hasher::parent_output(left, right, self.domain.key(), self.domain.flags(), self.platform()).chaining_value()
973    }
974
975    /// A layer of parents on `platform`: `out[i]` is the parent of
976    /// `children[2 * i]` and `children[2 * i + 1]`, side by side in the
977    /// CPU's lanes.
978    ///
979    /// Requires an even number of children and half as many outputs.
980    fn bare_parent_cvs_on(&self, platform: crate::platform::Platform, children: &[crate::CVBytes], out: &mut [crate::CVBytes]) {
981        assert_eq!(children.len() % 2, 0, "parents take their children in pairs");
982        assert_eq!(out.len(), children.len() / 2, "one parent per pair of children");
983        // As many pairs a call as the kernels take.
984        let pairs = crate::platform::MAX_SIMD_DEGREE;
985        for (children, out) in children.chunks(2 * pairs).zip(out.chunks_mut(pairs)) {
986            if children.len() == 2 {
987                out[0] = crate::hasher::parent_output(&children[0], &children[1], self.domain.key(), self.domain.flags(), platform).chaining_value();
988                continue;
989            }
990            let _ = crate::compress_parents_parallel(children.as_flattened(), self.domain.key(), self.domain.flags(), platform, out.as_flattened_mut());
991        }
992    }
993
994    /// The hash of the message whose root has these two children: the
995    /// tree's top, where the chaining values end.
996    fn bare_root_hash(&self, left: &crate::CVBytes, right: &crate::CVBytes) -> Hash {
997        crate::hasher::parent_output(left, right, self.domain.key(), self.domain.flags(), self.platform()).root_hash()
998    }
999
1000    /// The extended output of the message whose root has these two
1001    /// children: its first 32 bytes are [`bare_root_hash`](TreeHasher::bare_root_hash)'s.
1002    fn bare_root_output(&self, left: &crate::CVBytes, right: &crate::CVBytes) -> crate::OutputReader {
1003        crate::OutputReader::new(crate::hasher::parent_output(left, right, self.domain.key(), self.domain.flags(), self.platform()))
1004    }
1005    /// The chaining value of a whole subtree: the `index`-th of 2^`level`
1006    /// chunks.
1007    ///
1008    /// Requires `input.len() == 1024 << level`, checked in every build.
1009    pub fn subtree_cv(&self, level: u32, index: u64, input: &[u8]) -> Cv {
1010        let turn = self.turn(input.len());
1011        self.subtree_cv_on_platform(turn.platform(), level, index, input)
1012    }
1013
1014    /// The chaining values of a whole subtree's left and right halves,
1015    /// in that order. Keep the halves when the subtree might turn out to
1016    /// be the whole message: its root needs both children.
1017    ///
1018    /// Requires a positive `level` and the same whole subtree as
1019    /// [`subtree_cv`](Self::subtree_cv), checked in every build.
1020    pub fn subtree_halves(&self, level: u32, index: u64, input: &[u8]) -> [Cv; 2] {
1021        subtree_place(level, index, input.len());
1022        assert!(level > 0, "a subtree of one chunk has no halves");
1023        let [a, b] = half_places(level, index);
1024        let turn = self.turn(input.len());
1025        let [left, right] = self.halves_on(turn.platform(), index << level, input);
1026        [Cv { value: left, place: a }, Cv { value: right, place: b }]
1027    }
1028
1029    /// The chaining value of the message's last subtree: `input` is the
1030    /// message from its chunk `first_chunk` to its end.
1031    ///
1032    /// Requires from one byte to the whole subtree aligned at
1033    /// `first_chunk` (as many chunks as the largest power of two that
1034    /// divides it), checked in every build. That is what makes it no
1035    /// longer than the left sibling it will be given.
1036    pub fn last_cv(&self, first_chunk: u64, input: &[u8]) -> LastCv {
1037        let (len, max) = (input.len() as u64, last_max(first_chunk));
1038        assert!(len >= 1 && len <= max, "the last subtree at chunk {first_chunk} holds 1 to {max} bytes (found {len})");
1039        let turn = self.turn(input.len());
1040        LastCv { value: self.cv_on(turn.platform(), first_chunk, input), first_chunk, len }
1041    }
1042
1043    /// The parent of two whole subtrees: whole, a level up.
1044    ///
1045    /// Requires siblings in order (`left` at an even index, `right` the
1046    /// next of its size), checked in every build.
1047    pub fn parent_cv(&self, left: &Cv, right: &Cv) -> Cv {
1048        let place = left.set();
1049        assert!(place & 1 == 0 && right.place == place + 1, "the children are not siblings: {left:?} and {right:?}");
1050        Cv { value: self.bare_parent_cv(&left.value, &right.value), place: parent_place(place) }
1051    }
1052
1053    /// The parent of a whole subtree and the message's last subtree: the
1054    /// last subtree a level up.
1055    ///
1056    /// Requires `left` at an even index and `right` beginning where it
1057    /// ends, checked in every build. (A last subtree that begins there is
1058    /// no longer than `left`: [`last_cv`](TreeHasher::last_cv) saw to it.)
1059    pub fn last_parent_cv(&self, left: &Cv, right: &LastCv) -> LastCv {
1060        let (level, index) = (left.level(), left.index());
1061        assert!(index & 1 == 0 && right.first_chunk == (index + 1) << level, "the children are not siblings: {left:?} and {right:?}");
1062        LastCv { value: self.bare_parent_cv(&left.value, &right.value), first_chunk: index << level, len: (CHUNK << level) + right.len }
1063    }
1064
1065    /// A layer of parents: `out[i]` becomes the parent of `children[2 * i]`
1066    /// and `children[2 * i + 1]`, side by side in the CPU's lanes.
1067    ///
1068    /// The places cost 3 to 5 ns a parent over its hashing (the values are
1069    /// gathered for the kernels and labelled after): 2% of `b3sum
1070    /// --outboard` on a 1 GiB file in memory (Ryzen 9700X), which makes a
1071    /// parent for every 16 KiB.
1072    ///
1073    /// Requires an even number of children, half as many outputs, and the
1074    /// children consecutive whole subtrees of one size from an even index,
1075    /// checked in every build.
1076    pub fn parent_cvs(&self, children: &[Cv], out: &mut [Cv]) {
1077        assert_eq!(children.len() % 2, 0, "parents take their children in pairs");
1078        assert_eq!(out.len(), children.len() / 2, "one parent per pair of children");
1079        let Some(first) = children.first() else { return };
1080        let base = first.set();
1081        assert!(base & 1 == 0, "the first child is at an odd index: {first:?}");
1082        for (k, child) in children.iter().enumerate() {
1083            assert!(child.place == base + k as u64, "child {k} is not the next subtree of its size: {child:?}");
1084        }
1085        // The kernels read bare values side by side: gather, hash, label.
1086        // 32 children are the widest kernel's two rounds, and the two
1087        // arrays are 1.5 KiB of the stack.
1088        const PAIRS: usize = 16;
1089        // Take the shared accelerator's turn once for an eligible layer
1090        // (32 children = 16 pairs or more: one full SME2 parent group).
1091        let turn = self.turn_if(children.len() >= 32);
1092        let platform = turn.platform();
1093        let mut values = [[0u8; OUT_LEN]; 2 * PAIRS];
1094        let mut parents = [[0u8; OUT_LEN]; PAIRS];
1095        for (children, out) in children.chunks(2 * PAIRS).zip(out.chunks_mut(PAIRS)) {
1096            for (value, child) in values.iter_mut().zip(children) {
1097                *value = child.value;
1098            }
1099            self.bare_parent_cvs_on(platform, &values[..children.len()], &mut parents[..out.len()]);
1100            for (i, parent) in out.iter_mut().enumerate() {
1101                *parent = Cv { value: parents[i], place: parent_place(children[2 * i].place) };
1102            }
1103        }
1104    }
1105
1106    /// The root's two children, checked: `left` begins the message,
1107    /// `right` begins where it ends, and the two hold `len` bytes.
1108    fn root_children(left: &Cv, right: &LastCv, len: u64) {
1109        let (level, index) = (left.level(), left.index());
1110        assert!(index == 0 && right.first_chunk == 1 << level, "not a root's children: {left:?} and {right:?}");
1111        let held = (CHUNK << level) + right.len;
1112        assert!(held == len, "the root's children hold {held} bytes, and the message {len}");
1113    }
1114
1115    /// The hash of the message of `len` bytes whose root has these two
1116    /// children: the tree's top, where the chaining values end.
1117    ///
1118    /// Requires `left` at the message's start, `right` beginning where it
1119    /// ends, and the two holding `len` bytes, checked in every build: a
1120    /// tree that leaves out the message's end is refused, where it would
1121    /// give the hash of the bytes before it.
1122    pub fn root_hash(&self, left: &Cv, right: &LastCv, len: u64) -> Hash {
1123        Self::root_children(left, right, len);
1124        self.bare_root_hash(&left.value, &right.value)
1125    }
1126
1127    /// The extended output of the message of `len` bytes whose root has
1128    /// these two children: its first 32 bytes are
1129    /// [`root_hash`](TreeHasher::root_hash)'s.
1130    ///
1131    /// Requires what `root_hash` does.
1132    pub fn root_output(&self, left: &Cv, right: &LastCv, len: u64) -> crate::OutputReader {
1133        Self::root_children(left, right, len);
1134        self.bare_root_output(&left.value, &right.value)
1135    }
1136}
1137
1138/// The bytes of the left subtree of a message, or of a subtree, of `len`
1139/// bytes: the largest power of two of chunks below its chunk count. The
1140/// right subtree holds the rest.
1141///
1142/// Requires more than one chunk: a chunk or less does not split.
1143pub const fn left_len(len: u64) -> u64 {
1144    assert!(len > CHUNK_LEN as u64, "a chunk or less does not split");
1145    let chunks = (len - 1) / CHUNK_LEN as u64;
1146    (1u64 << (u64::BITS - 1 - chunks.leading_zeros())) * CHUNK_LEN as u64
1147}
1148
1149#[cfg(test)]
1150mod tree_test {
1151    use super::*;
1152    use std::vec::Vec;
1153
1154    /// Official BLAKE3's hazmat: the independent implementation of the
1155    /// tree's pieces.
1156    mod official {
1157        pub(super) use crate::test::official::parent;
1158        use blake3::hazmat::HasherExt;
1159        pub(super) fn hasher(mode: crate::Mode) -> blake3::Hasher {
1160            match mode {
1161                crate::Mode::Plain => blake3::Hasher::new(),
1162                crate::Mode::Keyed(key) => blake3::Hasher::new_keyed(key),
1163                crate::Mode::DeriveKey(context) => blake3::Hasher::new_derive_key(context),
1164                crate::Mode::DeriveKeyWith(_) => unreachable!("the tests derive from a context string"),
1165            }
1166        }
1167        pub(super) fn subtree_cv(mode: crate::Mode, first_chunk: u64, input: &[u8]) -> [u8; 32] {
1168            let mut hasher = hasher(mode);
1169            hasher.set_input_offset(first_chunk * 1024);
1170            hasher.update(input);
1171            hasher.finalize_non_root()
1172        }
1173    }
1174
1175    const KEY: [u8; 32] = [0x6b; 32];
1176
1177    fn modes() -> [Mode<'static>; 3] {
1178        [Mode::Plain, Mode::Keyed(&KEY), Mode::DeriveKey("blake3-servil tree api test")]
1179    }
1180
1181    fn painted(len: usize) -> Vec<u8> {
1182        let mut input = std::vec![0u8; len];
1183        crate::test::paint_test_input(&mut input);
1184        input
1185    }
1186
1187    /// A subtree's chaining value, at every kind of place and length: at
1188    /// chunk zero and at offsets whose alignment allows 1, 2, 4, 8, 16 and
1189    /// many chunks, low and beyond 2^32 chunks; lengths around a block, a
1190    /// chunk, a group of sixteen and powers of two up to what the place
1191    /// allows; in each mode, with the shared accelerator and on this core.
1192    /// Against official BLAKE3's hazmat.
1193    #[test]
1194    fn a_subtrees_chaining_value_matches_official_blake3_at_every_place() {
1195        crate::initialize();
1196        let input = painted(70 * CHUNK_LEN + 100);
1197        let mut checked = 0;
1198        for mode in modes() {
1199            for tree in [TreeHasher::new(mode), TreeHasher::new(mode).on_this_core()] {
1200                for first_chunk in [0u64, 1, 2, 4, 6, 8, 16, 48, 64, 1 << 20, (1 << 33) + 4, 3 << 40] {
1201                    let max = if first_chunk == 0 { input.len() } else { ((1u64 << first_chunk.trailing_zeros()) as usize * CHUNK_LEN).min(70 * CHUNK_LEN) };
1202                    for len in [
1203                        1,
1204                        63,
1205                        64,
1206                        65,
1207                        1023,
1208                        1024,
1209                        1025,
1210                        2047,
1211                        2048,
1212                        2049,
1213                        4096,
1214                        5000,
1215                        8 * 1024,
1216                        16 * 1024 - 1,
1217                        16 * 1024,
1218                        16 * 1024 + 1,
1219                        33 * 1024 - 5,
1220                        64 * 1024,
1221                        70 * 1024,
1222                    ] {
1223                        if len > max {
1224                            continue;
1225                        }
1226                        let bytes = &input[100..100 + len];
1227                        checked += 1;
1228                        let want = official::subtree_cv(mode, first_chunk, bytes);
1229                        assert_eq!(*tree.last_cv(first_chunk, bytes).as_bytes(), want, "first_chunk={first_chunk} len={len}");
1230                        if len > CHUNK_LEN {
1231                            let turn = tree.turn(len);
1232                            let [left, right] = tree.halves_on(turn.platform(), first_chunk, bytes);
1233                            assert_eq!(tree.bare_parent_cv(&left, &right), want, "the halves' parent, first_chunk={first_chunk} len={len}");
1234                            let split = left_len(len as u64) as usize;
1235                            assert_eq!(left, official::subtree_cv(mode, first_chunk, &bytes[..split]), "the left half, first_chunk={first_chunk} len={len}");
1236                            assert_eq!(
1237                                right,
1238                                official::subtree_cv(mode, first_chunk + (split / CHUNK_LEN) as u64, &bytes[split..]),
1239                                "the right half, first_chunk={first_chunk} len={len}"
1240                            );
1241                        }
1242                    }
1243                }
1244            }
1245        }
1246        // The 19 lengths where the place allows them all, fewer at the
1247        // narrower places: 164 a mode and tree.
1248        assert_eq!(checked, 3 * 2 * 164, "the places and lengths checked");
1249    }
1250
1251    #[test]
1252    fn whole_subtree_halves_keep_their_places_and_values() {
1253        crate::initialize();
1254        let input = painted(64 * CHUNK_LEN);
1255        for mode in modes() {
1256            for tree in [TreeHasher::new(mode), TreeHasher::new(mode).on_this_core()] {
1257                for (level, index) in [(1, 0), (2, 3), (5, 7), (6, (1 << 30) + 1)] {
1258                    let bytes = &input[..CHUNK_LEN << level];
1259                    let (head, tail) = bytes.split_at(bytes.len() / 2);
1260                    let first = index << level;
1261                    let want_left = official::subtree_cv(mode, first, head);
1262                    let want_right = official::subtree_cv(mode, first + (head.len() / CHUNK_LEN) as u64, tail);
1263                    assert_eq!(
1264                        tree.subtree_halves(level, index, bytes),
1265                        [Cv::at(level - 1, 2 * index, want_left), Cv::at(level - 1, 2 * index + 1, want_right)]
1266                    );
1267                }
1268            }
1269        }
1270    }
1271
1272    /// A parent and the root from two chaining values, against official
1273    /// BLAKE3's merges; the root's extended output begins with its hash;
1274    /// and a layer of parents is each pair's parent, at every count around
1275    /// the kernels' widths.
1276    #[test]
1277    fn parents_and_the_root_match_official_blake3() {
1278        crate::initialize();
1279        let bytes = painted(32 * 300);
1280        let cvs: Vec<crate::CVBytes> = bytes.as_chunks::<32>().0.to_vec();
1281        for mode in modes() {
1282            let tree = TreeHasher::new(mode);
1283            for pair in cvs[..40].chunks(2) {
1284                let (left, right) = (&pair[0], &pair[1]);
1285                assert_eq!(tree.bare_parent_cv(left, right), official::parent(mode, left, right, false));
1286                assert_eq!(*tree.bare_root_hash(left, right).as_bytes(), official::parent(mode, left, right, true));
1287                let mut out = [0u8; 150];
1288                tree.bare_root_output(left, right).fill(&mut out);
1289                assert_eq!(out[..32], *tree.bare_root_hash(left, right).as_bytes());
1290                assert_ne!(&tree.bare_parent_cv(left, right), tree.bare_root_hash(left, right).as_bytes(), "the root is not a chaining value");
1291            }
1292            for pairs in (0..=40).chain([63, 64, 65, 127, 128, 129, 150]) {
1293                let children = &cvs[..2 * pairs];
1294                let mut out = std::vec![[0u8; 32]; pairs];
1295                tree.bare_parent_cvs_on(tree.platform(), children, &mut out);
1296                for (i, got) in out.iter().enumerate() {
1297                    assert_eq!(*got, tree.bare_parent_cv(&children[2 * i], &children[2 * i + 1]), "pair {i} of {pairs}");
1298                }
1299            }
1300        }
1301    }
1302
1303    /// A whole message's hash built the way a tree builder builds it:
1304    /// split at `left_len` down to groups of sixteen chunks, each group's
1305    /// chaining value, each parent, and the root from its two children.
1306    /// And its extended output, against the Hasher's.
1307    #[test]
1308    fn a_tree_built_from_its_pieces_gives_the_messages_hash() {
1309        crate::initialize();
1310        fn cv(tree: &TreeHasher, input: &[u8], first_chunk: u64) -> crate::CVBytes {
1311            if input.len() <= 16 * CHUNK_LEN {
1312                return tree.last_cv(first_chunk, input).value;
1313            }
1314            let split = left_len(input.len() as u64) as usize;
1315            let left = cv(tree, &input[..split], first_chunk);
1316            let right = cv(tree, &input[split..], first_chunk + (split / CHUNK_LEN) as u64);
1317            tree.bare_parent_cv(&left, &right)
1318        }
1319        let input = painted((1 << 20) + 7);
1320        for mode in modes() {
1321            let tree = TreeHasher::new(mode).on_this_core();
1322            for len in [1025, 2048, 5000, 16 * 1024, 16 * 1024 + 1, 100_000, 1 << 19, (1 << 19) + 1, (1 << 20) + 7] {
1323                let message = &input[..len];
1324                let split = left_len(len as u64) as usize;
1325                let left = cv(&tree, &message[..split], 0);
1326                let right = cv(&tree, &message[split..], (split / CHUNK_LEN) as u64);
1327                assert_eq!(*tree.bare_root_hash(&left, &right).as_bytes(), crate::test::official::hash(mode, message), "len={len}");
1328                let mut out = [0u8; 200];
1329                tree.bare_root_output(&left, &right).fill(&mut out);
1330                assert_eq!(out.as_slice(), crate::test::official::xof(mode, message, 0, out.len()), "len={len}");
1331            }
1332        }
1333    }
1334
1335    /// Where a message splits, against official BLAKE3's, at every length
1336    /// around each power of two of chunks up to 2^40.
1337    #[test]
1338    fn left_len_is_official_blake3s() {
1339        for power in 0..=40u32 {
1340            let chunks = 1u64 << power;
1341            for len in [chunks * 1024 - 1, chunks * 1024, chunks * 1024 + 1, chunks * 1024 + 1024, chunks * 1536] {
1342                if len > CHUNK_LEN as u64 {
1343                    assert_eq!(left_len(len), blake3::hazmat::left_subtree_len(len), "len={len}");
1344                }
1345            }
1346        }
1347    }
1348
1349    #[test]
1350    #[should_panic(expected = "a chunk or less does not split")]
1351    fn left_len_requires_more_than_a_chunk() {
1352        left_len(1024);
1353    }
1354
1355    #[test]
1356    #[should_panic(expected = "the last subtree at chunk 0 holds 1 to")]
1357    fn a_subtree_is_not_empty() {
1358        crate::initialize();
1359        TreeHasher::new(Mode::Plain).last_cv(0, &[]);
1360    }
1361
1362    #[test]
1363    #[should_panic(expected = "the last subtree at chunk 6 holds 1 to 2048 bytes (found 2049)")]
1364    fn a_subtree_is_no_longer_than_its_place_allows() {
1365        crate::initialize();
1366        TreeHasher::new(Mode::Plain).last_cv(6, &[0; 2049]);
1367    }
1368
1369    #[test]
1370    #[should_panic(expected = "a subtree of one chunk has no halves")]
1371    fn the_halves_of_a_chunk_do_not_exist() {
1372        crate::initialize();
1373        TreeHasher::new(Mode::Plain).subtree_halves(0, 0, &[0; 1024]);
1374    }
1375
1376    #[test]
1377    #[should_panic(expected = "a whole subtree at level 1 holds 2048 bytes (found 2047)")]
1378    fn halves_need_the_whole_subtree() {
1379        crate::initialize();
1380        TreeHasher::new(Mode::Plain).subtree_halves(1, 0, &[0; 2047]);
1381    }
1382
1383    #[test]
1384    #[should_panic(expected = "parents take their children in pairs")]
1385    fn a_layer_of_parents_takes_pairs() {
1386        crate::initialize();
1387        let cvs = [[1u8; 32]; 3];
1388        let tree = TreeHasher::new(Mode::Plain);
1389        tree.bare_parent_cvs_on(tree.platform(), &cvs, &mut [[0u8; 32]]);
1390    }
1391
1392    #[test]
1393    #[should_panic(expected = "one parent per pair of children")]
1394    fn a_layer_of_parents_takes_one_output_a_pair() {
1395        crate::initialize();
1396        let cvs = [[1u8; 32]; 4];
1397        let tree = TreeHasher::new(Mode::Plain);
1398        tree.bare_parent_cvs_on(tree.platform(), &cvs, &mut [[0u8; 32]]);
1399    }
1400
1401    /// The hash of a whole message, a batch and a collection in a prepared
1402    /// mode: official BLAKE3's hashes, in each mode, with the shared
1403    /// accelerator and on this core, at lengths from empty to past the
1404    /// accelerator's size and the batch sizes its turn starts at.
1405    #[test]
1406    fn a_whole_message_a_batch_and_a_collection_match_official_blake3() {
1407        crate::initialize();
1408        let input = painted(40 * CHUNK_LEN + 7);
1409        let lens = [0, 1, 63, 64, 65, 1023, 1024, 1025, 2048, 3 * 1024 + 5, 15 * 1024, 16 * 1024 - 1, 16 * 1024, 16 * 1024 + 1, 40 * 1024 + 7];
1410        for mode in modes() {
1411            let want = |message: &[u8]| *official::hasher(mode).update(message).finalize().as_bytes();
1412            for tree in [TreeHasher::new(mode), TreeHasher::new(mode).on_this_core()] {
1413                for len in lens {
1414                    assert_eq!(*tree.hash(&input[..len]).as_bytes(), want(&input[..len]), "a message of {len} bytes");
1415                }
1416                // Batches: one message and many, a block or less, a chunk
1417                // or less, several chunks, and the accelerator's size.
1418                for (len, count) in [(1, 1), (32, 300), (64, 3), (64, 40), (100, 17), (1024, 9), (5000, 4), (5000, 20), (16 * 1024, 2)] {
1419                    let mut batch = Batch::new(len, count);
1420                    for i in 0..count {
1421                        batch.set(i, &input[i..i + len]);
1422                    }
1423                    let mut out = std::vec![[0u8; 32]; count];
1424                    tree.hash_many(&batch, &mut out);
1425                    for (i, digest) in out.iter().enumerate() {
1426                        assert_eq!(*digest, want(&input[i..i + len]), "message {i} of {count} of {len} bytes");
1427                    }
1428                }
1429                let mut packed = Packed::<32>::new(50);
1430                for (i, message) in packed.iter_mut().enumerate() {
1431                    message.copy_from_slice(&input[i..i + 32]);
1432                }
1433                let mut out = std::vec![[0u8; 32]; 50];
1434                tree.hash_many(&packed, &mut out);
1435                for (i, digest) in out.iter().enumerate() {
1436                    assert_eq!(*digest, want(&input[i..i + 32]), "packed message {i}");
1437                }
1438                // A collection of every length above, twice over, so the
1439                // short ones go by their blocks and the middle ones share
1440                // lanes.
1441                let blocks: Vec<Vec<Block>> = lens
1442                    .iter()
1443                    .chain(&lens)
1444                    .map(|&len| {
1445                        let mut blocks = std::vec![Block([0; 64]); len.div_ceil(64)];
1446                        Block::bytes_mut(&mut blocks)[..len].copy_from_slice(&input[..len]);
1447                        blocks
1448                    })
1449                    .collect();
1450                let items: Vec<(&[Block], usize)> = blocks.iter().zip(lens.iter().chain(&lens)).map(|(b, &len)| (&b[..], len)).collect();
1451                let mut out = std::vec![[0u8; 32]; items.len()];
1452                tree.hash_each(&items, &mut out);
1453                for (digest, &len) in out.iter().zip(lens.iter().chain(&lens)) {
1454                    assert_eq!(*digest, want(&input[..len]), "an item of {len} bytes");
1455                }
1456            }
1457        }
1458    }
1459
1460    #[test]
1461    #[should_panic(expected = "one digest per item")]
1462    fn a_collection_takes_one_output_an_item() {
1463        crate::initialize();
1464        let block = [Block([0; 64])];
1465        TreeHasher::new(Mode::Plain).hash_each(&[(&block[..], 3), (&block[..], 4)], &mut [[0u8; 32]]);
1466    }
1467
1468    /// A batch's parts hash as the batch does, for messages in blocks and
1469    /// packed ones, at every cut; and the caller's kernels, named, give
1470    /// the subtree's own chaining value.
1471    #[test]
1472    fn a_batchs_parts_hash_as_the_batch_does() {
1473        crate::initialize();
1474        let input = painted(64 * 1024);
1475        let tree = TreeHasher::new(Mode::Keyed(&KEY));
1476        let mut batch = Batch::new(100, 9);
1477        let mut packed = Packed::<16>::new(9);
1478        for i in 0..9 {
1479            batch.set(i, &input[i..i + 100]);
1480            packed[i].copy_from_slice(&input[i..i + 16]);
1481        }
1482        let (mut whole, mut whole_packed) = ([[0u8; 32]; 9], [[0u8; 32]; 9]);
1483        tree.hash_many(&batch, &mut whole);
1484        tree.hash_many(&packed, &mut whole_packed);
1485        for cut in 0..=9 {
1486            let (mut parts, mut parts_packed) = ([[0u8; 32]; 9], [[0u8; 32]; 9]);
1487            tree.hash_many(&batch.part(0..cut), &mut parts[..cut]);
1488            tree.hash_many(&batch.part(cut..9), &mut parts[cut..]);
1489            tree.hash_many(&packed.part(0..cut), &mut parts_packed[..cut]);
1490            // A part of a part counts from the part's first message.
1491            tree.hash_many(&packed.part(1.min(cut)..9).part(cut - 1.min(cut)..9 - 1.min(cut)), &mut parts_packed[cut..]);
1492            assert_eq!((whole, whole_packed), (parts, parts_packed), "cut at {cut}");
1493        }
1494        for level in [0, 1, 4, 6] {
1495            let len = 1024 << level;
1496            // Chunk 64 is the place of index `64 >> level` at every level here.
1497            let turn = crate::platform::Sme2Turn::acquire();
1498            let under = tree.subtree_cv_under(&turn, level, 64 >> level, &input[..len]);
1499            let pinned = tree.clone().on_this_core().subtree_cv_under(&turn, level, 64 >> level, &input[..len]);
1500            drop(turn);
1501            assert!(under == pinned, "pinned subtree_cv_under matches unpinned at {len} bytes");
1502            assert!(under == tree.subtree_cv(level, 64 >> level, &input[..len]), "{len} bytes");
1503            assert_eq!(*under.as_bytes(), official::subtree_cv(Mode::Keyed(&KEY), 64, &input[..len]), "{len} bytes");
1504        }
1505        // `subtree_cv_under` enforces the exact same subtree length/place checks as `subtree_cv`.
1506        {
1507            let turn = crate::platform::Sme2Turn::acquire();
1508            assert!(
1509                std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| tree.subtree_cv_under(&turn, 3, 0, &input[..7 * 1024]))).is_err(),
1510                "subtree_cv_under must reject a short subtree"
1511            );
1512        }
1513        // On SME2 hosts, verify `subtree_cv_under` dispatches SME2 only when
1514        // unpinned and holding a granted turn, and stays on NEON when pinned
1515        // via `on_this_core()` or given a contended turn (#460).
1516        #[cfg(target_arch = "aarch64")]
1517        if matches!(crate::platform::Platform::detect(), crate::platform::Platform::SME2) {
1518            let sme2_entries: std::vec::Vec<usize> = crate::sme2::entries().into_iter().map(|(_, p)| p as usize).collect();
1519            let ran_sme2 = || crate::RAN_ENTRIES.with(|e| e.borrow().iter().any(|p| sme2_entries.contains(p)));
1520            let turn = crate::platform::Sme2Turn::acquire();
1521            assert!(turn.is_sme2());
1522            crate::RAN_ENTRIES.with(|e| e.borrow_mut().clear());
1523            let _ = tree.subtree_cv_under(&turn, 6, 0, &input[..64 * 1024]);
1524            assert!(ran_sme2(), "unpinned subtree_cv_under with granted turn must use SME2");
1525
1526            crate::RAN_ENTRIES.with(|e| e.borrow_mut().clear());
1527            let _ = tree.clone().on_this_core().subtree_cv_under(&turn, 6, 0, &input[..64 * 1024]);
1528            assert!(!ran_sme2(), "on_this_core().subtree_cv_under must stay on NEON");
1529
1530            let contended = crate::platform::Sme2Turn::acquire();
1531            assert!(!contended.is_sme2());
1532            crate::RAN_ENTRIES.with(|e| e.borrow_mut().clear());
1533            let _ = tree.subtree_cv_under(&contended, 6, 0, &input[..64 * 1024]);
1534            assert!(!ran_sme2(), "subtree_cv_under with contended turn must stay on NEON");
1535            drop(contended);
1536            drop(turn);
1537        }
1538    }
1539
1540    #[test]
1541    #[should_panic(expected = "lies within the batch")]
1542    fn a_part_lies_within_its_batch() {
1543        let batch = Batch::new(100, 9);
1544        let _ = batch.part(3..10);
1545    }
1546
1547    #[test]
1548    #[should_panic(expected = "lies within the batch")]
1549    fn a_part_runs_forward() {
1550        let batch = Batch::new(100, 9);
1551        #[allow(clippy::reversed_empty_ranges)]
1552        let _ = batch.part(3..2);
1553    }
1554
1555    #[cfg(target_arch = "aarch64")]
1556    #[test]
1557    fn parent_cvs_and_hash_each_honor_a_held_sme2_turn() {
1558        crate::initialize();
1559        if !matches!(crate::platform::Platform::detect(), crate::platform::Platform::SME2) {
1560            return;
1561        }
1562        let tree = TreeHasher::new(Mode::Plain);
1563        // 32 leaf CVs -> 16 parent pairs (one full SME2 parent group).
1564        let input = painted(32 * CHUNK_LEN);
1565        let children: std::vec::Vec<Cv> = (0..32).map(|i| tree.subtree_cv(0, i as u64, &input[i * CHUNK_LEN..(i + 1) * CHUNK_LEN])).collect();
1566        let mut expected_parents = std::vec![Cv::unset(); 16];
1567        tree.clone().on_this_core().parent_cvs(&children, &mut expected_parents);
1568
1569        // 16 distinct two-chunk messages -> one full SME2 message group per round.
1570        let mut blocks = Batch::new(2 * CHUNK_LEN, 16);
1571        for i in 0..16 {
1572            blocks.message_mut(i).copy_from_slice(&input[i * 37..i * 37 + 2 * CHUNK_LEN]);
1573        }
1574        let items: std::vec::Vec<(&[Block], usize)> = (0..16).map(|i| (&blocks.blocks()[i * 32..(i + 1) * 32], 2 * CHUNK_LEN)).collect();
1575        let mut expected_each = std::vec![[0u8; OUT_LEN]; 16];
1576        tree.clone().on_this_core().hash_each(&items, &mut expected_each);
1577        // Few-message parent-round boundary: 3 x 15 KiB = 21 pairs (>= 16),
1578        // 2 x 15 KiB + 1 x 4 KiB = 16 pairs (exact threshold), and
1579        // 3 x 11 KiB = 15 pairs (< 16, must not contend for SME2 turn).
1580        let big_raw: std::vec::Vec<std::vec::Vec<u8>> = (0..3).map(|k| (0..15 * CHUNK_LEN).map(|i| ((i + k * 29) & 0xff) as u8).collect()).collect();
1581        let big_slices: std::vec::Vec<&[u8]> = big_raw.iter().map(|v| v.as_slice()).collect();
1582        let big_blocks = crate::test::messages(&big_slices);
1583        let items_3x15k: std::vec::Vec<(&[Block], usize)> = big_blocks.iter().map(|b| (b.as_slice(), 15 * CHUNK_LEN)).collect();
1584        let items_16_pairs: std::vec::Vec<(&[Block], usize)> =
1585            std::vec![(big_blocks[0].as_slice(), 15 * CHUNK_LEN), (big_blocks[1].as_slice(), 15 * CHUNK_LEN), (&big_blocks[2][..64], 4 * CHUNK_LEN)];
1586        let items_15_pairs: std::vec::Vec<(&[Block], usize)> = std::vec![
1587            (&big_blocks[0][..176], 11 * CHUNK_LEN),
1588            (&big_blocks[1][..176], 11 * CHUNK_LEN),
1589            (&big_blocks[2][..176], 11 * CHUNK_LEN),
1590            (&big_blocks[0][..32], 2 * CHUNK_LEN),
1591        ];
1592        let mut expected_3x15k = [[0u8; OUT_LEN]; 3];
1593        let mut expected_16_pairs = [[0u8; OUT_LEN]; 3];
1594        let mut expected_15_pairs = [[0u8; OUT_LEN]; 4];
1595        tree.clone().on_this_core().hash_each(&items_3x15k, &mut expected_3x15k);
1596        tree.clone().on_this_core().hash_each(&items_16_pairs, &mut expected_16_pairs);
1597        tree.clone().on_this_core().hash_each(&items_15_pairs, &mut expected_15_pairs);
1598        let tmpl = [0x5au8; 52];
1599        let mut expected_counter = std::vec![[0u8; OUT_LEN]; 18];
1600        tree.clone().on_this_core().hash_counter_range(&tmpl, 12, 7, &mut expected_counter);
1601        let chain_init: [[u8; 32]; 18] = core::array::from_fn(|i| [0x33u8.wrapping_add(i as u8); 32]);
1602        let mut got_chain = [[0u8; 16]; 18];
1603        let mut expected_chain = [[0u8; 16]; 18];
1604        tree.clone().on_this_core().hash_chains_32_trunc16(&chain_init, 3, &mut expected_chain);
1605        let chain_steps_small = [63u32; 18]; // 1134 < 1152 (SME2_VARLEN_MIN_WORK)
1606        let chain_steps_large = [64u32; 18]; // 1152 == SME2_VARLEN_MIN_WORK
1607        let mut expected_chain_large = [[0u8; 16]; 18];
1608        tree.clone().on_this_core().hash_chains_varlen_32_trunc16(&chain_init, &chain_steps_large, &mut expected_chain_large);
1609
1610        // Hold the SME2 turn: neither parent_cvs, hash_each, nor counter-range/find may enter SME2.
1611        let mut held = None;
1612        for _ in 0..10_000 {
1613            let t = crate::platform::Sme2Turn::take(crate::platform::Platform::SME2, true);
1614            if matches!(t.platform(), crate::platform::Platform::SME2) {
1615                held = Some(t);
1616                break;
1617            }
1618            std::thread::yield_now();
1619        }
1620        let held = held.expect("failed to acquire SME2 turn within bounded retries");
1621        let parents_fn = crate::sme2::ffi::blake3_servil_sme2_hash16_parents_512 as *const () as usize;
1622        let messages_fn = crate::sme2::ffi::blake3_servil_sme2_hash16_messages_512 as *const () as usize;
1623
1624        // Subthreshold calls (30 children = 15 pairs; 15 two-chunk messages; 17 counters) must
1625        // not even attempt to acquire the held turn (Ran::TurnTaken stays clear).
1626        let mut got_parents = std::vec![Cv::unset(); 16];
1627        let mut got_each = std::vec![[0u8; OUT_LEN]; 16];
1628        let mut got_counter = std::vec![[0u8; OUT_LEN]; 18];
1629        let mut got_counter16 = std::vec![[0u8; 16]; 18];
1630        let mut got_find = [(0u32, [0u8; OUT_LEN]); 1];
1631        crate::RAN.with(|r| r.set(0));
1632        crate::RAN_ENTRIES.with(|r| r.borrow_mut().clear());
1633        tree.parent_cvs(&children[..30], &mut got_parents[..15]);
1634        assert_eq!(crate::RAN.with(|r| r.get()) & crate::Ran::TurnTaken as u32, 0, "15 parent pairs must not try to take the SME2 turn");
1635        tree.hash_each(&items[..15], &mut got_each[..15]);
1636        assert_eq!(crate::RAN.with(|r| r.get()) & crate::Ran::TurnTaken as u32, 0, "15 two-chunk messages must not try to take the SME2 turn");
1637        let mut got_3 = [[0u8; OUT_LEN]; 3];
1638        let mut got_4 = [[0u8; OUT_LEN]; 4];
1639        tree.hash_each(&items_15_pairs, &mut got_4);
1640        assert_eq!(
1641            crate::RAN.with(|r| r.get()) & crate::Ran::TurnTaken as u32,
1642            0,
1643            "3 x 11 KiB + 1 x 2 KiB (15 parent pairs) must not try to take the SME2 turn"
1644        );
1645        assert_eq!(got_4, expected_15_pairs);
1646        tree.hash_counter_range(&tmpl, 12, 7, &mut got_counter[..17]);
1647        assert_eq!(crate::RAN.with(|r| r.get()) & crate::Ran::TurnTaken as u32, 0, "17 TreeHasher counters must not try to take the SME2 turn");
1648        assert_eq!(&got_counter[..17], &expected_counter[..17]);
1649        hash_counter_range(Mode::Plain, &tmpl, 12, 7, &mut got_counter[..17]);
1650        assert_eq!(crate::RAN.with(|r| r.get()) & crate::Ran::TurnTaken as u32, 0, "17 free counters must not try to take the SME2 turn");
1651        tree.hash_counter_range_trunc16(&tmpl, 12, 7, &mut got_counter16[..17]);
1652        assert_eq!(crate::RAN.with(|r| r.get()) & crate::Ran::TurnTaken as u32, 0, "17 TreeHasher trunc16 counters must not try to take the SME2 turn");
1653        hash_counter_range_trunc16(Mode::Plain, &tmpl, 12, 7, &mut got_counter16[..17]);
1654        assert_eq!(crate::RAN.with(|r| r.get()) & crate::Ran::TurnTaken as u32, 0, "17 free trunc16 counters must not try to take the SME2 turn");
1655        let _ = tree.find_counter_range(&tmpl, 12, 7, 17, u32::MAX, 0, &mut got_find);
1656        assert_eq!(crate::RAN.with(|r| r.get()) & crate::Ran::TurnTaken as u32, 0, "17 TreeHasher find counters must not try to take the SME2 turn");
1657        let _ = find_counter_range(Mode::Plain, &tmpl, 12, 7, 17, u32::MAX, 0, &mut got_find);
1658        assert_eq!(crate::RAN.with(|r| r.get()) & crate::Ran::TurnTaken as u32, 0, "17 free find counters must not try to take the SME2 turn");
1659        tree.hash_chains_32_trunc16(&chain_init[..17], 3, &mut got_chain[..17]);
1660        assert_eq!(crate::RAN.with(|r| r.get()) & crate::Ran::TurnTaken as u32, 0, "17 fixed chains must not try to take the SME2 turn");
1661        tree.hash_chains_32_trunc16(&chain_init, 0, &mut got_chain);
1662        assert_eq!(crate::RAN.with(|r| r.get()) & crate::Ran::TurnTaken as u32, 0, "0-step fixed chains must not try to take the SME2 turn");
1663        tree.hash_chains_varlen_32_trunc16(&chain_init, &chain_steps_small, &mut got_chain);
1664        assert_eq!(crate::RAN.with(|r| r.get()) & crate::Ran::TurnTaken as u32, 0, "subthreshold varlen chains must not try to take the SME2 turn");
1665        assert_eq!(&got_parents[..15], &expected_parents[..15]);
1666        assert_eq!(&got_each[..15], &expected_each[..15]);
1667        assert_eq!(&got_counter[..17], &expected_counter[..17]);
1668
1669        // Eligible calls (32 children = 16 pairs; 16 two-chunk messages; 18 counters) DO consult
1670        // the held turn (recording Ran::TurnTaken) and fall back off SME2.
1671        crate::RAN.with(|r| r.set(0));
1672        crate::RAN_ENTRIES.with(|r| r.borrow_mut().clear());
1673        tree.parent_cvs(&children, &mut got_parents);
1674        assert_ne!(crate::RAN.with(|r| r.get()) & crate::Ran::TurnTaken as u32, 0, "16 parent pairs must consult the SME2 turn");
1675        crate::RAN.with(|r| r.set(0));
1676        tree.hash_each(&items, &mut got_each);
1677        assert_ne!(crate::RAN.with(|r| r.get()) & crate::Ran::TurnTaken as u32, 0, "16 two-chunk messages must consult the SME2 turn");
1678        crate::RAN.with(|r| r.set(0));
1679        tree.hash_each(&items_16_pairs, &mut got_3);
1680        assert_ne!(crate::RAN.with(|r| r.get()) & crate::Ran::TurnTaken as u32, 0, "16 first-round parent pairs must consult the SME2 turn");
1681        assert_eq!(got_3, expected_16_pairs);
1682        crate::RAN.with(|r| r.set(0));
1683        tree.hash_each(&items_3x15k, &mut got_3);
1684        assert_ne!(crate::RAN.with(|r| r.get()) & crate::Ran::TurnTaken as u32, 0, "3 x 15 KiB (21 parent pairs) must consult the SME2 turn");
1685        assert_eq!(got_3, expected_3x15k);
1686        crate::RAN.with(|r| r.set(0));
1687        tree.hash_counter_range(&tmpl, 12, 7, &mut got_counter);
1688        assert_ne!(crate::RAN.with(|r| r.get()) & crate::Ran::TurnTaken as u32, 0, "18 TreeHasher counters must consult the SME2 turn");
1689        assert_eq!(got_counter, expected_counter);
1690        crate::RAN.with(|r| r.set(0));
1691        tree.hash_chains_32_trunc16(&chain_init, 3, &mut got_chain);
1692        assert_ne!(crate::RAN.with(|r| r.get()) & crate::Ran::TurnTaken as u32, 0, "18 fixed chains must consult the SME2 turn");
1693        assert_eq!(got_chain, expected_chain);
1694        crate::RAN.with(|r| r.set(0));
1695        hash_chains_32_trunc16(Mode::Plain, &chain_init, 3, &mut got_chain);
1696        assert_ne!(crate::RAN.with(|r| r.get()) & crate::Ran::TurnTaken as u32, 0, "18 free fixed chains must consult the SME2 turn");
1697        assert_eq!(got_chain, expected_chain);
1698        crate::RAN.with(|r| r.set(0));
1699        tree.hash_chains_varlen_32_trunc16(&chain_init, &chain_steps_large, &mut got_chain);
1700        assert_ne!(crate::RAN.with(|r| r.get()) & crate::Ran::TurnTaken as u32, 0, "eligible varlen chains must consult the SME2 turn");
1701        assert_eq!(got_chain, expected_chain_large);
1702        crate::RAN.with(|r| r.set(0));
1703        hash_counter_range(Mode::Plain, &tmpl, 12, 7, &mut got_counter);
1704        assert_ne!(crate::RAN.with(|r| r.get()) & crate::Ran::TurnTaken as u32, 0, "18 free counters must consult the SME2 turn");
1705        assert_eq!(got_counter, expected_counter);
1706        crate::RAN.with(|r| r.set(0));
1707        tree.hash_counter_range_trunc16(&tmpl, 12, 7, &mut got_counter16);
1708        assert_ne!(crate::RAN.with(|r| r.get()) & crate::Ran::TurnTaken as u32, 0, "18 TreeHasher trunc16 counters must consult the SME2 turn");
1709        crate::RAN.with(|r| r.set(0));
1710        hash_counter_range_trunc16(Mode::Plain, &tmpl, 12, 7, &mut got_counter16);
1711        assert_ne!(crate::RAN.with(|r| r.get()) & crate::Ran::TurnTaken as u32, 0, "18 free trunc16 counters must consult the SME2 turn");
1712        crate::RAN.with(|r| r.set(0));
1713        let _ = tree.find_counter_range(&tmpl, 12, 7, 18, u32::MAX, 0, &mut got_find);
1714        assert_ne!(crate::RAN.with(|r| r.get()) & crate::Ran::TurnTaken as u32, 0, "18 TreeHasher find counters must consult the SME2 turn");
1715        crate::RAN.with(|r| r.set(0));
1716        let _ = find_counter_range(Mode::Plain, &tmpl, 12, 7, 18, u32::MAX, 0, &mut got_find);
1717        assert_ne!(crate::RAN.with(|r| r.get()) & crate::Ran::TurnTaken as u32, 0, "18 free find counters must consult the SME2 turn");
1718        crate::RAN_ENTRIES.with(|r| {
1719            let ran = r.borrow();
1720            assert!(!ran.contains(&parents_fn), "parent_cvs bypassed a held SME2 turn");
1721            assert!(!ran.contains(&messages_fn), "hash_each bypassed a held SME2 turn");
1722        });
1723        assert_eq!(got_parents, expected_parents);
1724        assert_eq!(got_each, expected_each);
1725        drop(held);
1726
1727        // With the turn free, 32 children (16 pairs) and 16 two-chunk messages
1728        // DO enter SME2 (isolated nextest process has no competing SME2 user).
1729        crate::RAN.with(|r| r.set(0));
1730        crate::RAN_ENTRIES.with(|r| r.borrow_mut().clear());
1731        tree.parent_cvs(&children, &mut got_parents);
1732        tree.hash_each(&items, &mut got_each);
1733        assert_eq!(crate::RAN.with(|r| r.get()) & crate::Ran::TurnTaken as u32, 0, "SME2 turn must be free after dropping held guard");
1734        let ran = crate::RAN_ENTRIES.with(|r| r.borrow().clone());
1735        assert!(ran.contains(&parents_fn), "16 parent pairs should enter SME2 when turn is free");
1736        assert!(ran.contains(&messages_fn), "16 two-chunk messages should enter SME2 when turn is free");
1737        assert_eq!(got_parents, expected_parents);
1738        assert_eq!(got_each, expected_each);
1739
1740        // And with the turn free, 3 x 15 KiB (21 first-round parent pairs) enters SME2 parents.
1741        crate::RAN.with(|r| r.set(0));
1742        crate::RAN_ENTRIES.with(|r| r.borrow_mut().clear());
1743        tree.hash_each(&items_3x15k, &mut got_3);
1744        assert_eq!(crate::RAN.with(|r| r.get()) & crate::Ran::TurnTaken as u32, 0, "SME2 turn must be free for 3 x 15 KiB");
1745        let ran_3x15k = crate::RAN_ENTRIES.with(|r| r.borrow().clone());
1746        assert!(ran_3x15k.contains(&parents_fn), "3 x 15 KiB (21 parent pairs) should enter SME2 parents when turn is free");
1747        assert_eq!(got_3, expected_3x15k);
1748    }
1749
1750    #[test]
1751    fn tree_hasher_short_and_boundary_inputs_match_official() {
1752        crate::initialize();
1753        let key = [0x3du8; 32];
1754        let ctx = "blake3-servil tree hasher single-block fast path";
1755        let mut buf = std::vec![0u8; 1025];
1756        for (i, b) in buf.iter_mut().enumerate() {
1757            *b = ((i.wrapping_mul(41) ^ 0x5c) & 0xff) as u8;
1758        }
1759        for mode in [Mode::Plain, Mode::Keyed(&key), Mode::DeriveKey(ctx)] {
1760            let tree = TreeHasher::new(mode);
1761            let local = TreeHasher::new(mode).on_this_core();
1762            for len in (0usize..=65).chain([127, 128, 1023, 1024, 1025]) {
1763                let slice = &buf[..len];
1764                let want = crate::test::official::hash(mode, slice);
1765                assert_eq!(*tree.hash(slice).as_bytes(), want, "TreeHasher::hash len={len}");
1766                assert_eq!(*local.hash(slice).as_bytes(), want, "TreeHasher::on_this_core().hash len={len}");
1767            }
1768        }
1769        // Pin single-kernel dispatch for <= 64 B inputs on both default and
1770        // `on_this_core` trees (48 B and exact 64 B invoke exactly one root
1771        // kernel on both x86-64 and AArch64; on AArch64, <= 64 B also bypasses
1772        // `hash_long` and hits `c1`, while 65 B enters `hash_long`).
1773        for (label, tree) in [("default", TreeHasher::new(Mode::Keyed(&key))), ("on_this_core", TreeHasher::new(Mode::Keyed(&key)).on_this_core())] {
1774            for short_len in [48usize, crate::BLOCK_LEN] {
1775                #[cfg(target_arch = "aarch64")]
1776                TREE_HASH_LONG_CALLS.with(|c| c.set(0));
1777                crate::RAN_ENTRIES.with(|r| r.borrow_mut().clear());
1778                crate::RAN_KERNEL_CALLS.with(|c| c.set(0));
1779                let _ = tree.hash(&buf[..short_len]);
1780                assert_eq!(crate::RAN_KERNEL_CALLS.with(|c| c.get()), 1, "{label} len={short_len} must invoke exactly one kernel");
1781                let ran = crate::RAN_ENTRIES.with(|r| r.borrow().clone());
1782                assert_eq!(ran.len(), 1, "{label} len={short_len} must run a single root kernel: {ran:?}");
1783                #[cfg(target_arch = "aarch64")]
1784                {
1785                    let c1_entry = crate::neon_hybrid::entries()
1786                        .into_iter()
1787                        .find_map(|(name, addr)| (name == "c1").then_some(addr as usize))
1788                        .expect("neon_hybrid::entries must list c1");
1789                    assert_eq!(TREE_HASH_LONG_CALLS.with(|c| c.get()), 0, "{label} len={short_len} must bypass hash_long");
1790                    assert!(ran.contains(&c1_entry), "{label} len={short_len} must dispatch directly to c1");
1791                }
1792            }
1793
1794            #[cfg(target_arch = "aarch64")]
1795            {
1796                TREE_HASH_LONG_CALLS.with(|c| c.set(0));
1797                let _ = tree.hash(&buf[..crate::BLOCK_LEN + 1]);
1798                assert_eq!(TREE_HASH_LONG_CALLS.with(|c| c.get()), 1, "{label} len=65 must enter hash_long");
1799            }
1800        }
1801    }
1802}
1803
1804#[cfg(all(test, target_arch = "aarch64"))]
1805std::thread_local! {
1806    static TREE_HASH_LONG_CALLS: core::cell::Cell<usize> = const { core::cell::Cell::new(0) };
1807}