Skip to main content

blake3_servil_core/
incremental.rs

1//! The Hasher: a message fed in pieces, on the calling thread (the
2//! convenience API exports it; the throughput API's free functions take
3//! it to other cores and in groups).
4
5use super::*;
6use crate::throughput::{Cv, TreeHasher};
7
8/// One-byte operational state of a [`Hasher`], occupying the same byte as
9/// the former `finishing: bool` flag so `Hasher`'s size and layout stay
10/// unchanged.
11#[derive(Clone, Copy, PartialEq, Eq)]
12enum HasherState {
13    Ready,
14    /// Set while one `finalize_each` call finishes this hasher, so that
15    /// the call sees an index it is given twice (`each::finalize_each`).
16    Finishing,
17    /// Set if [`Hasher::update_with`] unwinds (for example, a panicked
18    /// callback or rejection of returned `Cv` positions), making later
19    /// hashing operations fail-stop instead of silently hashing truncated
20    /// bytes (#465).
21    Poisoned,
22}
23
24#[cold]
25#[inline(never)]
26fn panic_poisoned() -> ! {
27    panic!("Hasher was poisoned by an earlier panicked update_with call");
28}
29
30struct PoisonOnUnwind<'a>(&'a mut HasherCore, &'a mut HasherState);
31
32impl Drop for PoisonOnUnwind<'_> {
33    #[cold]
34    fn drop(&mut self) {
35        *self.1 = HasherState::Poisoned;
36        self.0.chunk_state.saturate_count();
37    }
38}
39
40/// A message's hash, fed in pieces: [`update`](Hasher::update) with each
41/// piece, in order, then [`finalize`](Hasher::finalize). The pieces may be
42/// of any lengths; the hash is the same as [`hash`](convenience::hash) of them all at once.
43/// Every call runs on the calling thread and returns with its input
44/// incorporated. For other cores, the crate `blake3-servil` has
45/// `throughput::update_multithreaded`; for many messages at once,
46/// `throughput::update_each`.
47///
48/// A `Hasher` is 26 KiB (it holds short pieces until it has 16 KiB to
49/// hash at once, and rows of chaining values, so that parents are hashed
50/// side by side); box it where that matters. It touches what it uses: a
51/// short message touches its first block.
52///
53/// # After a panic
54///
55/// Each call says what it refuses, and a callback of the caller's may
56/// panic too. If [`update_with`](Hasher::update_with) unwinds after passing
57/// length preflight — including a panic in its `halves` callback or rejection
58/// of the returned chaining values' positions — this `Hasher` is poisoned:
59/// later hashing operations (`update`, `update_with`, `update_reader`,
60/// `Write::write`, `finalize`, `finalize_xof`, `update_each`, `finalize_each`)
61/// panic instead of silently hashing a truncated message, and `finalize_each`
62/// refuses rather than resetting it. `Clone` and `clone_from` propagate the
63/// poisoned state (`clone_from` from a healthy source replaces it); `Debug`
64/// and `Write::flush` still succeed. Other panics (such as an out-of-range
65/// index mid-way through `update_each`) may leave some pieces incorporated
66/// and others not: replace such a hasher with a new one before its next
67/// message.
68///
69/// # Examples
70///
71/// ```
72/// # fn main() -> Result<(), Box<dyn std::error::Error>> {
73/// # blake3_servil_core::initialize();
74/// // Hash an input incrementally.
75/// let mut hasher = blake3_servil_core::convenience::Hasher::new(blake3_servil_core::Mode::Plain, None);
76/// hasher.update(b"foo");
77/// hasher.update(b"bar");
78/// hasher.update(b"baz");
79/// // finalize borrows the Hasher: more updates may follow it.
80/// assert_eq!(hasher.finalize(), blake3_servil_core::convenience::hash(b"foobarbaz"));
81///
82/// // Extended output. OutputReader also implements Read and Seek.
83/// let mut output = [0; 1000];
84/// let mut hasher = blake3_servil_core::convenience::Hasher::new(blake3_servil_core::Mode::Plain, None);
85/// hasher.update(b"foobarbaz");
86/// let mut output_reader = hasher.finalize_xof();
87/// output_reader.fill(&mut output);
88/// assert_eq!(&output[..32], blake3_servil_core::convenience::hash(b"foobarbaz").as_bytes());
89/// # Ok(())
90/// # }
91/// ```
92///
93/// # Trait implementations
94///
95/// - `Clone` copies the hashing state (26 KiB: the key, the tree so far and
96///   up to the last 16 KiB of the message's bytes), so both hashers go on
97///   with the same message, each alone; nothing wipes either copy when it
98///   is dropped.
99/// - `Debug` shows the mode flags and platform, keeping the key and message
100///   private.
101/// - `Write` feeds every written byte in order; flushing leaves the message
102///   unchanged.
103pub struct Hasher {
104    core: HasherCore,
105    stage: stage::Stage,
106    state: HasherState,
107}
108
109impl Clone for Hasher {
110    #[inline]
111    fn clone(&self) -> Self {
112        Self { core: self.core.clone(), stage: self.stage.clone(), state: self.state }
113    }
114
115    #[inline]
116    fn clone_from(&mut self, source: &Self) {
117        self.core.clone_from(&source.core);
118        self.stage.clone_from(&source.stage);
119        self.state = source.state;
120    }
121}
122
123/// The bytes a Hasher gathers before they hash side by side: 16 chunks,
124/// the widest kernels' lanes.
125pub(crate) const STAGE_LEN: usize = 16 * CHUNK_LEN;
126
127/// The stage buffer and its initialized-prefix length, kept private so
128/// `len <= STAGE_LEN`, `buf[..len]` initialized, and (when `len > 0`)
129/// `buf[..BLOCK_LEN]` zero-padded past `len` hold by construction.
130mod stage {
131    use crate::{BLOCK_LEN, STAGE_LEN};
132
133    pub(crate) struct Stage {
134        len: usize,
135        buf: [core::mem::MaybeUninit<u8>; STAGE_LEN],
136    }
137
138    impl Clone for Stage {
139        #[inline]
140        fn clone(&self) -> Self {
141            Self { len: self.len, buf: self.buf }
142        }
143
144        #[inline]
145        fn clone_from(&mut self, source: &Self) {
146            // Copy the live bytes, and with any staged the whole first block
147            // (`first_block`; an empty stage's is unwritten, and never read);
148            // the rest of the capacity is overwritten before it becomes input.
149            let prefix = &source.buf[..if source.len == 0 { 0 } else { source.len.max(BLOCK_LEN) }];
150            self.len = source.len;
151            self.buf[..prefix.len()].copy_from_slice(prefix);
152        }
153    }
154
155    impl Stage {
156        #[inline(always)]
157        pub(crate) fn new() -> Self {
158            Self { len: 0, buf: [core::mem::MaybeUninit::uninit(); STAGE_LEN] }
159        }
160
161        #[inline(always)]
162        pub(crate) fn len(&self) -> usize {
163            self.len
164        }
165
166        #[inline(always)]
167        pub(crate) fn is_empty(&self) -> bool {
168            self.len == 0
169        }
170
171        #[inline(always)]
172        pub(crate) fn clear(&mut self) {
173            self.len = 0;
174        }
175
176        /// The message's first block, padded with zeros, while the message is
177        /// a block or less and whole in the stage. An empty stage's is a block
178        /// of zeros apart (a new Hasher's stage is unwritten, and a reset one's
179        /// holds the last message).
180        #[inline(always)]
181        pub(crate) fn first_block(&self) -> &[u8; BLOCK_LEN] {
182            static EMPTY: [u8; BLOCK_LEN] = [0; BLOCK_LEN];
183            if self.len == 0 {
184                return &EMPTY;
185            }
186            // Sound: when `self.len > 0`, `append`, `pad_first_block`, and
187            // `clone_from` initialize `buf[..BLOCK_LEN]` with zeros past `len`.
188            unsafe { &*(self.buf.as_ptr() as *const [u8; BLOCK_LEN]) }
189        }
190
191        /// The bytes gathered in the stage.
192        #[inline(always)]
193        pub(crate) fn as_bytes(&self) -> &[u8] {
194            // Sound: `self.len <= STAGE_LEN` and `buf[..self.len]` were written.
195            unsafe { core::slice::from_raw_parts(self.buf.as_ptr() as *const u8, self.len) }
196        }
197
198        /// Copy `bytes` into the stage after what it holds. Under a block
199        /// into an empty stage, the rest of the first block is zeroed.
200        pub(crate) fn append(&mut self, bytes: &[u8]) {
201            assert!(bytes.len() <= STAGE_LEN - self.len, "staged bytes exceed STAGE_LEN");
202            crate::counted(crate::Counted::Staged);
203            if self.len == 0 {
204                // (From a block up there is nothing left of the block to zero.)
205                self.buf[bytes.len().min(BLOCK_LEN)..BLOCK_LEN].fill(core::mem::MaybeUninit::new(0));
206            }
207            self.buf[self.len..self.len + bytes.len()].write_copy_of_slice(bytes);
208            self.len += bytes.len();
209        }
210
211        /// Store `input` (at most `BLOCK_LEN` bytes) into an empty stage as one
212        /// zero-padded block in the 16-byte pieces `finalize`'s kernel loads.
213        #[cfg(target_arch = "x86_64")]
214        #[inline(always)]
215        pub(crate) fn pad_first_block(&mut self, input: &[u8]) {
216            assert!(self.len == 0 && input.len() <= BLOCK_LEN, "pad_first_block requires empty stage and at most one block");
217            let first: &mut [core::mem::MaybeUninit<u8>; BLOCK_LEN] = (&mut self.buf[..BLOCK_LEN]).try_into().expect("STAGE_LEN >= BLOCK_LEN");
218            crate::chunk_root::pad_block(first, input);
219            self.len = input.len();
220        }
221
222        /// Clear the stage length first (so a panic in `f` never leaves stale
223        /// staged bytes), then pass the previously staged bytes to `f`.
224        #[inline(always)]
225        pub(crate) fn take_with(&mut self, f: impl FnOnce(&[u8])) {
226            let len = core::mem::replace(&mut self.len, 0);
227            // Sound: `buf[..len]` were written before `self.len` was cleared,
228            // and `self.buf` is not mutated while `bytes` is borrowed by `f`.
229            let bytes = unsafe { core::slice::from_raw_parts(self.buf.as_ptr() as *const u8, len) };
230            f(bytes);
231        }
232
233        #[cfg(test)]
234        pub(crate) fn fill_from_for_test(&mut self, start: usize, byte: u8) {
235            self.buf[start..].fill(core::mem::MaybeUninit::new(byte));
236        }
237
238        /// # Safety
239        ///
240        /// The test caller must have initialized `self.buf[i]` before reading it.
241        #[cfg(test)]
242        pub(crate) unsafe fn byte_for_test(&self, i: usize) -> u8 {
243            // Sound: caller's precondition.
244            unsafe { self.buf[i].assume_init() }
245        }
246    }
247}
248
249/// The tree's state behind a [`Hasher`]: its immutable prepared mode,
250/// its chunk, and the chaining values of its finished subtrees.
251pub(crate) struct HasherCore {
252    domain: Domain,
253    chunk_state: ChunkState,
254    // The stack size is MAX_DEPTH + 1 because we do lazy merging. For example,
255    // with 7 chunks, we have 3 entries in the stack. Adding an 8th chunk
256    // requires a 4th entry, rather than merging everything down to 1, because
257    // we don't know whether more input is coming (official BLAKE3's
258    // reference implementation merges eagerly instead).
259    cv_stack: CvStack,
260}
261
262impl Clone for HasherCore {
263    fn clone(&self) -> Self {
264        Self { domain: self.domain, chunk_state: self.chunk_state.clone(), cv_stack: self.cv_stack.clone() }
265    }
266
267    /// In place, field by field: the stack copies the entries it holds
268    /// (a clone made and then moved here would copy 10 KiB twice).
269    fn clone_from(&mut self, source: &Self) {
270        self.domain = source.domain;
271        self.chunk_state.clone_from(&source.chunk_state);
272        self.cv_stack.clone_from(&source.cv_stack);
273    }
274}
275
276/// Check that `incoming` more bytes after `count` stay within BLAKE3's
277/// `2^64 - 1` byte message domain.
278#[inline(always)]
279fn check_input_room(count: u64, incoming: usize) {
280    assert!(incoming as u64 <= u64::MAX - count, "BLAKE3 messages contain at most 2^64 - 1 bytes (have {count}, adding {incoming})");
281}
282
283/// What the Hasher's kernels take from the library (hasher::Hooks): with
284/// `pooled`, subtrees of the given size and more on the pool; whole
285/// subtrees on `platform` (an SME2 turn's); `chunk_platform`, the chunk
286/// state's, otherwise.
287struct HasherHooks<'a> {
288    domain: &'a Domain,
289    chunk_platform: Platform,
290    platform: Platform,
291    pooled: Option<&'a Pool<'a>>,
292}
293
294/// The callback and threshold that one call of Hasher::update_with lends.
295pub(crate) struct Pool<'a> {
296    pub min_len: usize,
297    pub halves: &'a dyn Fn(&TreeHasher, u32, u64, &[u8]) -> [Cv; 2],
298}
299
300impl hasher::Hooks for HasherHooks<'_> {
301    #[inline(always)]
302    #[allow(unused_variables)]
303    fn subtree_cv(&self, input: &[u8], ahead: usize, counter: u64) -> Option<CVBytes> {
304        // After the first input, no subtree is the root: on SME2 the flat
305        // walk runs it down to its own chaining value, so one value goes
306        // on the stack and about one merge runs on the core between SME2
307        // kernels (about 0.2 us of other work between them puts the SME
308        // unit in its slow state: `sme2`'s documentation).
309        #[cfg(target_arch = "aarch64")]
310        if self.pooled.is_none() && matches!(self.platform, Platform::SME2) && sme2::flat_takes(input.len()) {
311            crate::counted(crate::Counted::Flat);
312            // Sound: startup verified FEAT_SME2; SME2 assembly checks the calling thread's SVL at entry and falls back to NEON if != 512 bits.
313            return Some(unsafe { sme2::compress_subtree_flat_to_cv(input, ahead, self.domain.key(), counter, self.domain.flags()) });
314        }
315        None
316    }
317
318    #[inline(always)]
319    fn children(&self, input: &[u8], ahead: usize, counter: u64) -> [CVBytes; 2] {
320        if let Some(pool) = self.pooled.filter(|pool| input.len() >= pool.min_len) {
321            let level = crate::throughput::level_of(input.len() as u64);
322            let index = counter >> level;
323            assert!(index << level == counter, "a subtree of {} bytes starts at its own boundary, not chunk {counter}", input.len());
324            let halves = (pool.halves)(&TreeHasher::of_domain(*self.domain), level, index, input);
325            return Cv::halves_bytes(halves, level, index);
326        }
327        if self.pooled.is_some() {
328            // Pooled, the subtrees below take the lock one at a time, and
329            // the pool's own never use SME2.
330            let own = platform::Sme2Turn::take(self.chunk_platform, input.len() >= SME2_SIZED_LEN);
331            compress_subtree_to_parent_node(input, ahead, self.domain.key(), counter, self.domain.flags(), own.platform())
332        } else {
333            compress_subtree_to_parent_node(input, ahead, self.domain.key(), counter, self.domain.flags(), self.platform)
334        }
335    }
336
337    /// A whole group or more is cut, on the caller's own kernels: not
338    /// pooled, and by kernels 4 to ROW lanes wide (the SME2 unit's are
339    /// wider, and its subtrees are its own: `subtree_cv`).
340    #[inline(always)]
341    fn cuts(&self, len: usize) -> bool {
342        self.pooled.is_none() && len >= STAGE_LEN && (4..=hasher::ROW).contains(&self.platform.simd_degree())
343    }
344
345    #[inline(always)]
346    fn cut(&self, input: &[u8], ahead: usize, counter: u64, out: &mut [CVBytes; hasher::ROW]) -> usize {
347        crate::counted(crate::Counted::Row);
348        let kernels = crate::tree::PlatformKernels { key: self.domain.key(), flags: self.domain.flags(), platform: self.platform };
349        crate::tree::wide(&kernels, input, ahead, counter, out)
350    }
351
352    #[inline(always)]
353    fn parents(&self, children: &[CVBytes], out: &mut [CVBytes]) -> usize {
354        compress_parents_parallel(children.as_flattened(), self.domain.key(), self.domain.flags(), self.platform, out.as_flattened_mut())
355    }
356}
357
358/// The Hasher's kernels: chunks, nodes, and parents on the chunk state's
359/// platform, the rest from `hooks`.
360type HasherKernels<'a> = hasher::Kernels<'a, HasherHooks<'a>>;
361
362/// A Hasher's kernels on its immutable domain and chunk state (see HasherHooks).
363#[inline(always)]
364fn kernels_on<'a>(domain: &'a Domain, chunk_state: &ChunkState, platform: Platform, pooled: Option<&'a Pool<'a>>) -> HasherKernels<'a> {
365    hasher::Kernels {
366        key: domain.key(),
367        flags: domain.flags(),
368        platform: chunk_state.platform(),
369        hooks: HasherHooks { domain, chunk_platform: chunk_state.platform(), platform, pooled },
370    }
371}
372
373impl Hasher {
374    #[inline(always)]
375    pub(crate) fn from_core(core: HasherCore) -> Self {
376        // One literal, with nothing written after it: a Hasher made in a
377        // local and then written to (its first block zeroed) was copied
378        // to its caller, 16 KiB of it, once the core held the stack's rows
379        // (160 ns a 64-byte message where 41 had done). The empty stage's
380        // first block is never read (`first_block`). Whether the compiler
381        // builds a Hasher where it goes depends on its fields' layout too
382        // (one more byte in the stack cost 13 ns; the stack aligned to 64
383        // bytes, 68 ns), and no test of ours can see it: after any change
384        // to these types, time `new` on x86-64 and on AArch64.
385        Self { core, stage: stage::Stage::new(), state: HasherState::Ready }
386    }
387
388    /// Fail-stop if an earlier [`Hasher::update_with`] call unwound and left
389    /// this hasher's staged/core state incomplete (#465).
390    #[inline(always)]
391    fn assert_not_poisoned(&self) {
392        if self.state == HasherState::Poisoned {
393            panic_poisoned();
394        }
395    }
396
397    #[inline(always)]
398    fn check_room(&self, incoming: usize) {
399        let count = self.count();
400        if incoming as u64 > u64::MAX - count {
401            self.panic_room(count, incoming);
402        }
403    }
404
405    #[cold]
406    #[inline(never)]
407    fn panic_room(&self, count: u64, incoming: usize) -> ! {
408        self.assert_not_poisoned();
409        panic!("BLAKE3 messages contain at most 2^64 - 1 bytes (have {count}, adding {incoming})");
410    }
411
412    /// The prepared mode (immutable key words and domain flags).
413    #[inline(always)]
414    pub(crate) fn domain(&self) -> &Domain {
415        &self.core.domain
416    }
417
418    #[inline(always)]
419    pub(crate) fn is_plain(&self) -> bool {
420        self.core.domain.is_plain()
421    }
422
423    #[inline(always)]
424    pub(crate) fn platform(&self) -> Platform {
425        self.core.chunk_state.platform()
426    }
427
428    /// Mark this hasher as participating in an active `finalize_each` call;
429    /// returns `true` if it was already marked. Panics if the hasher was
430    /// poisoned by a prior panicked `update_with` call.
431    #[inline(always)]
432    pub(crate) fn mark_finishing(&mut self) -> bool {
433        self.assert_not_poisoned();
434        core::mem::replace(&mut self.state, HasherState::Finishing) == HasherState::Finishing
435    }
436
437    #[inline(always)]
438    pub(crate) fn clear_finishing(&mut self) {
439        self.state = HasherState::Ready;
440    }
441
442    #[cfg(test)]
443    pub(crate) fn set_platform_for_test(&mut self, platform: Platform) {
444        self.core.chunk_state.set_platform(platform);
445    }
446
447    #[inline(always)]
448    pub(crate) fn staged_len(&self) -> usize {
449        self.stage.len()
450    }
451
452    #[inline(always)]
453    pub(crate) fn chunk_state(&self) -> &ChunkState {
454        &self.core.chunk_state
455    }
456
457    #[inline(always)]
458    pub(crate) fn stage_first_block(&self) -> &[u8; BLOCK_LEN] {
459        self.stage.first_block()
460    }
461
462    /// True when the whole message is plain mode, at most one chunk, and
463    /// sits completely in the stage (`finalize_each` batching).
464    #[inline(always)]
465    pub(crate) fn is_plain_single_chunk_staged(&self) -> bool {
466        self.stage.len() <= CHUNK_LEN && self.core.count() == 0 && self.core.domain.is_plain()
467    }
468
469    /// The bytes gathered in the stage.
470    pub(crate) fn staged_bytes(&self) -> &[u8] {
471        self.stage.as_bytes()
472    }
473
474    /// Copy `bytes` into the stage after what it holds.
475    #[cfg(test)]
476    pub(crate) fn stage(&mut self, bytes: &[u8]) {
477        self.stage.append(bytes);
478    }
479
480    /// `update`'s gathering: an update of STAGE_LEN or more from a 16 KiB
481    /// boundary of the message (or an empty stage) goes to the core whole;
482    /// shorter ones gather in the stage until it reaches the next boundary,
483    /// and the stage goes to the core as one update, its chunks side by
484    /// side in the lanes. A message of under 16 KiB is therefore whole in
485    /// the stage, where `finalize` hashes it as the one-shot call would.
486    fn gather(&mut self, input: &[u8], pooled: Option<&Pool<'_>>) -> &mut Self {
487        self.gather_part(input, pooled, false);
488        self
489    }
490
491    /// [`gather`](Hasher::gather), but with `hold`, a stage that fills a
492    /// whole group is kept for the caller to hash with others' (`held_group`),
493    /// and the rest of `input` returned; else nothing is left.
494    pub(crate) fn gather_part<'a>(&mut self, mut input: &'a [u8], pooled: Option<&Pool<'_>>, hold: bool) -> &'a [u8] {
495        self.check_room(input.len());
496        while !input.is_empty() {
497            // Whole groups skip the stage. So does a fresh keyed/derived hasher's
498            // first chunk in a turn of many hashers (`hold`) on x86-64, where
499            // `finalize_each` finishes its final block side by side via
500            // `ffi_output::input` whenever 16 eligible descriptors pack together.
501            // Everywhere else (including plain mode in `update_each` on x86-64
502            // and all modes on AArch64) the first chunk is staged so
503            // `finalize_each` batches 1 KiB chunks via `hash_many_rounded` and
504            // AVX2/AVX-512 multi-block prefixes via `hash_by_blocks` (with
505            // scalar final blocks), while longer messages keep exact 16 KiB
506            // group boundaries (#404). Non-consuming mid-chunk `finalize()` on a
507            // staged plain first chunk rehashes that prefix fresh.
508            #[cfg(target_arch = "x86_64")]
509            if crate::ffi_partial::first_chunk_to_core(self.stage.is_empty(), hold, self.core.domain.is_plain(), self.core.count(), input.len()) {
510                self.core.update_pooled(input, pooled);
511                return &[];
512            }
513            let at = self.count() % STAGE_LEN as u64;
514            // On a 16 KiB boundary with nothing staged, the input's whole
515            // groups go to the core as they lie; what follows them is
516            // staged below, so the next groups start on a boundary too
517            // (BLAKE3 #393: sent whole, an input's ragged end left the
518            // core off the boundary, and every later piece hashed in the
519            // narrow subtrees that fit there, at half the speed).
520            if self.stage.is_empty() && at == 0 && input.len() >= STAGE_LEN {
521                let groups = input.len() / STAGE_LEN * STAGE_LEN;
522                // The loop's variant on this path: a group or more leaves the input.
523                assert!(groups > 0, "no whole group went to the core");
524                self.update_groups_guarded(&input[..groups], pooled);
525                input = &input[groups..];
526                continue;
527            }
528            let to_boundary = STAGE_LEN - usize::try_from(at).expect("at < STAGE_LEN");
529            let take = cmp::min(to_boundary, input.len());
530            // The loop's variant: every pass stages at least one byte of
531            // the input, which is not empty (`at` is below STAGE_LEN).
532            assert!(take > 0, "the stage took nothing");
533            self.stage.append(&input[..take]);
534            input = &input[take..];
535            if take < to_boundary {
536                return &[];
537            }
538            if hold && self.held_group().is_some() {
539                return input;
540            }
541            self.flush_stage_guarded(pooled);
542        }
543        self.assert_not_poisoned();
544        &[]
545    }
546
547    /// Forward whole-group flushes to [`HasherCore::update_groups`], poisoning
548    /// this hasher on unwind with zero work on normal return and without
549    /// adding unwind tables to `gather_part` (#465).
550    #[inline(never)]
551    fn update_groups_guarded(&mut self, bytes: &[u8], pooled: Option<&Pool<'_>>) {
552        let guard = PoisonOnUnwind(&mut self.core, &mut self.state);
553        guard.0.update_groups(bytes, pooled);
554        core::mem::forget(guard);
555    }
556
557    #[inline(never)]
558    fn flush_stage_guarded(&mut self, pooled: Option<&Pool<'_>>) {
559        let core = &mut self.core;
560        let state = &mut self.state;
561        self.stage.take_with(|bytes| {
562            let guard = PoisonOnUnwind(core, state);
563            guard.0.update_groups(bytes, pooled);
564            core::mem::forget(guard);
565        });
566    }
567
568    /// A whole group in the stage: its first chunk's counter and its bytes.
569    pub(crate) fn held_group(&self) -> Option<(u64, &[u8; STAGE_LEN])> {
570        (self.stage.len() == STAGE_LEN).then(|| (self.core.count() / CHUNK_LEN as u64, self.stage.as_bytes().try_into().unwrap()))
571    }
572
573    /// The held group's subtree, as [`HasherCore::push_group`] takes it
574    /// (its two halves' values at chunk zero, else its own), into the
575    /// core; the stage empty again.
576    pub(crate) fn take_held(&mut self, result: &[u8; BLOCK_LEN]) {
577        assert_eq!(self.stage.len(), STAGE_LEN, "a held group fills the stage");
578        self.stage.clear();
579        self.core.push_group(result);
580    }
581
582    /// The key of a fresh core, as a kernel reads it: the chunk state's
583    /// chaining value, which is the key until a block is compressed. Not
584    /// `core.domain.key()`: `new` has just stored both, and it stores
585    /// `domain.key` in 16-byte pieces that straddle the kernel's two
586    /// 16-byte loads of it, which a CPU cannot forward to those loads, so
587    /// the kernel's first round would wait for the stores to reach the
588    /// cache (14 ns of a 64-byte message's 55 ns on a Zen 4 core,
589    /// November 14, 2026). The chaining value is 64-byte aligned
590    /// (ChunkState), stored as it is loaded.
591    #[inline(always)]
592    fn fresh_key(&self) -> &CVWords {
593        assert_eq!(self.core.count(), 0, "a fresh core's chaining value is its key");
594        self.core.chunk_state.cv()
595    }
596
597    /// The root's output with the Hasher left as it is. With nothing
598    /// staged it is the core's. Else, where the core holds whole groups
599    /// (as `update` leaves it), the staged bytes are a whole subtree after
600    /// them: a local tail chunk and stack hash them, on this frame, and
601    /// their node is folded into the stack's entries, which are only read
602    /// (`hasher::above`); the Hasher's core is not copied (10 KiB with the
603    /// stack's rows). After a turn of many hashers that left a first
604    /// chunk in the core (`gather_part`), a copy of the core takes the
605    /// staged bytes.
606    fn root_output(&self) -> Output {
607        if self.stage.is_empty() {
608            return self.core.final_output();
609        }
610        let core = &self.core;
611        let counter = core.chunk_state.chunk_counter();
612        if core.chunk_state.count() > 0 || counter % (STAGE_LEN / CHUNK_LEN) as u64 != 0 {
613            let mut core = self.core.clone();
614            core.update(self.stage.as_bytes());
615            return core.final_output();
616        }
617        crate::counted(crate::Counted::TailApart);
618        let kernels = core.kernels();
619        let mut tail_chunk = ChunkState::new(core.domain.key(), counter, core.domain.flags(), core.chunk_state.platform());
620        let mut tail_stack = CvStack::new();
621        hasher::feed(&kernels, &mut tail_chunk, &mut tail_stack, counter, self.stage.as_bytes());
622        let node = hasher::final_node(&kernels, &tail_chunk, &tail_stack);
623        if counter == 0 {
624            return node;
625        }
626        hasher::above(&kernels, &core.cv_stack, hasher::ones(counter), node)
627    }
628
629    /// The root hash, for a caller that then resets the Hasher
630    /// (`finalize_each`): a message whole in the stage as `finalize` hashes
631    /// it, any other finished in place, with no copy of the core.
632    pub(crate) fn take_root_hash(&mut self) -> Hash {
633        if self.core.count() == 0 {
634            return self.finalize();
635        }
636        self.take_output().root_hash()
637    }
638
639    /// The root's output, the state finished in place: the Hasher is then
640    /// finished, to be reset or dropped (`finalize_each`, which resets it).
641    pub(crate) fn take_output(&mut self) -> Output {
642        self.stage.take_with(|staged| {
643            self.core.update(staged);
644        });
645        self.core.final_output()
646    }
647
648    /// Construct a new `Hasher` in a [`Mode`]: the plain hash, the keyed
649    /// hash, or key derivation with a context string or a context key.
650    ///
651    /// `length_hint` is the message's likely length in bytes, where the
652    /// program knows one (a file's size, a protocol's length field), or
653    /// `None`: a scheduling hint, never part of the hash, so the digest is
654    /// the same whatever it says and however many bytes then arrive. The
655    /// Hasher does not use it today; keeping it in the constructor avoids a
656    /// breaking signature change when scheduling uses it later.
657    pub fn new(mode: Mode, length_hint: Option<u64>) -> Self {
658        let _ = length_hint;
659        Self::from_core(HasherCore::new_internal(Domain::from_mode(mode)))
660    }
661
662    /// The `Hasher` back in its initial state, its mode kept: what
663    /// `finalize_each` leaves the hashers it finishes in.
664    pub(crate) fn reset(&mut self) {
665        self.core.reset();
666        self.stage.clear();
667        self.state = HasherState::Ready;
668    }
669
670    /// Add the message's next piece, of any length, on the calling thread.
671    ///
672    /// # Panics
673    ///
674    /// Panics if the cumulative input length would exceed BLAKE3's maximum
675    /// message length of `2^64 - 1` bytes (this limit applies equally through
676    /// [`update_with`](Hasher::update_with), `update_reader`, `std::io::Write`,
677    /// and grouped updates).
678    ///
679    /// **Speed**: pieces of any size hash at nearly the speed of whole
680    /// buffers: short pieces are copied into the `Hasher` until it holds
681    /// 16 KiB, which then hash at once. Pieces of 16 KiB and more, starting
682    /// at a multiple of 16 KiB of the message, skip the copy (about 5% of the
683    /// time on an Apple M4). For a whole message in memory, [`hash`](convenience::hash) is a
684    /// little faster; for a file or reader, see
685    /// [`update_reader`](#method.update_reader).
686    #[inline]
687    pub fn update(&mut self, input: &[u8]) -> &mut Self {
688        // A block or less into an empty stage (a Hasher per short message,
689        // above all) is staged here, in line, as one zero-padded block in
690        // the 16-byte pieces `finalize`'s kernel loads (pad_block). When
691        // `chunk_counter < 2^54 - 1`, at least 1,023 bytes remain in the
692        // 2^64 - 1 byte domain even if the buffered chunk is full, so <= 64
693        // bytes always fit; near the limit we fall through to `update_longer`
694        // for the exact `check_input_room` check.
695        #[cfg(target_arch = "x86_64")]
696        if input.len() <= BLOCK_LEN && self.stage.is_empty() && self.core.chunk_state.chunk_counter() < (1u64 << 54) - 1 {
697            crate::counted(crate::Counted::PaddedFirstBlock);
698            self.stage.pad_first_block(input);
699            return self;
700        }
701        self.update_longer(input)
702    }
703
704    /// [`update`](Hasher::update) past its path for a block or less into an
705    /// empty stage, out of line.
706    #[inline(never)]
707    fn update_longer(&mut self, input: &[u8]) -> &mut Self {
708        // A fresh hasher's first update is a one-shot call's work (a
709        // Hasher per message, the digest traits): it prefetches its code,
710        // as convenience::hash does. A Hasher fed in pieces pays it once.
711        // Under 16 KiB it waits whole in the stage for `finalize`, which
712        // hashes it with the one-shot call's kernels; from 16 KiB it goes
713        // to the core now.
714        #[cfg(target_arch = "aarch64")]
715        if self.count() == 0 && (CHUNK_LEN + 1..PREFETCH_BELOW).contains(&input.len()) {
716            prefetch_cold(input.len(), self.core.chunk_state.platform(), input.len() >= STAGE_LEN);
717        }
718        self.gather(input, None)
719    }
720
721    /// Add the next piece, letting the caller hash large whole subtrees.
722    ///
723    /// The Hasher can pass subtrees of at least `min_len` bytes to
724    /// `halves`. For each call, return the same ordered values as
725    /// `tree.subtree_halves(level, index, input)` in the given mode. The
726    /// Hasher checks both places in every build; the callback is
727    /// responsible for their bytes.
728    ///
729    /// The callback finishes its work before returning. It is borrowed
730    /// only for this update, so it can use the caller's workers or scratch.
731    /// Input that is not passed to it hashes on the calling thread.
732    ///
733    /// If this call unwinds after passing length preflight (for example, a
734    /// panic in `halves` or rejection of returned chaining value positions),
735    /// this `Hasher` is poisoned: later hashing operations panic rather than
736    /// silently hashing truncated bytes ([after a panic](Hasher#after-a-panic)).
737    pub fn update_with(&mut self, input: &[u8], min_len: usize, halves: &dyn Fn(&TreeHasher, u32, u64, &[u8]) -> [Cv; 2]) -> &mut Self {
738        self.gather(input, Some(&Pool { min_len, halves }))
739    }
740
741    /// The [`struct@Hash`] of everything updated so far. The Hasher is left
742    /// as it was: more updates may follow, and a later `finalize` then
743    /// covers them too, as with official BLAKE3's `Hasher`.
744    ///
745    /// **Speed**: when the entire message is still in the stage (under 16 KiB
746    /// fed via `update`), it is hashed here as [`hash`](convenience::hash)
747    /// would hash it. Otherwise, an empty stage reads the core in place, a
748    /// staged tail after an aligned empty chunk hashes the tail apart without
749    /// copying the core, and a fallback (such as staged bytes behind a partial
750    /// chunk left in the core by `update_each` on x86-64) copies the core
751    /// (~10 KiB).
752    #[inline]
753    pub fn finalize(&self) -> Hash {
754        self.assert_not_poisoned();
755        // A message whole in the stage, the empty one too: the core holds
756        // none of it.
757        if self.core.count() == 0 {
758            // A block or less: one kernel call on the stage's first block.
759            // Read the mode byte from `chunk_state` (same 64-byte-aligned
760            // cache line as `fresh_key`, initialized from `domain`).
761            #[cfg(target_arch = "x86_64")]
762            if self.stage.len() <= BLOCK_LEN {
763                let n = u8::try_from(self.stage.len()).expect("stage length <= BLOCK_LEN");
764                return Hash(crate::chunk_root::block_root(
765                    self.core.chunk_state.platform(),
766                    self.stage.first_block(),
767                    n,
768                    self.fresh_key(),
769                    self.core.chunk_state.flags(),
770                ));
771            }
772            return crate::hash_serial_from(self.core.chunk_state.platform(), self.stage.as_bytes(), self.fresh_key(), self.core.domain.flags(), false);
773        }
774        self.root_output().root_hash()
775    }
776
777    /// An [`OutputReader`] over everything updated so far, which supplies
778    /// any number of output bytes; the Hasher is left as it was, as with
779    /// [`finalize`](Hasher::finalize).
780    pub fn finalize_xof(&self) -> OutputReader {
781        self.assert_not_poisoned();
782        OutputReader::new(self.root_output())
783    }
784
785    /// The number of bytes passed to [`update`](Hasher::update) so far.
786    pub(crate) fn count(&self) -> u64 {
787        self.core.count() + self.stage.len() as u64
788    }
789
790    /// As [`update`](Hasher::update), but reading from a
791    /// [`std::io::Read`](https://doc.rust-lang.org/std/io/trait.Read.html) implementation.
792    ///
793    /// [`Hasher`] implements
794    /// [`std::io::Write`](https://doc.rust-lang.org/std/io/trait.Write.html), so it's possible to
795    /// use [`std::io::copy`](https://doc.rust-lang.org/std/io/fn.copy.html) to update a [`Hasher`]
796    /// from any reader. Unfortunately, this standard approach can limit performance, because
797    /// `copy` currently uses an internal 8 KiB buffer that isn't big enough to take advantage of
798    /// all SIMD instruction sets. (In particular, [AVX-512](https://en.wikipedia.org/wiki/AVX-512)
799    /// needs a 16 KiB buffer.) `update_reader` avoids this performance problem and is slightly
800    /// more convenient.
801    ///
802    /// The internal buffer size this method uses may change at any time, and it may be different
803    /// for different targets. The only guarantee is that it will be large enough for all of this
804    /// crate's SIMD implementations on the current platform. On the current implementation the
805    /// initial read allocates and zero-initializes a 64 KiB stack buffer before promoting to 1 MiB
806    /// on the heap if the stream fills it, so very small readers pay that fixed stack-zeroing cost.
807    ///
808    /// The most common implementer of
809    /// [`std::io::Read`](https://doc.rust-lang.org/std/io/trait.Read.html) might be
810    /// [`std::fs::File`](https://doc.rust-lang.org/std/fs/struct.File.html).
811    ///
812    /// The buffer holds the message's last bytes when the call returns, and
813    /// is not cleared. For a secret message, read into a buffer of your
814    /// own, call [`update`](Hasher::update), and clear the buffer.
815    ///
816    /// # Example
817    ///
818    /// ```no_run
819    /// # use std::fs::File;
820    /// # use std::io;
821    /// # fn main() -> io::Result<()> {
822    /// # blake3_servil_core::initialize();
823    /// // Hash standard input.
824    /// let mut hasher = blake3_servil_core::convenience::Hasher::new(blake3_servil_core::Mode::Plain, None);
825    /// hasher.update_reader(std::io::stdin().lock())?;
826    /// println!("{}", hasher.finalize());
827    /// # Ok(())
828    /// # }
829    /// ```
830    pub fn update_reader(&mut self, reader: impl std::io::Read) -> std::io::Result<&mut Self> {
831        self.assert_not_poisoned();
832        io::copy_wide(reader, self)?;
833        Ok(self)
834    }
835}
836
837impl HasherCore {
838    #[inline(always)]
839    pub(crate) fn new_internal(domain: Domain) -> Self {
840        Self::new_from(domain, Platform::detect())
841    }
842
843    /// [`HasherCore::new_internal`] on `platform` (the self-test's way in,
844    /// as [`hash_serial_from`]).
845    #[inline(always)]
846    pub(crate) fn new_from(domain: Domain, platform: Platform) -> Self {
847        Self { domain, chunk_state: ChunkState::new(domain.key(), 0, domain.flags(), platform), cv_stack: CvStack::new() }
848    }
849
850    /// Back to the empty message, with the same domain and platform.
851    pub(crate) fn reset(&mut self) -> &mut Self {
852        self.chunk_state = ChunkState::new(self.domain.key(), 0, self.domain.flags(), self.chunk_state.platform());
853        self.cv_stack.clear();
854        self
855    }
856
857    // As described in push_cv() below, we do "lazy merging", delaying merges
858    // until right before the next CV is about to be added (official BLAKE3's
859    // reference implementation merges eagerly). Also, we aren't
860    // always merging 1 chunk at a time. Instead, each CV might represent any
861    // power-of-two number of chunks, as long as the smaller-above-larger stack
862    // order is maintained. Instead of the "count the trailing 0-bits"
863    // algorithm described in the spec (which assumes you're adding one chunk
864    // at a time), we use a "count the total number of 1-bits" variant (which
865    // doesn't assume that). The principle is the same: each CV that should
866    // remain in the stack is represented by a 1-bit in the total number of
867    // chunks (or bytes) so far.
868    fn merge_cv_stack(&mut self, chunk_counter: u64) {
869        let post_merge_stack_len = hasher::ones(chunk_counter);
870        let kernels = kernels_on(&self.domain, &self.chunk_state, self.chunk_state.platform(), None);
871        self.cv_stack.merge(&kernels, post_merge_stack_len);
872    }
873
874    fn push_cv(&mut self, new_cv: &CVBytes, chunk_counter: u64) {
875        self.merge_cv_stack(chunk_counter);
876        self.cv_stack.push(*new_cv);
877    }
878
879    /// [`update`](Hasher::update) with a held group (STAGE_LEN bytes from a
880    /// multiple of STAGE_LEN, the core's chunk empty: Hasher::take_held,
881    /// its one caller), whose subtree value `result` holds as
882    /// the pool's task computes it: at chunk zero its two halves' values
883    /// (the group may be the root's), elsewhere its own. The group is one
884    /// whole subtree, so nothing of it reaches the chunk state.
885    pub fn push_group(&mut self, result: &[u8; BLOCK_LEN]) {
886        const CHUNKS: u64 = (STAGE_LEN / CHUNK_LEN) as u64;
887        check_input_room(self.count(), STAGE_LEN);
888        let counter = self.chunk_state.chunk_counter();
889        assert!(self.chunk_state.count() == 0 && counter % CHUNKS == 0, "a held group starts at a group boundary, the core's chunk empty");
890        if counter == 0 {
891            self.push_cv(result[..OUT_LEN].try_into().unwrap(), 0);
892            self.push_cv(result[OUT_LEN..].try_into().unwrap(), CHUNKS / 2);
893        } else {
894            self.push_cv(result[..OUT_LEN].try_into().unwrap(), counter);
895        }
896        self.chunk_state.advance_chunks(CHUNKS);
897    }
898
899    /// What `gather_part` sends to the core (an input's whole groups, or
900    /// the stage's bytes up to a group boundary), pooled only where the
901    /// slice reaches the pool's threshold: shorter, it holds no subtree
902    /// for the pool, and hashes exactly as the serial update hashes it.
903    /// Kept pooled, it would lose what the hooks do only without a pool:
904    /// the rows a whole group is cut into, and the SME2 turn over the
905    /// whole slice. (64 open messages fed 16 KiB at a time took 9% to 15%
906    /// longer through a pooled turn (update_each_multithreaded, a call
907    /// since removed) than through update_each,
908    /// on a Ryzen 9700X and an EPYC 9255: BLAKE3 #470.) The threshold is
909    /// held against the slice, not against the update that completed it:
910    /// a group gathered from shorter updates is the pool's where it
911    /// reaches the threshold.
912    ///
913    /// The core's and not the Hasher's: the Hasher calls it with a view of
914    /// its own stage, and a method on the Hasher would borrow the stage
915    /// exclusively while the view reads it.
916    #[inline(always)]
917    pub(crate) fn update_groups(&mut self, groups: &[u8], pooled: Option<&Pool<'_>>) {
918        self.update_pooled(groups, pooled.filter(|pool| groups.len() >= pool.min_len));
919    }
920
921    /// `update`'s loop; with `pooled`, whole subtrees at or above the
922    /// callback's threshold may go to the pool.
923    pub(crate) fn update_pooled(&mut self, input: &[u8], pooled: Option<&Pool<'_>>) -> &mut Self {
924        check_input_room(self.count(), input.len());
925        // The partial chunk first (hasher::fill), then whole subtrees and the
926        // last chunk (hasher::feed), as src/hasher.rs describes.
927        let fill_kernels = kernels_on(&self.domain, &self.chunk_state, self.chunk_state.platform(), pooled);
928        let rest = hasher::fill(&fill_kernels, &mut self.chunk_state, &mut self.cv_stack, 0, input);
929        // Pooled, the subtrees take the lock one at a time (children).
930        let turn = platform::Sme2Turn::take(self.chunk_state.platform(), pooled.is_none() && rest.len() >= SME2_SIZED_LEN);
931        let kernels = kernels_on(&self.domain, &self.chunk_state, turn.platform(), pooled);
932        hasher::feed(&kernels, &mut self.chunk_state, &mut self.cv_stack, 0, rest);
933        self
934    }
935
936    /// A Hasher's own kernels for its final output, with no pool.
937    #[inline(always)]
938    fn kernels(&self) -> HasherKernels<'_> {
939        kernels_on(&self.domain, &self.chunk_state, self.chunk_state.platform(), None)
940    }
941
942    pub fn final_output(&self) -> Output {
943        hasher::final_node(&self.kernels(), &self.chunk_state, &self.cv_stack)
944    }
945
946    /// The serial update: whole subtrees now, the last chunk kept.
947    pub fn update(&mut self, input: &[u8]) -> &mut Self {
948        self.update_pooled(input, None)
949    }
950
951    /// Bytes hashed into the core so far.
952    pub fn count(&self) -> u64 {
953        self.chunk_state.chunk_counter() * CHUNK_LEN as u64 + self.chunk_state.count() as u64
954    }
955}
956
957// Don't derive(Debug), because the state may be secret.
958impl fmt::Debug for Hasher {
959    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
960        f.debug_struct("Hasher").field("flags", &self.core.domain.flags()).field("platform", &self.core.chunk_state.platform()).finish()
961    }
962}
963
964impl std::io::Write for Hasher {
965    /// This is equivalent to [`update`](#method.update).
966    #[inline]
967    fn write(&mut self, input: &[u8]) -> std::io::Result<usize> {
968        self.update(input);
969        Ok(input.len())
970    }
971
972    #[inline]
973    fn flush(&mut self) -> std::io::Result<()> {
974        Ok(())
975    }
976}
977
978#[cfg(test)]
979mod test {
980    use super::*;
981
982    fn update_with_one_wrong_half(wrong: usize) {
983        crate::initialize();
984        Hasher::new(Mode::Plain, None).update_with(&[0; STAGE_LEN], STAGE_LEN, &|tree, level, index, input| {
985            let mut halves = tree.subtree_halves(level, index, input);
986            halves[wrong] = halves[1 - wrong];
987            halves
988        });
989    }
990
991    #[test]
992    #[should_panic(expected = "not the halves of level 4 index 0")]
993    fn pool_rejects_a_wrong_left_half_alone() {
994        update_with_one_wrong_half(0);
995    }
996
997    #[test]
998    #[should_panic(expected = "not the halves of level 4 index 0")]
999    fn pool_rejects_a_wrong_right_half_alone() {
1000        update_with_one_wrong_half(1);
1001    }
1002
1003    /// A panic of the caller's callback comes out of `update_with`, both
1004    /// from a group the input holds whole and from one that a one-byte
1005    /// update completes in the stage; and a hasher replaced after it (as
1006    /// "After a panic" asks) hashes its next message. (A hook that caught
1007    /// the panic and hashed the subtree itself passed every test, once the
1008    /// turn's callback test went with `update_each_with`: BLAKE3 #476.)
1009    #[test]
1010    fn a_callbacks_panic_comes_out_of_update_with() {
1011        crate::initialize();
1012        let mut input = vec![0u8; 2 * STAGE_LEN];
1013        crate::test::paint_test_input(&mut input);
1014        let panics = |_: &TreeHasher, _: u32, _: u64, _: &[u8]| -> [Cv; 2] { panic!("this callback panics") };
1015        for whole in [true, false] {
1016            let mut hasher = Hasher::new(Mode::Plain, None);
1017            let call = std::panic::catch_unwind(core::panic::AssertUnwindSafe(|| {
1018                if whole {
1019                    hasher.update_with(&input, STAGE_LEN, &panics);
1020                } else {
1021                    hasher.update(&input[..STAGE_LEN + 1]);
1022                    hasher.update(&input[STAGE_LEN + 1..2 * STAGE_LEN - 1]);
1023                    hasher.update_with(&input[2 * STAGE_LEN - 1..], STAGE_LEN, &panics);
1024                }
1025            }));
1026            let message = call.expect_err("the callback's panic did not come out");
1027            assert_eq!(message.downcast_ref::<&str>(), Some(&"this callback panics"), "whole: {whole}");
1028            let mut hasher = Hasher::new(Mode::Plain, None);
1029            hasher.update_with(&input, STAGE_LEN, &|tree, level, index, bytes| tree.subtree_halves(level, index, bytes));
1030            assert_eq!(*hasher.finalize().as_bytes(), crate::test::official::hash(Mode::Plain, &input), "whole: {whole}");
1031        }
1032    }
1033
1034    /// Groups shorter than the pool's threshold go to the core as the
1035    /// serial update sends them: the callback is not asked, and their
1036    /// whole subtrees take the serial update's paths. Counted, since the
1037    /// digests are the same either way: the rows a whole group is cut
1038    /// into, and on SME2 the flat walks to one value. (Kept pooled, such
1039    /// an update cut no row, and no subtree of it walked flat to its one
1040    /// value: 64 open messages fed 16 KiB at a time took 9% to 15% longer
1041    /// through a pooled turn (`update_each_multithreaded`, a call since
1042    /// removed) than through `update_each`,
1043    /// BLAKE3 #470.) The threshold here
1044    /// is above every piece and every group the pieces fill in the stage;
1045    /// what is held to it is the group, not the piece that completes it
1046    /// (`a_staged_group_is_held_to_the_threshold_by_its_own_length`). At
1047    /// the threshold the callback is asked
1048    /// (`pool_halves_use_the_subtrees_nonzero_place`), and above it too.
1049    #[test]
1050    fn an_update_below_the_pools_threshold_is_the_serial_update() {
1051        crate::initialize();
1052        let mut input = std::vec![0u8; 16 * STAGE_LEN];
1053        crate::test::paint_test_input(&mut input);
1054        let counts = || [crate::Counted::Row, crate::Counted::Flat].map(|what| crate::COUNTED.with(|c| c[what as usize].replace(0)));
1055        // The threshold of the library with threads: 512 KiB, above every
1056        // piece here and every group they fill in the stage.
1057        const THRESHOLD: usize = 32 * STAGE_LEN;
1058        let key = [0x52u8; 32];
1059        let platform = Platform::detect();
1060        let rows_here = (4..=hasher::ROW).contains(&platform.simd_degree());
1061        #[cfg(target_arch = "aarch64")]
1062        let flat_here = matches!(platform, Platform::SME2);
1063        #[cfg(not(target_arch = "aarch64"))]
1064        let flat_here = false;
1065        for mode in [Mode::Plain, Mode::Keyed(&key), Mode::DeriveKey("below the pool's threshold")] {
1066            let (mut serial, mut pooled) = (Hasher::new(mode, None), Hasher::new(mode, None));
1067            let (mut fed, mut seen) = (0, [0u64; 2]);
1068            // A group; a group and a part; the rest of that group; a
1069            // group; then, from the 64 KiB boundary, four groups that are
1070            // one subtree; two groups and a part.
1071            for n in [STAGE_LEN, STAGE_LEN + 100, STAGE_LEN - 100, STAGE_LEN, 4 * STAGE_LEN, 2 * STAGE_LEN + 7] {
1072                let piece = &input[fed..fed + n];
1073                fed += n;
1074                counts();
1075                serial.update(piece);
1076                let want = counts();
1077                pooled.update_with(piece, THRESHOLD, &|_, _, _, _| panic!("an input below the threshold holds no subtree for the callback"));
1078                assert_eq!(counts(), want, "{fed} bytes in, a piece of {n}: the serial update's rows and flat walks");
1079                assert_eq!(pooled.finalize(), serial.finalize(), "{fed} bytes");
1080                seen = [seen[0] + want[0], seen[1] + want[1]];
1081            }
1082            // The comparison is of something wherever the kernels have
1083            // these paths: the pieces after the first group cut rows, and
1084            // the 64 KiB subtree walks flat.
1085            assert_eq!((seen[0] > 0, seen[1] > 0), (rows_here, flat_here), "rows and flat walks counted: {seen:?}");
1086            // Above the threshold the callback takes its subtrees: here
1087            // 64 KiB from the next 64 KiB boundary, one subtree, with a
1088            // threshold of a group.
1089            let calls = core::cell::Cell::new(0);
1090            assert_eq!(fed, 10 * STAGE_LEN + 7);
1091            pooled.update(&input[fed..12 * STAGE_LEN]);
1092            pooled.update_with(&input[12 * STAGE_LEN..], STAGE_LEN, &|tree, level, index, bytes| {
1093                calls.set(calls.get() + 1);
1094                tree.subtree_halves(level, index, bytes)
1095            });
1096            assert_eq!(calls.get(), 1, "one subtree of 64 KiB, above a threshold of 16 KiB");
1097            assert_eq!(*pooled.finalize().as_bytes(), crate::test::official::hash(mode, &input));
1098        }
1099    }
1100
1101    /// The threshold is held against the slice that goes to the core, not
1102    /// against the update that completes it. A group gathered in the stage
1103    /// from shorter updates keeps the pool where it reaches the threshold,
1104    /// though its last piece is one byte: the callback is asked for it.
1105    /// One byte under the threshold it is the serial update's, cut into
1106    /// the rows the serial update cuts. (A filter on the update's own
1107    /// length would pass every other test here and take the staged groups
1108    /// from a caller of `update_with` whose threshold is a group; a gate
1109    /// one byte early would keep the pool for the second case, where the
1110    /// callback is silent either way, the hooks holding each subtree to
1111    /// the threshold again, and only the rows tell.)
1112    #[test]
1113    fn a_staged_group_is_held_to_the_threshold_by_its_own_length() {
1114        crate::initialize();
1115        let input = painted();
1116        let input = &input[..2 * STAGE_LEN + 5];
1117        let asked = core::cell::RefCell::new(std::vec::Vec::new());
1118        let mut hasher = Hasher::new(Mode::Plain, None);
1119        hasher.update(&input[..STAGE_LEN - 1]);
1120        hasher.update_with(&input[STAGE_LEN - 1..STAGE_LEN], STAGE_LEN, &|tree, level, index, bytes| {
1121            asked.borrow_mut().push((level, index, bytes.len()));
1122            tree.subtree_halves(level, index, bytes)
1123        });
1124        assert_eq!(asked.borrow().as_slice(), &[(4, 0, STAGE_LEN)], "a group of the threshold's length, completed by one byte");
1125        hasher.update(&input[STAGE_LEN..]);
1126        assert_eq!(*hasher.finalize().as_bytes(), crate::test::official::hash(Mode::Plain, input));
1127        // One byte under the threshold, and the message's second group:
1128        // its first cuts no row on either path.
1129        let rows = || crate::COUNTED.with(|c| c[crate::Counted::Row as usize].replace(0));
1130        let (mut serial, mut pooled) = (Hasher::new(Mode::Plain, None), Hasher::new(Mode::Plain, None));
1131        serial.update(&input[..2 * STAGE_LEN - 1]);
1132        pooled.update(&input[..2 * STAGE_LEN - 1]);
1133        let last = &input[2 * STAGE_LEN - 1..2 * STAGE_LEN];
1134        rows();
1135        serial.update(last);
1136        let want = rows();
1137        pooled.update_with(last, STAGE_LEN + 1, &|_, _, _, _| panic!("a group one byte under the threshold holds no subtree for the callback"));
1138        assert_eq!(rows(), want, "a group one byte under the threshold: the serial update's rows");
1139        let rows_here = (4..=hasher::ROW).contains(&Platform::detect().simd_degree());
1140        assert_eq!(want > 0, rows_here, "the comparison is of something wherever the kernels cut rows");
1141        assert_eq!(pooled.finalize(), serial.finalize());
1142        assert_eq!(*pooled.finalize().as_bytes(), crate::test::official::hash(Mode::Plain, &input[..2 * STAGE_LEN]));
1143    }
1144
1145    #[test]
1146    fn pool_halves_use_the_subtrees_nonzero_place() {
1147        let calls = core::cell::Cell::new(0);
1148        crate::initialize();
1149        let input = painted();
1150        let input = &input[..2 * STAGE_LEN];
1151        let key = [3; KEY_LEN];
1152        let mut hasher = Hasher::new(Mode::Keyed(&key), None);
1153        hasher.update(&input[..STAGE_LEN]);
1154        hasher.update_with(&input[STAGE_LEN..], STAGE_LEN, &|tree, level, index, input| {
1155            assert_eq!((level, index, input.len()), (4, 1, STAGE_LEN));
1156            calls.set(calls.get() + 1);
1157            tree.subtree_halves(level, index, input)
1158        });
1159        assert_eq!(calls.get(), 1);
1160        assert_eq!(hasher.finalize().as_bytes(), blake3::keyed_hash(&key, input).as_bytes());
1161    }
1162
1163    fn painted() -> std::vec::Vec<u8> {
1164        let mut input = std::vec![0u8; 3 * STAGE_LEN];
1165        crate::test::paint_test_input(&mut input);
1166        input
1167    }
1168
1169    /// The length hint is a scheduling hint and never part of the hash:
1170    /// every hint, accurate, short, long, zero or absent, gives the
1171    /// one-shot digest, in every mode, through `new` and through `reset`.
1172    /// A Hasher that one day uses the hint keeps this contract or fails here.
1173    #[test]
1174    fn test_the_length_hint_never_changes_the_digest() {
1175        let input = painted();
1176        let key = [3u8; 32];
1177        for mode in [Mode::Plain, Mode::Keyed(&key), Mode::DeriveKey("hint test")] {
1178            for len in [0, 1, CHUNK_LEN, CHUNK_LEN + 1, STAGE_LEN + 7, input.len()] {
1179                let message = &input[..len];
1180                let want = crate::convenience::hash_with(mode, message);
1181                let hints = [None, Some(0), Some(1), Some(len as u64), Some(len as u64 / 2), Some(2 * len as u64 + 1), Some(u64::MAX)];
1182                let mut reused = Hasher::new(mode, Some(7));
1183                for hint in hints {
1184                    let mut fresh = Hasher::new(mode, hint);
1185                    for piece in message.chunks(1000) {
1186                        fresh.update(piece);
1187                    }
1188                    assert_eq!(fresh.finalize(), want, "{len} bytes, hint {hint:?}");
1189                    reused.reset();
1190                    reused.update(message);
1191                    assert_eq!(reused.clone().finalize(), want, "{len} bytes, hint {hint:?}, after reset");
1192                }
1193            }
1194        }
1195    }
1196
1197    /// In-place checkpointing overwrites the live stage prefix only. A
1198    /// full-capacity copy gives identical digests but changes the canary
1199    /// in unused destination storage, making the performance invariant
1200    /// deterministic rather than a timing assertion.
1201    #[test]
1202    fn clone_from_copies_only_the_live_stage_prefix() {
1203        crate::initialize();
1204        let input = painted();
1205        let key = [0x42u8; 32];
1206        let other_key = [0x73u8; 32];
1207        for mode in [Mode::Plain, Mode::Keyed(&key), Mode::DeriveKey("in-place prefix checkpoint")] {
1208            for len in [0usize, 64, 1024, 1025, 2048, STAGE_LEN - 1, STAGE_LEN, 2 * STAGE_LEN + 17] {
1209                let mut source = Hasher::new(mode, None);
1210                for part in input[..len].chunks(17) {
1211                    source.update(part);
1212                }
1213                // The live part of the stage: the staged bytes, and with any
1214                // staged the whole first block (zero past a message that
1215                // ends inside it); nothing of an empty stage.
1216                let live = if source.stage.len() == 0 { 0 } else { source.stage.len().max(BLOCK_LEN) };
1217                source.stage.fill_from_for_test(live, 0xbb);
1218                let mut copy = Hasher::new(Mode::Keyed(&other_key), None);
1219                copy.update(&input[..2 * STAGE_LEN]);
1220                copy.stage.fill_from_for_test(0, 0xaa);
1221                copy.clone_from(&source);
1222                let expected = crate::test::official::hash(mode, &input[..len]);
1223                assert_eq!(copy.count(), source.count());
1224                assert_eq!(*copy.clone().finalize().as_bytes(), expected);
1225                assert_eq!(copy.stage.as_bytes(), source.stage.as_bytes());
1226                // Sound: every byte in `live..STAGE_LEN` was painted `0xaa` on `copy`,
1227                // and `source.stage.len()..live` was zero-padded for nonempty stages.
1228                assert!((live..STAGE_LEN).all(|i| unsafe { copy.stage.byte_for_test(i) } == 0xaa), "unused stage copied at len={len}");
1229                if source.core.count() == 0 {
1230                    assert!(
1231                        (source.stage.len()..live).all(|i| unsafe { copy.stage.byte_for_test(i) } == 0),
1232                        "the first block is zero past a message whole in the stage, len={len}"
1233                    );
1234                }
1235                copy.update(&input[len..len + 129]);
1236                assert_eq!(*copy.clone().finalize().as_bytes(), crate::test::official::hash(mode, &input[..len + 129]));
1237                assert_eq!(*source.finalize().as_bytes(), expected, "checkpoint source is untouched");
1238                let mut out = [0u8; 129];
1239                copy.finalize_xof().fill(&mut out);
1240                assert_eq!(out.as_slice(), crate::test::official::xof(mode, &input[..len + 129], 0, out.len()));
1241            }
1242        }
1243    }
1244
1245    /// A whole group from a 16 KiB boundary goes to the core unstaged;
1246    /// shorter updates, a fresh hasher's first chunk among them, stage up
1247    /// to the next boundary, where the stage goes to the core. Staging
1248    /// gives the same digest either way, so only `staged` tells (BLAKE3
1249    /// #219).
1250    #[test]
1251    fn test_update_stages_exactly_what_it_must() {
1252        let input = painted();
1253        let mut h = Hasher::new(Mode::Plain, None);
1254        for (end, staged) in [(CHUNK_LEN, CHUNK_LEN), (CHUNK_LEN + 100, CHUNK_LEN + 100), (STAGE_LEN, 0), (2 * STAGE_LEN, 0)] {
1255            let from = h.count() as usize;
1256            h.update(&input[from..end]);
1257            assert_eq!(h.stage.len(), staged, "after {end} bytes");
1258        }
1259        assert_eq!(h.finalize(), crate::convenience::hash(&input[..2 * STAGE_LEN]));
1260    }
1261
1262    /// `finalize` and `finalize_xof` leave the Hasher as it was: asked
1263    /// twice they answer alike, and updates after them extend the message,
1264    /// as with official BLAKE3's Hasher. At every length class of the
1265    /// first part (a block, a chunk, the stage, beyond it), fed whole and
1266    /// in pieces of 7 bytes, in every mode.
1267    #[test]
1268    fn finalize_leaves_the_hasher_as_it_was_and_later_updates_extend_the_message() {
1269        crate::initialize();
1270        let input = painted();
1271        let key = [0x5a; 32];
1272        for mode in [Mode::Plain, Mode::Keyed(&key), Mode::DeriveKey("finalize, then more")] {
1273            for first in [0usize, 1, 17, 63, 64, 65, 1000, 1024, 1025, STAGE_LEN - 1, STAGE_LEN, STAGE_LEN + 1, 2 * STAGE_LEN - 300] {
1274                for more in [0usize, 1, 64, 1500, STAGE_LEN] {
1275                    for piece in [usize::MAX, 7] {
1276                        let what = std::format!("first={first} more={more} piece={piece}");
1277                        let mut h = Hasher::new(mode, None);
1278                        for part in input[..first].chunks(piece.min(first.max(1))) {
1279                            h.update(part);
1280                        }
1281                        let state = (h.stage.len(), h.core.count());
1282                        let want = crate::test::official::hash(mode, &input[..first]);
1283                        assert_eq!(*h.finalize().as_bytes(), want, "{what}");
1284                        let mut out = [0u8; 100];
1285                        h.finalize_xof().fill(&mut out);
1286                        assert_eq!(out.as_slice(), crate::test::official::xof(mode, &input[..first], 0, out.len()), "{what}");
1287                        assert_eq!(*h.finalize().as_bytes(), want, "asked again, {what}");
1288                        assert_eq!((h.stage.len(), h.core.count()), state, "untouched, {what}");
1289                        h.update(&input[first..first + more]);
1290                        assert_eq!(*h.finalize().as_bytes(), crate::test::official::hash(mode, &input[..first + more]), "extended, {what}");
1291                        h.finalize_xof().fill(&mut out);
1292                        assert_eq!(out.as_slice(), crate::test::official::xof(mode, &input[..first + more], 0, out.len()), "extended, {what}");
1293                    }
1294                }
1295            }
1296        }
1297    }
1298
1299    /// A message of a block or less is hashed from the stage's first block
1300    /// where it lies, so the block must be zero past the message whatever
1301    /// the Hasher held before (`first_block`): after a longer message and a
1302    /// reset (`finalize_each`), after `clone_from` over a longer message,
1303    /// and when its bytes arrive by the path that skips `update`'s own
1304    /// first block (`gather`, as `update_with` calls it).
1305    #[test]
1306    fn a_block_or_less_is_padded_whatever_the_hasher_held_before() {
1307        crate::initialize();
1308        let input = painted();
1309        let key = [0x77; 32];
1310        for mode in [Mode::Plain, Mode::Keyed(&key)] {
1311            for long in [0usize, 30, 64, 100, 5000, STAGE_LEN, STAGE_LEN + 300] {
1312                for short in [0usize, 1, 10, 31, 63, 64] {
1313                    let what = std::format!("long={long} short={short}");
1314                    let message = &input[1000..1000 + short];
1315                    let want = crate::test::official::hash(mode, message);
1316                    // Reset by finalize_each, then the short message, whole and in two parts.
1317                    for split in [0, short / 2] {
1318                        let mut hashers = std::vec![Hasher::new(mode, None)];
1319                        hashers[0].update(&input[..long]);
1320                        let mut out = [[0u8; OUT_LEN]];
1321                        crate::each::finalize_each(&mut hashers, &[0], &mut out);
1322                        assert_eq!(out[0], crate::test::official::hash(mode, &input[..long]), "{what}");
1323                        hashers[0].update(&message[..split]);
1324                        hashers[0].update(&message[split..]);
1325                        assert_eq!(*hashers[0].finalize().as_bytes(), want, "after a reset, {what} split={split}");
1326                        crate::each::finalize_each(&mut hashers, &[0], &mut out);
1327                        assert_eq!(out[0], want, "finished with others after a reset, {what} split={split}");
1328                    }
1329                    // clone_from over a Hasher that held the longer message.
1330                    let mut source = Hasher::new(mode, None);
1331                    source.update(message);
1332                    let mut copy = Hasher::new(mode, None);
1333                    copy.update(&input[..long]);
1334                    copy.clone_from(&source);
1335                    assert_eq!(*copy.finalize().as_bytes(), want, "after clone_from, {what}");
1336                    assert_eq!(*source.clone().finalize().as_bytes(), want, "a clone, {what}");
1337                    // The bytes by `gather`, in two parts.
1338                    let mut gathered = Hasher::new(mode, None);
1339                    gathered.gather(&message[..short / 2], None);
1340                    gathered.gather(&message[short / 2..], None);
1341                    assert_eq!(*gathered.finalize().as_bytes(), want, "gathered, {what}");
1342                }
1343            }
1344        }
1345    }
1346
1347    /// The assembly entry points `f` runs on this thread.
1348    fn entries_run(f: &mut dyn FnMut()) -> std::collections::BTreeSet<usize> {
1349        crate::RAN_ENTRIES.with(|r| r.borrow_mut().clear());
1350        f();
1351        crate::RAN_ENTRIES.with(|r| r.borrow().clone())
1352    }
1353
1354    /// A message whole in the stage is hashed by the kernels the one-shot
1355    /// call runs, and no others: by `finalize`, and by `finalize_each` when
1356    /// it finishes a hasher alone. Another path gives the same digest with
1357    /// more work (a copy of the core, a chunk state's block-by-block
1358    /// compression), so the kernels that ran are what tells (BLAKE3 #219).
1359    /// The control: a message a turn left in its chunk state on x86-64
1360    /// finishes by other kernels, so the record does tell.
1361    #[test]
1362    fn a_message_whole_in_the_stage_runs_the_one_shot_calls_kernels() {
1363        crate::initialize();
1364        let input = painted();
1365        let key = [0x21; 32];
1366        for mode in [Mode::Plain, Mode::Keyed(&key)] {
1367            for len in [0usize, 1, 64, 65, 1000, 1024, 1025, 5000, STAGE_LEN - 1] {
1368                let message = &input[..len];
1369                let one_shot = entries_run(&mut || {
1370                    crate::convenience::hash_with(mode, message);
1371                });
1372                // The record names the kernels of a chunk or less on every
1373                // machine; of longer inputs, only some machines' kernels.
1374                assert!(len > CHUNK_LEN || !one_shot.is_empty(), "a kernel ran, len={len}");
1375                let mut hashers = std::vec![Hasher::new(mode, None)];
1376                assert!(
1377                    entries_run(&mut || {
1378                        hashers[0].update(message);
1379                    })
1380                    .is_empty(),
1381                    "staging runs no kernel, len={len}"
1382                );
1383                assert_eq!(
1384                    entries_run(&mut || {
1385                        hashers[0].finalize();
1386                    }),
1387                    one_shot,
1388                    "finalize, len={len}"
1389                );
1390                let mut out = [[0u8; OUT_LEN]];
1391                assert_eq!(entries_run(&mut || crate::each::finalize_each(&mut hashers, &[0], &mut out)), one_shot, "finalize_each alone, len={len}");
1392                #[cfg(not(target_arch = "aarch64"))]
1393                if (65..=CHUNK_LEN).contains(&len) {
1394                    let mut turn = Hasher::new(mode, None);
1395                    turn.gather_part(message, None, true);
1396                    if matches!(mode, Mode::Plain) {
1397                        assert_eq!(
1398                            entries_run(&mut || {
1399                                turn.finalize();
1400                            }),
1401                            one_shot,
1402                            "plain turn stages first chunk, len={len}"
1403                        );
1404                    } else {
1405                        assert_ne!(
1406                            entries_run(&mut || {
1407                                turn.finalize();
1408                            }),
1409                            one_shot,
1410                            "the control: from a chunk state, len={len}"
1411                        );
1412                    }
1413                }
1414            }
1415        }
1416    }
1417
1418    /// A block or less into an empty stage is stored as one padded block
1419    /// (`update`'s own path, which the kernel's loads are served from);
1420    /// more, or into a stage that holds bytes, takes the longer path. The
1421    /// digest is the same either way, so the count tells (BLAKE3 #219).
1422    #[test]
1423    #[cfg(target_arch = "x86_64")]
1424    fn an_update_of_a_block_or_less_into_an_empty_stage_is_stored_padded() {
1425        crate::initialize();
1426        let input = painted();
1427        let padded = |hasher: &mut Hasher, bytes: &[u8]| {
1428            crate::COUNTED.with(|c| c[crate::Counted::PaddedFirstBlock as usize].set(0));
1429            hasher.update(bytes);
1430            crate::COUNTED.with(|c| c[crate::Counted::PaddedFirstBlock as usize].get())
1431        };
1432        for (len, expected) in [(0usize, 1), (1, 1), (63, 1), (64, 1), (65, 0), (1024, 0), (STAGE_LEN, 0)] {
1433            let mut h = Hasher::new(Mode::Plain, None);
1434            assert_eq!(padded(&mut h, &input[..len]), expected, "a fresh hasher, {len} bytes");
1435        }
1436        // Into a stage that holds bytes: the longer path. At the message's
1437        // next 16 KiB boundary the stage is empty again.
1438        let mut h = Hasher::new(Mode::Plain, None);
1439        assert_eq!(padded(&mut h, &input[..10]), 1);
1440        assert_eq!(padded(&mut h, &input[10..20]), 0, "the stage holds bytes");
1441        assert_eq!(padded(&mut h, &input[20..STAGE_LEN]), 0);
1442        assert_eq!(h.stage.len(), 0, "the stage went to the core");
1443        assert_eq!(padded(&mut h, &input[STAGE_LEN..STAGE_LEN + 64]), 1, "an empty stage again");
1444        assert_eq!(h.finalize(), crate::convenience::hash(&input[..STAGE_LEN + 64]));
1445    }
1446
1447    /// What the stack's rows and the tail's own core are for, counted
1448    /// (the digests are the same without them): a message's first group
1449    /// goes to the core as its two halves, every later whole group or
1450    /// more as a row; `finalize` with bytes staged after whole groups
1451    /// hashes them apart and reads the stack, the Hasher's core not
1452    /// copied, and the Hasher goes on to the same digests after. In every
1453    /// mode, at lengths around the groups.
1454    #[test]
1455    fn later_groups_are_rows_and_finalize_hashes_the_tail_apart() {
1456        crate::initialize();
1457        let mut input = std::vec![0u8; 8 * STAGE_LEN];
1458        crate::test::paint_test_input(&mut input);
1459        let count = |what: crate::Counted| crate::COUNTED.with(|c| c[what as usize].replace(0));
1460        let key = [0x51u8; 32];
1461        let rows_here = (4..=hasher::ROW).contains(&Platform::detect().simd_degree());
1462        for mode in [Mode::Plain, Mode::Keyed(&key), Mode::DeriveKey("rows and tails")] {
1463            let mut h = Hasher::new(mode, None);
1464            let (mut fed, mut rows) = (0, 0);
1465            // Pieces: a group; a group and a part; the rest of that group;
1466            // two groups and a part from the third boundary (the fourth
1467            // group, then the fifth: two subtrees); the rest of a group.
1468            for (n, new_rows) in [(STAGE_LEN, 0), (STAGE_LEN + 100, 1), (STAGE_LEN - 100, 1), (2 * STAGE_LEN + 7, 2), (STAGE_LEN - 7, 1)] {
1469                count(crate::Counted::Row);
1470                h.update(&input[fed..fed + n]);
1471                fed += n;
1472                rows += new_rows;
1473                assert_eq!(count(crate::Counted::Row), if rows_here { new_rows } else { 0 }, "{fed} bytes in: the update's subtrees after the first");
1474                count(crate::Counted::TailApart);
1475                assert_eq!(*h.finalize().as_bytes(), crate::test::official::hash(mode, &input[..fed]), "{fed} bytes");
1476                let apart = u64::from(h.stage.len() > 0);
1477                assert_eq!(count(crate::Counted::TailApart), apart, "{fed} bytes: {} staged", h.stage.len());
1478                let mut xof = [0u8; 100];
1479                h.finalize_xof().fill(&mut xof);
1480                assert_eq!(xof[..32], *h.finalize().as_bytes());
1481            }
1482            let _ = rows;
1483        }
1484        // A short piece staged into a stage that held another message:
1485        // the first block is the piece and zeros (`stage`), whatever was
1486        // there, on the path that copies (gather_part), which a first
1487        // update of a block or less on x86-64 does not take.
1488        let mut h = Hasher::new(Mode::Plain, None);
1489        h.update(&input[..3000]);
1490        h.reset();
1491        h.gather_part(&input[..5], None, false);
1492        assert_eq!((h.stage.len(), h.core.count()), (5, 0));
1493        assert_eq!(*h.finalize().as_bytes(), crate::test::official::hash(Mode::Plain, &input[..5]));
1494        h.gather_part(&input[5..70], None, false);
1495        assert_eq!(*h.finalize().as_bytes(), crate::test::official::hash(Mode::Plain, &input[..70]));
1496    }
1497
1498    /// After a turn of many hashers left a message's first chunk in the
1499    /// core (x86-64) and later bytes in the stage, `finalize` takes the
1500    /// copy of the core: the digest is right, and no tail is hashed apart.
1501    #[test]
1502    fn finalize_after_a_turn_that_left_a_chunk_in_the_core() {
1503        crate::initialize();
1504        let input = painted();
1505        let key = [0x53u8; 32];
1506        let mode = Mode::Keyed(&key);
1507        let mut hashers = [Hasher::new(mode, None), Hasher::new(mode, None)];
1508        crate::throughput::update_each(&mut hashers, &[(0, &input[..700]), (1, &input[..64])]);
1509        crate::throughput::update_each(&mut hashers, &[(0, &input[700..2500]), (1, &input[64..65])]);
1510        crate::COUNTED.with(|c| c[crate::Counted::TailApart as usize].set(0));
1511        for (h, len) in hashers.iter().zip([2500, 65]) {
1512            assert_eq!(*h.finalize().as_bytes(), crate::test::official::hash(mode, &input[..len]), "{len} bytes");
1513        }
1514        if !cfg!(target_arch = "aarch64") {
1515            assert!(hashers[0].core.chunk_state.count() > 0 && hashers[0].stage.len() > 0, "a chunk in the core, bytes in the stage");
1516            assert_eq!(crate::COUNTED.with(|c| c[crate::Counted::TailApart as usize].get()), 0);
1517        }
1518        // The same state made by hand, on every target: part of a chunk
1519        // in the core, or whole chunks short of a group, and bytes staged.
1520        for in_core in [700, 3 * CHUNK_LEN, STAGE_LEN + CHUNK_LEN] {
1521            let mut h = Hasher::new(Mode::Plain, None);
1522            h.core.update(&input[..in_core]);
1523            h.stage(&input[in_core..in_core + 900]);
1524            // The count with bytes in the core's chunk state. On AArch64
1525            // an update from offset zero leaves none there (it stages its
1526            // ragged end and sends the core whole groups), so no test of
1527            // such updates tells a count that subtracts them. This state,
1528            // made by hand, does.
1529            assert_eq!(h.count(), (in_core + 900) as u64, "{in_core} bytes in the core: the count");
1530            crate::COUNTED.with(|c| c[crate::Counted::TailApart as usize].set(0));
1531            assert_eq!(*h.finalize().as_bytes(), crate::test::official::hash(Mode::Plain, &input[..in_core + 900]), "{in_core} bytes in the core");
1532            assert_eq!(crate::COUNTED.with(|c| c[crate::Counted::TailApart as usize].get()), 0, "{in_core} bytes in the core: the copy");
1533        }
1534    }
1535
1536    /// An update of 16 KiB or more from a boundary gives the core its
1537    /// whole groups and stages what follows them, so that later pieces
1538    /// start on a boundary again: three pieces of a third of 64 KiB, then
1539    /// pieces that end off and on the boundaries. Sent whole, such pieces
1540    /// hash to the same digest in narrower subtrees, at half the speed
1541    /// (BLAKE3 #393), so only `staged` tells (BLAKE3 #219).
1542    #[test]
1543    fn test_an_updates_whole_groups_skip_the_stage_and_its_end_is_staged() {
1544        let mut input = std::vec![0u8; 65536 + 6 * STAGE_LEN];
1545        crate::test::paint_test_input(&mut input);
1546        let mut h = Hasher::new(Mode::Plain, None);
1547        let third = 65536 / 3;
1548        // After each update: the bytes staged, and the copies into the
1549        // stage the update made (one for a ragged end; two where it first
1550        // fills the stage to the boundary; none for whole groups alone).
1551        for (end, staged, copies) in [
1552            (third, third - STAGE_LEN, 1),
1553            (2 * third, 2 * third - 2 * STAGE_LEN, 2),
1554            (65536, 0, 1),
1555            (65536 + STAGE_LEN + 5, 5, 1),
1556            (65536 + 2 * STAGE_LEN, 0, 1),
1557            (65536 + 2 * STAGE_LEN + 100, 100, 1),
1558            (65536 + 4 * STAGE_LEN + 100, 100, 2),
1559            (65536 + 5 * STAGE_LEN, 0, 1),
1560            (65536 + 6 * STAGE_LEN, 0, 0),
1561        ] {
1562            let from = h.count() as usize;
1563            crate::COUNTED.with(|c| c[crate::Counted::Staged as usize].set(0));
1564            h.update(&input[from..end]);
1565            assert_eq!(crate::COUNTED.with(|c| c[crate::Counted::Staged as usize].get()), copies, "copies into the stage, after {end} bytes");
1566            let _ = copies;
1567            assert_eq!(h.stage.len(), staged, "after {end} bytes");
1568            assert_eq!(h.finalize(), crate::convenience::hash(&input[..end]), "after {end} bytes");
1569        }
1570    }
1571
1572    /// Construct a hasher whose chunk counter sits near the 2^64 - 1 byte
1573    /// BLAKE3 domain limit (without streaming 16 EiB) so unit tests can
1574    /// verify both acceptance of the final legal byte and refusal of the
1575    /// first byte past 2^64 - 1 on every ingress path.
1576    fn near_limit(remaining_bytes: u64) -> Hasher {
1577        assert!(remaining_bytes >= 1 && remaining_bytes <= CHUNK_LEN as u64 - 1);
1578        let mut h = Hasher::new(Mode::Plain, None);
1579        // Chunk counter (2^54 - 1) leaves 1023 bytes in the final legal chunk.
1580        h.core.chunk_state.set_chunk_counter((1u64 << 54) - 1);
1581        let fill = (CHUNK_LEN as u64 - 1 - remaining_bytes) as usize;
1582        if fill > 0 {
1583            h.core.chunk_state.update(&std::vec![0u8; fill]);
1584        }
1585        assert_eq!(u64::MAX - h.count(), remaining_bytes);
1586        h
1587    }
1588
1589    #[test]
1590    fn accepts_last_legal_byte_at_u64_max() {
1591        crate::initialize();
1592        let mut h = near_limit(10);
1593        h.update(&[1u8; 9]);
1594        h.update(&[2u8; 1]);
1595        assert_eq!(h.count(), u64::MAX);
1596        // Zero-length update at u64::MAX is still valid.
1597        h.update(&[]);
1598        assert_eq!(h.count(), u64::MAX);
1599    }
1600
1601    #[test]
1602    #[should_panic(expected = "BLAKE3 messages contain at most 2^64 - 1 bytes")]
1603    fn refuses_byte_past_u64_max_on_short_fast_path() {
1604        crate::initialize();
1605        let mut h = near_limit(1);
1606        h.update(&[0u8; 2]);
1607    }
1608
1609    #[test]
1610    #[should_panic(expected = "BLAKE3 messages contain at most 2^64 - 1 bytes")]
1611    fn refuses_byte_past_u64_max_after_filling_to_limit() {
1612        crate::initialize();
1613        let mut h = near_limit(1);
1614        h.update(&[0u8; 1]);
1615        assert_eq!(h.count(), u64::MAX);
1616        h.update(&[0u8; 1]);
1617    }
1618
1619    #[test]
1620    #[should_panic(expected = "BLAKE3 messages contain at most 2^64 - 1 bytes")]
1621    fn push_group_refuses_group_past_u64_max() {
1622        crate::initialize();
1623        let mut h = Hasher::new(Mode::Plain, None);
1624        // Counter at the last 16-chunk boundary before 2^54: adding STAGE_LEN
1625        // (16 KiB) would reach 2^64 bytes exactly.
1626        h.core.chunk_state.set_chunk_counter((1u64 << 54) - (STAGE_LEN / CHUNK_LEN) as u64);
1627        h.core.push_group(&[0u8; BLOCK_LEN]);
1628    }
1629
1630    #[test]
1631    #[should_panic(expected = "staged bytes exceed STAGE_LEN")]
1632    fn stage_append_checks_capacity() {
1633        crate::initialize();
1634        let mut h = Hasher::new(Mode::Plain, None);
1635        h.stage(&[0u8; STAGE_LEN]);
1636        h.stage(&[0u8; 1]);
1637    }
1638
1639    /// With `hold`, a stage that fills a whole group from the message's
1640    /// start is kept (`held_group`) and the rest of the input handed back,
1641    /// for `update_each` to hash the group beside other hashers' groups.
1642    #[test]
1643    fn test_gather_part_holds_a_whole_group() {
1644        let input = painted();
1645        let mut h = Hasher::new(Mode::Plain, None);
1646        h.update(&input[..STAGE_LEN]);
1647        h.update(&input[STAGE_LEN..STAGE_LEN + 100]);
1648        let rest = h.gather_part(&input[STAGE_LEN + 100..2 * STAGE_LEN + 50], None, true);
1649        assert_eq!(rest.len(), 50, "the rest handed back");
1650        let (counter, bytes) = h.held_group().expect("a whole group held");
1651        assert_eq!((counter, &bytes[..]), ((STAGE_LEN / CHUNK_LEN) as u64, &input[STAGE_LEN..2 * STAGE_LEN]));
1652    }
1653
1654    #[cfg(target_arch = "aarch64")]
1655    #[test]
1656    fn set_platform_for_test_updates_chunk_state_platform() {
1657        crate::initialize();
1658        let mut h = Hasher::new(Mode::Plain, None);
1659        h.set_platform_for_test(Platform::SME2);
1660        assert_eq!(h.platform(), Platform::SME2);
1661        h.set_platform_for_test(Platform::NEON);
1662        assert_eq!(h.platform(), Platform::NEON);
1663    }
1664
1665    /// Panicking inside `Hasher::update_with`'s callback (whether flushing
1666    /// staged bytes or hashing direct whole groups) or returning wrong-place
1667    /// `Cv`s poisons the `Hasher` so every subsequent hashing operation fails
1668    /// stop with `"Hasher was poisoned"` instead of silently hashing truncated
1669    /// bytes (#465). Over-length preflight refusal does not poison, `Clone`
1670    /// propagates poison, `clone_from` from a healthy source replaces it,
1671    /// `update_reader` refuses before invoking `Read::read`, and sibling
1672    /// hashers in `finalize_each` stay untouched while the poisoned entry
1673    /// stays poisoned.
1674    #[test]
1675    fn update_with_callback_panic_poisons_hasher_fail_stop() {
1676        use core::panic::AssertUnwindSafe;
1677        use std::io::{Read, Write as _};
1678
1679        fn panic_message(res: std::thread::Result<()>) -> String {
1680            let payload = res.expect_err("expected panic");
1681            payload.downcast_ref::<&str>().map(|s| (*s).to_owned()).or_else(|| payload.downcast_ref::<String>().cloned()).unwrap_or_default()
1682        }
1683        fn assert_poison_panic(label: &str, f: impl FnOnce()) {
1684            let msg = panic_message(std::panic::catch_unwind(AssertUnwindSafe(f)));
1685            assert!(msg.contains("Hasher was poisoned"), "{label}: expected poison panic, got {msg:?}");
1686        }
1687        struct MustNotRead;
1688        impl Read for MustNotRead {
1689            fn read(&mut self, _buf: &mut [u8]) -> std::io::Result<usize> {
1690                panic!("read must not be invoked on poisoned Hasher");
1691            }
1692        }
1693
1694        crate::initialize();
1695        let data = painted();
1696
1697        // Non-panicking `update_with` succeeds and leaves `Hasher` usable.
1698        let mut ok = Hasher::new(Mode::Plain, None);
1699        ok.update(&data[..8_192]);
1700        ok.update_with(&data[8_192..3 * STAGE_LEN], STAGE_LEN, &|tree, level, index, bytes| tree.subtree_halves(level, index, bytes));
1701        assert_eq!(ok.finalize(), crate::convenience::hash(&data[..3 * STAGE_LEN]));
1702
1703        // Over-length preflight refusal in `update_with` does not poison a healthy `Hasher`.
1704        let mut near_limit = Hasher::new(Mode::Plain, None);
1705        near_limit.core.chunk_state.set_chunk_counter((1u64 << 54) - 1);
1706        near_limit.update(&[0u8; CHUNK_LEN - 2]);
1707        let over_msg = panic_message(std::panic::catch_unwind(AssertUnwindSafe(|| {
1708            near_limit.update_with(&[0u8; 2], STAGE_LEN, &|t, l, i, b| t.subtree_halves(l, i, b));
1709        })));
1710        assert!(over_msg.contains("2^64 - 1"), "expected length refusal, got {over_msg:?}");
1711        near_limit.update(&[]);
1712        near_limit.update(&[0u8; 1]);
1713        assert_eq!(near_limit.count(), u64::MAX);
1714
1715        // 1. Poisoned via callback panic while flushing staged prefix bytes.
1716        let mut h = Hasher::new(Mode::Plain, None);
1717        h.update(&data[..8_192]);
1718        let boom = panic_message(std::panic::catch_unwind(AssertUnwindSafe(|| {
1719            h.update_with(&data[8_192..3 * STAGE_LEN], STAGE_LEN, &|_, _, _, _| panic!("callback boom"));
1720        })));
1721        assert!(boom.contains("callback boom"), "expected callback panic, got {boom:?}");
1722
1723        // Every direct consumer and cloned consumer must fail-stop with the poison panic.
1724        let cloned = h.clone();
1725        assert_poison_panic("cloned finalize", || {
1726            let _ = cloned.finalize();
1727        });
1728        let mut target = Hasher::new(Mode::Plain, None);
1729        target.clone_from(&h);
1730        assert_poison_panic("clone_from poisoned", || {
1731            let _ = target.finalize();
1732        });
1733        assert_poison_panic("finalize", || {
1734            let _ = h.finalize();
1735        });
1736        assert_poison_panic("finalize_xof", || {
1737            let _ = h.finalize_xof();
1738        });
1739        assert_poison_panic("empty update", || {
1740            h.update(&[]);
1741        });
1742        assert_poison_panic("1-byte update", || {
1743            h.update(b"x");
1744        });
1745        assert_poison_panic("short update", || {
1746            h.update(b"short");
1747        });
1748        assert_poison_panic("Write::write", || {
1749            let _ = h.write(b"abc");
1750        });
1751        assert_poison_panic("update_reader before read", || {
1752            let _ = h.update_reader(MustNotRead);
1753        });
1754        assert_poison_panic("subsequent update_with", || {
1755            h.update_with(b"more", STAGE_LEN, &|t, l, i, b| t.subtree_halves(l, i, b));
1756        });
1757
1758        // `update_each` and `finalize_each` must refuse the poisoned hasher while
1759        // preserving outputs, keeping the poisoned hasher poisoned, and leaving
1760        // unpoisoned sibling hashers unmarked and intact.
1761        let mut good = Hasher::new(Mode::Plain, None);
1762        good.update(b"still-good");
1763        let mut pair = [good, h];
1764        assert_poison_panic("update_each", || {
1765            crate::each::update_each(&mut pair, &[(1, &[])]);
1766        });
1767        let mut out = [[0xAAu8; OUT_LEN]; 2];
1768        assert_poison_panic("finalize_each", || {
1769            crate::each::finalize_each(&mut pair, &[0, 1], &mut out);
1770        });
1771        assert_eq!(out, [[0xAAu8; OUT_LEN]; 2], "refused finalize_each must leave outputs untouched");
1772        assert_poison_panic("rejected entry remains poisoned after finalize_each", || {
1773            let _ = pair[1].finalize();
1774        });
1775        let mut one = [[0u8; OUT_LEN]; 1];
1776        crate::each::finalize_each(&mut pair, &[0], &mut one);
1777        assert_eq!(one[0], *crate::convenience::hash(b"still-good").as_bytes());
1778
1779        // `clone_from` from a healthy source replaces the poisoned state.
1780        let mut fresh = Hasher::new(Mode::Plain, None);
1781        fresh.update(b"healthy");
1782        pair[1].clone_from(&fresh);
1783        assert_eq!(pair[1].finalize(), crate::convenience::hash(b"healthy"));
1784
1785        // 2. Poisoned via callback panic on direct whole-group path (empty stage on entry).
1786        let mut direct = Hasher::new(Mode::Plain, None);
1787        let direct_boom = panic_message(std::panic::catch_unwind(AssertUnwindSafe(|| {
1788            direct.update_with(&data[..2 * STAGE_LEN], STAGE_LEN, &|_, _, _, _| panic!("direct boom"));
1789        })));
1790        assert!(direct_boom.contains("direct boom"), "expected direct callback panic, got {direct_boom:?}");
1791        assert_poison_panic("direct-path finalize", || {
1792            let _ = direct.finalize();
1793        });
1794
1795        // 3. Poisoned via wrong-position `Cv` returned from callback.
1796        let mut wrong_cv = Hasher::new(Mode::Plain, None);
1797        let cv_err = panic_message(std::panic::catch_unwind(AssertUnwindSafe(|| {
1798            wrong_cv.update_with(&data[..2 * STAGE_LEN], STAGE_LEN, &|_, _, _, _| [Cv::at(0, 0, [0; 32]), Cv::at(0, 1, [0; 32])]);
1799        })));
1800        assert!(!cv_err.contains("Hasher was poisoned"), "expected Cv position panic, got {cv_err:?}");
1801        assert_poison_panic("wrong-cv finalize", || {
1802            let _ = wrong_cv.finalize();
1803        });
1804    }
1805}