1use crate::many::TABLE;
13use crate::platform::Platform;
14use crate::throughput::Block;
15use crate::{CHUNK_END, CHUNK_LEN, CHUNK_START, CVBytes, CVWords, ChunkState, Hash, Hasher, IncrementCounter, Mode, OUT_LEN};
16
17pub fn update_each(hashers: &mut [Hasher], pieces: &[(usize, &[u8])]) {
80 update_turn(hashers, pieces);
81}
82
83struct Marked<'a> {
87 hashers: &'a mut [Hasher],
88 which: &'a [usize],
89 count: usize,
90 active: bool,
91}
92
93impl Drop for Marked<'_> {
94 fn drop(&mut self) {
95 if self.active {
96 for &i in &self.which[..self.count] {
97 self.hashers[i].clear_finishing();
98 }
99 }
100 }
101}
102
103pub fn finalize_each(hashers: &mut [Hasher], which: &[usize], out: &mut [[u8; OUT_LEN]]) {
135 assert_eq!(which.len(), out.len(), "one digest per message named");
136 let mut marked = Marked { hashers, which, count: 0, active: true };
137 for &i in which {
138 assert!(i < marked.hashers.len(), "finalize_each names hasher {i} of {}", marked.hashers.len());
139 assert!(!marked.hashers[i].mark_finishing(), "each finalized index is distinct");
140 marked.count += 1;
141 }
142 let hashers = &mut *marked.hashers;
143 if which.is_empty() {
144 marked.active = false;
145 return;
146 }
147 if which.len() == 1 {
148 let i = which[0];
149 out[0] = *hashers[i].take_root_hash().as_bytes();
150 hashers[i].reset();
151 marked.active = false;
152 return;
153 }
154 #[cfg(target_arch = "x86_64")]
157 crate::ffi_partial::finalize_each(hashers, which, out);
158 #[cfg(target_arch = "aarch64")]
159 crate::ffi_output::finalize_each(hashers, which, out);
160 marked.active = false;
161}
162
163#[inline]
164pub(crate) fn finalize_indices_serial(hashers: &mut [Hasher], w_chunk: &[usize], slots: &[u8], o_chunk: &mut [[u8; OUT_LEN]]) {
165 for &k in slots {
166 let k = usize::from(k);
167 o_chunk[k] = *hashers[w_chunk[k]].take_root_hash().as_bytes();
168 }
169}
170
171pub(crate) fn hash_held_leaves_serial(hashers: &[Hasher], held: &[usize], platform: Platform, level: &mut [[u8; OUT_LEN]]) {
174 const PER: usize = crate::STAGE_LEN / CHUNK_LEN;
175 for (k, &i) in held.iter().enumerate() {
176 let h = &hashers[i];
177 let (counter, bytes) = h.held_group().expect("a held group");
178 let refs: [&[u8; CHUNK_LEN]; PER] = core::array::from_fn(|j| bytes[j * CHUNK_LEN..(j + 1) * CHUNK_LEN].try_into().unwrap());
179 let domain = h.domain();
180 platform.hash_many(
181 &refs,
182 domain.key(),
183 counter,
184 IncrementCounter::Yes,
185 domain.flags(),
186 CHUNK_START,
187 CHUNK_END,
188 level[k * PER..(k + 1) * PER].as_flattened_mut(),
189 );
190 }
191}
192
193pub(crate) fn commit_held_groups(hashers: &mut [Hasher], held: &[usize], level: &[[u8; OUT_LEN]], next: &[[u8; OUT_LEN]]) {
197 for (k, &i) in held.iter().enumerate() {
198 let (counter, _) = hashers[i].held_group().unwrap();
199 let mut result = [0u8; crate::BLOCK_LEN];
200 if counter == 0 {
201 result.copy_from_slice(next[2 * k..2 * k + 2].as_flattened());
202 } else {
203 result[..OUT_LEN].copy_from_slice(&level[k]);
204 }
205 hashers[i].take_held(&result);
206 }
207}
208
209fn update_turn(hashers: &mut [Hasher], pieces: &[(usize, &[u8])]) {
223 struct Held<'h> {
231 hashers: &'h mut [Hasher],
232 held: crate::stack_vec::StackVec<usize, TABLE>,
233 }
234 impl Drop for Held<'_> {
235 fn drop(&mut self) {
236 flush_held(self.hashers, &mut self.held);
237 }
238 }
239 let mut turn = Held { hashers, held: crate::stack_vec::StackVec::new() };
240 let mut waiting = crate::stack_vec::StackVec::<(usize, &[u8]), TABLE>::new();
241 for &(i, bytes) in pieces {
242 if waiting.is_full() || turn.held.is_full() {
243 drain(turn.hashers, &mut turn.held, &mut waiting);
244 }
245 if turn.hashers[i].held_group().is_some() {
246 waiting.push((i, bytes));
247 continue;
248 }
249 gather(turn.hashers, i, bytes, &mut turn.held, &mut waiting);
250 }
251 drain(turn.hashers, &mut turn.held, &mut waiting);
252}
253
254fn gather<'a>(
257 hashers: &mut [Hasher],
258 i: usize,
259 bytes: &'a [u8],
260 held: &mut crate::stack_vec::StackVec<usize, TABLE>,
261 waiting: &mut crate::stack_vec::StackVec<(usize, &'a [u8]), TABLE>,
262) {
263 debug_assert!(hashers[i].held_group().is_none(), "a held hasher's bytes wait");
265 let rest = hashers[i].gather_part(bytes, None, true);
266 assert!(rest.len() < bytes.len() || bytes.is_empty(), "a turn's pass gathered nothing");
267 if hashers[i].held_group().is_some() {
268 held.push(i);
269 if !rest.is_empty() {
270 waiting.push((i, rest));
271 }
272 }
273}
274
275fn drain<'a>(hashers: &mut [Hasher], held: &mut crate::stack_vec::StackVec<usize, TABLE>, waiting: &mut crate::stack_vec::StackVec<(usize, &'a [u8]), TABLE>) {
282 loop {
283 flush_held(hashers, held);
284 if waiting.is_empty() {
285 return;
286 }
287 let batch = core::mem::take(waiting);
288 for &(i, bytes) in &batch {
289 if hashers[i].held_group().is_some() {
290 waiting.push((i, bytes));
291 } else {
292 gather(hashers, i, bytes, held, waiting);
293 }
294 }
295 assert!(waiting.len() < batch.len() || !held.is_empty(), "drain made no progress");
296 }
297}
298
299const INDEPENDENT_MIN: usize = 3;
306
307fn flush_held(hashers: &mut [Hasher], held: &mut crate::stack_vec::StackVec<usize, TABLE>) {
310 if held.is_empty() {
311 return;
312 }
313 let list = core::mem::take(held);
314 hash_held(hashers, &list);
315}
316
317#[cfg(test)]
318std::thread_local! {
319 static HELD_GROUPS: core::cell::RefCell<Vec<Vec<usize>>> = const { core::cell::RefCell::new(Vec::new()) };
321}
322
323fn independent_lanes(hashers: &mut [Hasher], held: &[usize]) -> bool {
330 let Some(&first) = held.first() else { return false };
331 let platform = hashers[first].platform();
332 #[cfg(target_arch = "x86_64")]
333 if !matches!(platform, Platform::AVX2 | Platform::AVX512) {
334 return false;
335 }
336 if held.len() < INDEPENDENT_MIN || held.iter().all(|&i| hashers[i].is_plain()) {
338 return false;
339 }
340 crate::ffi_output::held_groups(hashers, held, platform);
341 #[cfg(test)]
342 let _ = HELD_GROUPS.try_with(|groups| groups.borrow_mut().push(held.to_vec()));
343 crate::counted(crate::Counted::HeldPass);
344 true
345}
346
347#[cfg(test)]
348std::thread_local! {
349 static LAST_COHORT_TIER: core::cell::Cell<usize> = const { core::cell::Cell::new(0) };
351}
352
353fn hash_held(hashers: &mut [Hasher], held: &[usize]) {
359 if independent_lanes(hashers, held) {
360 return;
361 }
362 const PLAIN_TILE: usize = 16;
367 let mut plain = crate::stack_vec::StackVec::<usize, TABLE>::new();
368 plain.extend(held.iter().copied().filter(|&i| hashers[i].is_plain()));
369 if !plain.is_empty() {
370 #[cfg(test)]
371 let _ = HELD_GROUPS.try_with(|groups| groups.borrow_mut().push(plain.as_slice().to_vec()));
372 #[cfg(test)]
373 crate::counted(crate::Counted::HeldPass);
374 let turn = crate::platform::Sme2Turn::take(hashers[plain[0]].platform(), true);
375 let platform = turn.platform();
376 if plain.len() == 1 {
377 hash_cohort_on::<1>(hashers, &plain, platform);
378 } else {
379 for tile in plain.as_slice().chunks(PLAIN_TILE) {
380 hash_cohort_on::<PLAIN_TILE>(hashers, tile, platform);
381 }
382 }
383 }
384 for &i in held {
385 if !hashers[i].is_plain() {
386 hash_cohort::<1>(hashers, &[i]);
387 }
388 }
389}
390
391const STAGE_PARENTS: usize = ALONE_CHUNKS / 2;
393
394pub(crate) struct HeldWorkspace<const N: usize> {
398 level: crate::stack_vec::StackVec<[Block; STAGE_PARENTS], N>,
399 next: crate::stack_vec::StackVec<[Block; STAGE_PARENTS / 2], N>,
400}
401
402impl<const N: usize> HeldWorkspace<N> {
403 #[inline(always)]
405 pub(crate) fn new() -> Self {
406 const {
407 assert!(ALONE_CHUNKS == 16 && crate::STAGE_LEN == ALONE_CHUNKS * CHUNK_LEN);
408 }
409 Self { level: crate::stack_vec::StackVec::new(), next: crate::stack_vec::StackVec::new() }
410 }
411
412 pub(crate) fn buffers(&mut self, count: usize) -> (&mut [CVBytes], &mut [CVBytes]) {
415 assert!(count > 0 && count <= N && self.level.is_empty() && self.next.is_empty(), "one fresh HeldWorkspace per cohort");
416 self.level.extend(core::iter::repeat_n([Block::ZERO; STAGE_PARENTS], count));
417 self.next.extend(core::iter::repeat_n([Block::ZERO; STAGE_PARENTS / 2], count));
418 let (level, _) = Block::bytes_mut(self.level.as_mut_slice().as_flattened_mut()).as_chunks_mut::<OUT_LEN>();
419 let (next, _) = Block::bytes_mut(self.next.as_mut_slice().as_flattened_mut()).as_chunks_mut::<OUT_LEN>();
420 (level, next)
421 }
422}
423
424#[inline(never)]
428fn hash_cohort<const N: usize>(hashers: &mut [Hasher], alike: &[usize]) {
429 let first = alike[0];
430 #[cfg(test)]
431 let _ = HELD_GROUPS.try_with(|groups| groups.borrow_mut().push(alike.to_vec()));
432 #[cfg(test)]
433 crate::counted(crate::Counted::HeldPass);
434 let turn = crate::platform::Sme2Turn::take(hashers[first].platform(), true);
435 hash_cohort_on::<N>(hashers, alike, turn.platform());
436}
437
438#[inline(never)]
443fn hash_cohort_on<const N: usize>(hashers: &mut [Hasher], alike: &[usize], platform: Platform) {
444 use crate::{BLOCK_LEN, PARENT};
445 let first = alike[0];
446 #[cfg(test)]
447 let _ = LAST_COHORT_TIER.try_with(|t| t.set(N));
448 let domain = hashers[first].domain();
449 let flags = domain.flags();
450 let key = if domain.is_plain() { *crate::IV } else { *domain.key() };
453 let mut work = HeldWorkspace::<N>::new();
454 let (mut level, mut next) = work.buffers(alike.len());
455 #[cfg(target_arch = "aarch64")]
456 let on_sme2 = matches!(platform, Platform::SME2);
457 #[cfg(not(target_arch = "aarch64"))]
458 let on_sme2 = false;
459 {
460 let mut refs = crate::stack_vec::StackVec::<[&[u8; CHUNK_LEN]; ALONE_CHUNKS], N>::new();
461 refs.extend(alike.iter().map(|&i| {
462 let hasher = &hashers[i];
463 assert!(alike.len() == 1 || hasher.is_plain(), "only plain hashers share a cohort");
466 let stage = hasher.held_group().expect("a held group").1;
467 core::array::from_fn(|j| stage[j * CHUNK_LEN..(j + 1) * CHUNK_LEN].try_into().unwrap())
468 }));
469 let refs = refs.as_slice().as_flattened();
470 let mut counters = crate::stack_vec::StackVec::<u64, N>::new();
471 counters.extend(alike.iter().map(|&i| hashers[i].held_group().unwrap().0));
472 if on_sme2 {
473 #[cfg(target_arch = "aarch64")]
474 unsafe {
477 crate::sme2::hash_groups_at(refs, &counters, &key, flags, CHUNK_START, CHUNK_END, level.as_flattened_mut())
478 };
479 } else {
480 for (k, &counter) in counters.iter().enumerate() {
481 platform.hash_many(
482 &refs[k * ALONE_CHUNKS..(k + 1) * ALONE_CHUNKS],
483 &key,
484 counter,
485 IncrementCounter::Yes,
486 flags,
487 CHUNK_START,
488 CHUNK_END,
489 level[k * ALONE_CHUNKS..(k + 1) * ALONE_CHUNKS].as_flattened_mut(),
490 );
491 }
492 }
493 }
494 let parent_flags = flags | PARENT;
495 let mut per = ALONE_CHUNKS;
496 while per > 1 {
497 let count = alike.len() * per / 2;
498 let bytes = level[..2 * count].as_flattened();
499 if on_sme2 {
500 #[cfg(target_arch = "aarch64")]
504 unsafe {
507 crate::sme2::hash_block_run(bytes, &key, parent_flags, next[..count].as_flattened_mut())
508 };
509 } else {
510 let (full, tail) = bytes.as_chunks::<BLOCK_LEN>().0.as_chunks::<STAGE_PARENTS>();
513 let mut rows = crate::stack_vec::StackVec::<_, N>::new();
514 rows.extend(full.iter().map(|row| row.each_ref()));
515 if let Some(first) = tail.first() {
516 rows.push(core::array::from_fn(|i| tail.get(i).unwrap_or(first)));
517 }
518 platform.hash_many(&rows.as_slice().as_flattened()[..count], &key, 0, IncrementCounter::No, parent_flags, 0, 0, next[..count].as_flattened_mut());
519 }
520 core::mem::swap(&mut level, &mut next);
521 per /= 2;
522 }
523 commit_held_groups(hashers, alike, level, next);
524}
525
526const ALONE_CHUNKS: usize = 16;
528
529pub fn hash_each(mode: Mode, items: &[(&[Block], usize)], out: &mut [[u8; OUT_LEN]]) {
547 assert_eq!(items.len(), out.len(), "one digest per item");
548 let mut room = core::mem::MaybeUninit::uninit();
549 let (key, flags) = mode.key(&mut room);
550 hash_each_on(key, flags, items, out, Platform::detect(), |item| crate::hash_serial(item, key, flags));
551}
552
553#[cfg(target_arch = "aarch64")]
556pub(crate) const BY_BLOCKS_AT_ONCE: usize = TABLE;
557#[cfg(not(target_arch = "aarch64"))]
558pub(crate) const BY_BLOCKS_AT_ONCE: usize = 64;
559
560pub(crate) fn hash_by_blocks(items: &[&[u8]], key: &CVWords, flags: u8, out: &mut [[u8; OUT_LEN]], platform: Platform) {
571 hash_chunks_by_blocks(items, key, 0, flags, CHUNK_END | crate::ROOT, out, platform);
572}
573
574fn hash_chunks_by_blocks(items: &[&[u8]], key: &CVWords, counter: u64, flags: u8, flags_end: u8, out: &mut [[u8; OUT_LEN]], platform: Platform) {
575 assert_eq!(items.len(), out.len(), "one digest per item");
576 assert!(items.iter().all(|i| i.len() <= CHUNK_LEN), "items of up to a chunk");
577 for (items, out) in items.chunks(BY_BLOCKS_AT_ONCE).zip(out.chunks_mut(BY_BLOCKS_AT_ONCE)) {
578 by_blocks_at_once(items, key, counter, flags, flags_end, out, platform);
579 }
580}
581
582fn by_blocks_at_once(items: &[&[u8]], key: &CVWords, counter: u64, flags: u8, flags_end: u8, out: &mut [[u8; OUT_LEN]], platform: Platform) {
583 const GROUP: usize = 16;
584 const BINS: usize = 16;
585 const { assert!(BINS * crate::BLOCK_LEN == crate::CHUNK_LEN) };
586 const { assert!(BY_BLOCKS_AT_ONCE <= u8::MAX as usize) };
587 let n = items.len();
588 if n == 0 {
589 return;
590 }
591 #[cfg(target_arch = "aarch64")]
598 {
599 let len = items[0].len();
600 if counter == 0
601 && matches!(platform, Platform::SME2)
602 && items.len() * len >= crate::SME2_SIZED_LEN
603 && len % crate::BLOCK_LEN == 0
604 && items.iter().all(|item| item.len() == len)
605 {
606 let turn = crate::platform::Sme2Turn::take(platform, true);
607 if matches!(turn.platform(), Platform::SME2) {
608 let mut lanes: crate::stack_vec::StackVec<*const u8, BY_BLOCKS_AT_ONCE> = items.iter().map(|item| item.as_ptr()).collect();
609 let last = *lanes.last().unwrap();
610 while lanes.len() % GROUP != 0 {
611 lanes.push(last);
612 }
613 crate::counted(crate::Counted::ByBlocksCall);
614 unsafe {
618 crate::sme2::hash_messages_raw(&lanes, len / crate::BLOCK_LEN, key, flags, CHUNK_START, flags_end, crate::BLOCK_LEN, out.as_flattened_mut())
619 };
620 return;
621 }
622 }
623 }
624 let whole = |item: &[u8]| item.len().saturating_sub(1) / crate::BLOCK_LEN;
625 let mut order = [0u8; BY_BLOCKS_AT_ONCE];
626 if items.is_sorted_by_key(|item| whole(item)) {
627 for (slot, i) in order[..n].iter_mut().zip(0u8..) {
628 *slot = i;
629 }
630 } else {
631 let mut ends = [0u8; BINS];
632 for item in items {
633 ends[whole(item)] += 1;
634 }
635 let mut sum = 0u8;
636 for end in &mut ends {
637 sum += *end;
638 *end = sum;
639 }
640 let n_u8 = u8::try_from(n).expect("chunk <= BY_BLOCKS_AT_ONCE");
641 for i in (0..n_u8).rev() {
642 let bin = whole(items[usize::from(i)]);
643 ends[bin] -= 1;
644 order[usize::from(ends[bin])] = i;
645 }
646 }
647 let order = &order[..n];
648 #[cfg(target_arch = "aarch64")]
651 let last_lanes = crate::neon_hybrid::sha3_detected();
652 #[cfg(not(target_arch = "aarch64"))]
653 let last_lanes = false;
654 let mut cvs = [*key; BY_BLOCKS_AT_ONCE];
655 for same_blocks in order.chunk_by(|&a, &b| whole(items[usize::from(a)]) == whole(items[usize::from(b)])) {
658 let k = whole(items[usize::from(same_blocks[0])]);
659 #[cfg(target_arch = "aarch64")]
660 if last_lanes {
661 for group in same_blocks.chunks(GROUP) {
662 let inputs: crate::stack_vec::StackVec<*const u8, GROUP> = group.iter().map(|&i| items[usize::from(i)].as_ptr()).collect();
663 let mut last_blocks = [[0u8; crate::BLOCK_LEN]; GROUP];
664 let mut lengths = [0u32; GROUP];
665 for ((&i, block), len) in group.iter().zip(&mut last_blocks).zip(&mut lengths) {
666 let tail = &items[usize::from(i)][k * crate::BLOCK_LEN..];
667 block[..tail.len()].copy_from_slice(tail);
668 *len = u32::from(u8::try_from(tail.len()).expect("tail block <= 64"));
669 }
670 let lasts: crate::stack_vec::StackVec<*const u8, GROUP> = last_blocks[..group.len()].iter().map(|b| b.as_ptr()).collect();
671 let mut digests = [0u8; GROUP * OUT_LEN];
672 crate::counted(crate::Counted::ByBlocksCall);
673 unsafe {
676 crate::neon_hybrid::hash_last_lanes(
677 &inputs,
678 &lasts,
679 &lengths[..group.len()],
680 k + 1,
681 key,
682 counter,
683 flags,
684 CHUNK_START,
685 flags_end,
686 &mut digests[..group.len() * OUT_LEN],
687 );
688 }
689 for (&i, digest) in group.iter().zip(digests.chunks_exact(OUT_LEN)) {
690 out[usize::from(i)].copy_from_slice(digest);
691 }
692 }
693 continue;
694 }
695 if k > 0 {
696 for group in same_blocks.chunks(GROUP) {
697 #[cfg_attr(not(target_arch = "x86_64"), allow(unused_mut))]
698 let mut inputs: crate::stack_vec::StackVec<*const u8, GROUP> = group.iter().map(|&i| items[usize::from(i)].as_ptr()).collect();
699 #[cfg(target_arch = "x86_64")]
700 let padded = crate::ffi_output::pad_by_blocks_inputs(&mut inputs, platform);
701 let mut lanes = [0u8; GROUP * OUT_LEN];
702 crate::counted(crate::Counted::ByBlocksCall);
703 #[cfg(target_arch = "x86_64")]
707 unsafe {
708 crate::pair::hash_many_blocks(platform, &inputs, k, key, counter, false, flags, CHUNK_START, 0, &mut lanes[..padded * OUT_LEN])
709 };
710 #[cfg(target_arch = "aarch64")]
714 unsafe {
715 crate::neon_hybrid::hash_messages_raw(
716 inputs.as_ptr(),
717 group.len(),
718 k,
719 key,
720 counter,
721 flags,
722 CHUNK_START,
723 0,
724 crate::BLOCK_LEN,
725 &mut lanes[..group.len() * OUT_LEN],
726 )
727 };
728 for (n, &i) in group.iter().enumerate() {
729 cvs[usize::from(i)] = crate::platform::words_from_le_bytes_32(lanes[n * OUT_LEN..][..OUT_LEN].try_into().unwrap());
730 }
731 }
732 }
733 }
734 if last_lanes {
735 return;
736 }
737 #[cfg(target_arch = "x86_64")]
738 let serial_start = crate::ffi_output::finish_last_blocks_order(&order, items, &cvs, counter, flags, flags_end, out, platform);
739 #[cfg(not(target_arch = "x86_64"))]
740 let serial_start = 0usize;
741 for &i in &order[serial_start..] {
742 let i = usize::from(i);
743 let item = items[i];
744 let k = whole(item);
745 let mut cv = cvs[i];
746 let mut block = [0u8; crate::BLOCK_LEN];
747 let last = item.len() - k * crate::BLOCK_LEN;
748 block[..last].copy_from_slice(&item[k * crate::BLOCK_LEN..]);
749 let start = if k == 0 { CHUNK_START } else { 0 };
750 platform.compress_in_place(&mut cv, &block, u8::try_from(last).expect("last block <= 64"), counter, flags | start | flags_end);
751 out[i] = crate::hasher::le_bytes(&cv);
752 }
753}
754
755pub(crate) trait Item {
758 fn bytes(&self) -> &[u8];
759}
760
761impl Item for &[u8] {
762 #[inline(always)]
763 fn bytes(&self) -> &[u8] {
764 self
765 }
766}
767
768impl Item for (&[Block], usize) {
769 #[inline(always)]
770 fn bytes(&self) -> &[u8] {
771 &Block::bytes(self.0)[..self.1]
772 }
773}
774
775pub(crate) fn hash_each_on<I: Item>(key: &CVWords, flags: u8, items: &[I], out: &mut [[u8; OUT_LEN]], platform: Platform, alone: impl Fn(&[u8]) -> Hash) {
779 let key = *key;
780 #[cfg(target_arch = "x86_64")]
782 let platform_takes = crate::pair::takes_platform(platform);
783 #[cfg(target_arch = "aarch64")]
786 let platform_takes = true;
787 let by_blocks = platform_takes && items.iter().filter(|i| i.bytes().len() <= CHUNK_LEN).take(2).count() == 2;
788 if by_blocks {
789 let mut small_done = 0usize;
793 let mut small = (0..items.len()).filter(|&i| items[i].bytes().len() <= CHUNK_LEN).peekable();
794 while small.peek().is_some() {
795 let part: crate::stack_vec::StackVec<usize, BY_BLOCKS_AT_ONCE> = small.by_ref().take(BY_BLOCKS_AT_ONCE).collect();
796 small_done += part.len();
797 let bytes: crate::stack_vec::StackVec<&[u8], BY_BLOCKS_AT_ONCE> = part.iter().map(|&i| items[i].bytes()).collect();
798 let mut digests = [[0u8; OUT_LEN]; BY_BLOCKS_AT_ONCE];
799 hash_by_blocks(&bytes, &key, flags, &mut digests[..part.len()], platform);
800 for (&i, digest) in part.iter().zip(&digests) {
801 out[i] = *digest;
802 }
803 }
804 if small_done == items.len() {
805 return;
806 }
807 }
808 if items.is_empty() {
809 return;
810 }
811 if SHARED
817 .try_with(|shared| {
818 let mut shared = shared.try_borrow_mut().expect("one collection at a time on a thread");
819 hash_each_middle(&mut shared, &key, flags, items, out, platform, by_blocks, platform_takes, &alone);
820 })
821 .is_err()
822 {
823 let mut local = Shared { messages: Vec::new(), cvs: Vec::new() };
824 hash_each_middle(&mut local, &key, flags, items, out, platform, by_blocks, platform_takes, &alone);
825 }
826}
827
828#[allow(clippy::too_many_arguments)]
831fn hash_each_middle<I: Item>(
832 shared: &mut Shared,
833 key: &CVWords,
834 flags: u8,
835 items: &[I],
836 out: &mut [[u8; OUT_LEN]],
837 platform: Platform,
838 by_blocks: bool,
839 platform_takes: bool,
840 alone: &impl Fn(&[u8]) -> Hash,
841) {
842 let Shared { messages, cvs } = shared;
843 messages.clear();
844 #[cfg(target_arch = "aarch64")]
845 let last_lanes = crate::neon_hybrid::sha3_detected();
846 #[cfg(not(target_arch = "aarch64"))]
847 let last_lanes = false;
848 let min_k = usize::from(!last_lanes);
849 let mut slots = 0;
850 let mut most_full = 0;
851 let mut max_chunks = 0usize;
852 let mut partial_any = [false; ALONE_CHUNKS];
853 let mut partial_seen = [0u16; ALONE_CHUNKS];
854 let mut partial_shared = [false; ALONE_CHUNKS];
855 for (i, item) in items.iter().map(Item::bytes).enumerate() {
856 let chunks = item.len().div_ceil(CHUNK_LEN);
857 if chunks <= 1 && by_blocks {
858 continue;
859 }
860 if chunks <= 1 || chunks >= ALONE_CHUNKS {
861 out[i] = *alone(item).as_bytes();
862 } else {
863 let full = item.len() / CHUNK_LEN;
864 most_full = most_full.max(full);
865 max_chunks = max_chunks.max(chunks);
866 if full != chunks {
867 partial_any[full] = true;
868 let tail = &item[full * CHUNK_LEN..];
869 let k = (tail.len() - 1) / crate::BLOCK_LEN;
870 if k >= min_k {
871 let bit = 1u16 << k;
872 if (partial_seen[full] & bit) != 0 {
873 partial_shared[full] = true;
874 }
875 partial_seen[full] |= bit;
876 }
877 }
878 messages.push((i, slots));
879 slots += chunks;
880 }
881 }
882 if messages.is_empty() {
883 return;
884 }
885 cvs.clear();
886 cvs.resize(slots, [0u8; OUT_LEN]);
887 for c in 1..ALONE_CHUNKS {
894 if !partial_any[c] {
895 continue;
896 }
897 if platform_takes && partial_shared[c] {
898 let mut slices = crate::stack_vec::StackVec::<&[u8], BY_BLOCKS_AT_ONCE>::new();
899 let mut owners = crate::stack_vec::StackVec::<usize, BY_BLOCKS_AT_ONCE>::new();
900 let mut flush_partial = |slices: &mut crate::stack_vec::StackVec<&[u8], BY_BLOCKS_AT_ONCE>,
901 owners: &mut crate::stack_vec::StackVec<usize, BY_BLOCKS_AT_ONCE>| {
902 let mut digests = [[0u8; OUT_LEN]; BY_BLOCKS_AT_ONCE];
903 hash_chunks_by_blocks(slices, key, c as u64, flags, CHUNK_END, &mut digests[..slices.len()], platform);
904 for (&slot, digest) in owners.iter().zip(&digests) {
905 cvs[slot] = *digest;
906 }
907 slices.clear();
908 owners.clear();
909 };
910 for &(i, at) in messages.iter() {
911 let item = items[i].bytes();
912 let full = item.len() / CHUNK_LEN;
913 if full == c && item.len() > c * CHUNK_LEN {
914 slices.push(&item[c * CHUNK_LEN..]);
915 owners.push(at + c);
916 if slices.is_full() {
917 flush_partial(&mut slices, &mut owners);
918 }
919 }
920 }
921 if !slices.is_empty() {
922 flush_partial(&mut slices, &mut owners);
923 }
924 } else {
925 for &(i, at) in messages.iter() {
926 let item = items[i].bytes();
927 let full = item.len() / CHUNK_LEN;
928 if full == c && item.len() > c * CHUNK_LEN {
929 cvs[at + c] = ChunkState::new(key, c as u64, flags, platform).update(&item[c * CHUNK_LEN..]).output().chaining_value();
930 }
931 }
932 }
933 }
934 #[cfg(target_arch = "aarch64")]
939 let turn = crate::sme2::turn_for_each_middle(platform, items, messages);
940 #[cfg(target_arch = "aarch64")]
941 let round_platform = turn.platform();
942 #[cfg(not(target_arch = "aarch64"))]
943 let round_platform = platform;
944 for k in 0..most_full {
945 crate::counted(crate::Counted::EachRound);
946 let mut refs = crate::stack_vec::StackVec::<&[u8; CHUNK_LEN], LANES_AT_ONCE>::new();
949 let mut owners = crate::stack_vec::StackVec::<usize, LANES_AT_ONCE>::new();
950 let mut flush = |refs: &mut crate::stack_vec::StackVec<&[u8; CHUNK_LEN], LANES_AT_ONCE>,
951 owners: &mut crate::stack_vec::StackVec<usize, LANES_AT_ONCE>| {
952 let mut lane_out = [0u8; LANES_AT_ONCE * OUT_LEN];
953 let lanes = &mut lane_out[..refs.len() * OUT_LEN];
954 round_platform.hash_many(refs, key, k as u64, IncrementCounter::No, flags, CHUNK_START, CHUNK_END, lanes);
955 for (j, &slot) in owners.iter().enumerate() {
956 cvs[slot].copy_from_slice(&lanes[j * OUT_LEN..(j + 1) * OUT_LEN]);
957 }
958 refs.clear();
959 owners.clear();
960 };
961 for &(i, at) in messages.iter() {
962 if let Some(chunk) = items[i].bytes().get(k * CHUNK_LEN..(k + 1) * CHUNK_LEN) {
963 refs.push(chunk.try_into().unwrap());
964 owners.push(at + k);
965 if refs.is_full() {
966 flush(&mut refs, &mut owners);
967 }
968 }
969 }
970 if !refs.is_empty() {
971 flush(&mut refs, &mut owners);
972 }
973 }
974 if messages.len() == 1 {
975 let (i, at) = messages[0];
976 let chunks = items[i].bytes().len().div_ceil(CHUNK_LEN);
977 out[i] = *root(&cvs[at..at + chunks], key, flags, platform).as_bytes();
978 } else {
979 let parent_flags = flags | crate::PARENT;
987 let parent_rounds = usize::BITS - (max_chunks - 1).leading_zeros() - 1;
988 for round in 0..parent_rounds {
989 let mut jobs = crate::stack_vec::StackVec::<(usize, usize), LANES_AT_ONCE>::new();
990 let mut flushed = false;
991 let mut flush_parents = |jobs: &mut crate::stack_vec::StackVec<(usize, usize), LANES_AT_ONCE>, cvs: &mut [CVBytes]| {
992 flushed = true;
993 let mut lane_out = [0u8; LANES_AT_ONCE * OUT_LEN];
994 {
995 let mut refs = crate::stack_vec::StackVec::<&[u8; crate::BLOCK_LEN], LANES_AT_ONCE>::new();
996 for &(src, _) in jobs.iter() {
997 refs.push(cvs[src..src + 2].as_flattened().try_into().unwrap());
998 }
999 round_platform.hash_many(&refs, key, 0, IncrementCounter::No, parent_flags, 0, 0, &mut lane_out[..refs.len() * OUT_LEN]);
1000 }
1001 for (j, &(_, dst)) in jobs.iter().enumerate() {
1002 cvs[dst].copy_from_slice(&lane_out[j * OUT_LEN..(j + 1) * OUT_LEN]);
1003 }
1004 jobs.clear();
1005 };
1006 for &(i, at) in messages.iter() {
1007 let chunks = items[i].bytes().len().div_ceil(CHUNK_LEN);
1008 let n = ((chunks - 1) >> round) + 1;
1009 if n <= 2 {
1010 continue;
1011 }
1012 for j in 0..(n / 2) {
1013 jobs.push((at + 2 * j, at + j));
1014 if jobs.is_full() {
1015 flush_parents(&mut jobs, cvs);
1016 }
1017 }
1018 }
1019 if !jobs.is_empty() {
1020 flush_parents(&mut jobs, cvs);
1021 }
1022 assert!(flushed, "each scheduled parent round reduces at least one pair");
1023 for &(i, at) in messages.iter() {
1024 let chunks = items[i].bytes().len().div_ceil(CHUNK_LEN);
1025 let n = ((chunks - 1) >> round) + 1;
1026 if n <= 2 {
1027 continue;
1028 }
1029 if (n & 1) == 1 {
1030 let pairs = n / 2;
1031 cvs[at + pairs] = cvs[at + 2 * pairs];
1032 }
1033 }
1034 }
1035 let root_flags = flags | crate::PARENT | crate::ROOT;
1036 for chunk in messages.chunks(LANES_AT_ONCE) {
1037 let mut refs = crate::stack_vec::StackVec::<&[u8; crate::BLOCK_LEN], LANES_AT_ONCE>::new();
1038 for &(_, at) in chunk {
1039 refs.push(cvs[at..at + 2].as_flattened().try_into().unwrap());
1040 }
1041 let mut lane_out = [0u8; LANES_AT_ONCE * OUT_LEN];
1042 round_platform.hash_many(&refs, key, 0, IncrementCounter::No, root_flags, 0, 0, &mut lane_out[..refs.len() * OUT_LEN]);
1043 for (j, &(i, _)) in chunk.iter().enumerate() {
1044 out[i].copy_from_slice(&lane_out[j * OUT_LEN..(j + 1) * OUT_LEN]);
1045 }
1046 }
1047 }
1048 #[cfg(target_arch = "aarch64")]
1049 drop(turn);
1050 messages.clear();
1051 cvs.clear();
1052}
1053
1054pub(crate) const LANES_AT_ONCE: usize = TABLE;
1056
1057struct Shared {
1064 messages: Vec<(usize, usize)>,
1065 cvs: Vec<CVBytes>,
1066}
1067
1068std::thread_local! {
1069 static SHARED: core::cell::RefCell<Shared> = const { core::cell::RefCell::new(Shared { messages: Vec::new(), cvs: Vec::new() }) };
1070}
1071
1072const PREPARED_MESSAGES: usize = 144;
1081const PREPARED_CVS: usize = 288;
1082
1083pub fn prepare_thread() {
1086 let _ = SHARED.try_with(|shared| {
1087 let mut shared = shared.borrow_mut();
1088 shared.messages.clear();
1089 shared.cvs.clear();
1090 shared.messages.reserve(PREPARED_MESSAGES);
1091 shared.cvs.reserve(PREPARED_CVS);
1092 });
1093}
1094
1095fn root(cvs: &[CVBytes], key: &CVWords, flags: u8, platform: Platform) -> Hash {
1098 let split = crate::tree::left_chunks(cvs.len());
1099 let left = subtree(&cvs[..split], key, flags, platform);
1100 let right = subtree(&cvs[split..], key, flags, platform);
1101 crate::hasher::parent_output(&left, &right, key, flags, platform).root_hash()
1102}
1103
1104fn subtree(cvs: &[CVBytes], key: &CVWords, flags: u8, platform: Platform) -> CVBytes {
1106 if cvs.len() == 1 {
1107 return cvs[0];
1108 }
1109 let split = crate::tree::left_chunks(cvs.len());
1110 let left = subtree(&cvs[..split], key, flags, platform);
1111 let right = subtree(&cvs[split..], key, flags, platform);
1112 crate::hasher::parent_output(&left, &right, key, flags, platform).chaining_value()
1113}
1114
1115#[cfg(test)]
1116mod test {
1117 use super::*;
1118
1119 #[test]
1120 #[should_panic(expected = "only plain hashers share a cohort")]
1121 fn a_shared_cohort_refuses_a_keyed_stage() {
1122 crate::initialize();
1123 let key = [7; crate::KEY_LEN];
1124 let mut hashers = [Hasher::new(Mode::Plain, None), Hasher::new(Mode::Keyed(&key), None)];
1125 for h in &mut hashers {
1126 h.stage(&[0; crate::STAGE_LEN]);
1127 }
1128 hash_cohort::<2>(&mut hashers, &[0, 1]);
1129 }
1130
1131 #[test]
1135 fn a_plain_cohort_keeps_iv_beside_keyed_hashers() {
1136 crate::initialize();
1137 let mut input = vec![0u8; 4 * crate::STAGE_LEN];
1138 crate::test::paint_test_input(&mut input);
1139 let key = [0x5a; 32];
1140 let mut hashers = [
1141 Hasher::new(Mode::Plain, None),
1142 Hasher::new(Mode::Keyed(&key), None),
1143 Hasher::new(Mode::Plain, None),
1144 Hasher::new(Mode::DeriveKey("cohort separation"), None),
1145 ];
1146 assert_eq!(hashers[0].domain().key(), crate::IV);
1147 assert_eq!(hashers[2].domain().key(), crate::IV);
1148 for piece in input.chunks(4096) {
1149 update_each(&mut hashers, &[(0, piece), (1, piece), (2, piece), (3, piece)]);
1150 }
1151 assert_eq!(hashers[0].clone().finalize(), crate::test::official::hash(Mode::Plain, &input));
1152 assert_eq!(hashers[1].clone().finalize(), crate::test::official::hash(Mode::Keyed(&key), &input));
1153 assert_eq!(hashers[2].clone().finalize(), crate::test::official::hash(Mode::Plain, &input));
1154 assert_eq!(hashers[3].clone().finalize(), crate::test::official::hash(Mode::DeriveKey("cohort separation"), &input));
1155 let mut plain_cohort = [Hasher::new(Mode::Plain, None), Hasher::new(Mode::Plain, None)];
1158 for h in &mut plain_cohort {
1159 h.stage(&input[..crate::STAGE_LEN]);
1160 }
1161 hash_cohort::<2>(&mut plain_cohort, &[0, 1]);
1162 for h in &plain_cohort {
1163 assert_eq!(h.clone().finalize(), crate::test::official::hash(Mode::Plain, &input[..crate::STAGE_LEN]));
1164 }
1165 }
1166
1167 #[test]
1168 fn prepare_thread_reserves_collection_storage() {
1169 SHARED.with(|s| assert_eq!((s.borrow().messages.capacity(), s.borrow().cvs.capacity()), (0, 0)));
1171 prepare_thread();
1172 SHARED.with(|s| {
1173 let s = s.borrow();
1174 assert!(s.messages.capacity() >= PREPARED_MESSAGES);
1175 assert!(s.cvs.capacity() >= PREPARED_CVS);
1176 assert!(s.messages.is_empty() && s.cvs.is_empty());
1177 });
1178 }
1179
1180 #[cfg(target_arch = "x86_64")]
1181 #[test]
1182 fn finalize_each_groups_only_full_output_lanes() {
1183 crate::initialize();
1184 let expected = crate::test::official::hash(Mode::Plain, b"output selector");
1185 let width = crate::ffi_output::lanes(Platform::detect());
1186 for n in [0, 1, 2, 3, 4, 7, 8, 9, 15, 16, 17, 31, 32, 33] {
1187 let mut hashers: Vec<_> = (0..n)
1188 .map(|_| {
1189 let mut h = Hasher::new(Mode::Plain, None);
1190 h.update(b"output selector");
1191 h
1192 })
1193 .collect();
1194 let which: Vec<_> = (0..n).collect();
1195 let mut out = vec![[0u8; OUT_LEN]; n];
1196 crate::COUNTED.with(|c| c[crate::Counted::OutputGroupTurn as usize].set(0));
1197 finalize_each(&mut hashers, &which, &mut out);
1198 let turns = crate::COUNTED.with(|c| c[crate::Counted::OutputGroupTurn as usize].get());
1199 let expected_turns = u64::from(width != 0 && n >= 4);
1200 assert_eq!(turns, expected_turns, "output group dispatch n={n}");
1201 assert!(out.iter().all(|digest| *digest == expected));
1202 assert!(hashers.iter().all(|h| h.count() == 0));
1203 }
1204 for (n, w, want) in [
1208 (2, 0, 2),
1209 (5, 0, 5),
1210 (4, 8, 4),
1211 (5, 8, 8),
1212 (7, 8, 8),
1213 (8, 8, 8),
1214 (12, 8, 12),
1215 (13, 8, 16),
1216 (15, 8, 16),
1217 (16, 8, 16),
1218 (4, 16, 4),
1219 (5, 16, 8),
1220 (8, 16, 8),
1221 (9, 16, 16),
1222 (15, 16, 16),
1223 (16, 16, 16),
1224 ] {
1225 assert_eq!(crate::ffi_output::prefix_padded_count(n, w), want, "prefix_padded_count({n}, {w})");
1226 }
1227 let lens = [0usize, 1, 24, 48, 63, 64, 65, 96, 128, 192, 255, 384, 512, 768, 1000, 1024];
1228 for plat in crate::test::every_platform() {
1229 let pw = crate::ffi_output::lanes(plat);
1230 for n in [2usize, 4, 5, 7, 8, 9, 12, 13, 15, 16] {
1232 let bufs: Vec<Vec<u8>> = (0..n).map(|i| vec![(i as u8).wrapping_mul(17); 256]).collect();
1233 let slices: Vec<&[u8]> = bufs.iter().map(Vec::as_slice).collect();
1234 let mut out = vec![[0u8; OUT_LEN]; n];
1235 crate::pair::BLOCKS_CALLS.with(|c| c.borrow_mut().clear());
1236 hash_by_blocks(&slices, crate::IV, 0, &mut out, plat);
1237 let calls = crate::pair::BLOCKS_CALLS.with(|c| c.borrow().clone());
1238 assert_eq!(calls, vec![(3, crate::ffi_output::prefix_padded_count(n, pw))], "prefix padding {plat:?} n={n}");
1239 for (i, buf) in bufs.iter().enumerate() {
1240 assert_eq!(out[i], *blake3::hash(buf).as_bytes(), "prefix {plat:?} n={n} item {i}");
1241 }
1242 }
1243 for count in [2usize, 3, 4, 7, 8, 9, 12, 13, 15, 16, 19, 24, 33] {
1244 let bufs: Vec<Vec<u8>> = (0..count)
1245 .map(|i| {
1246 let len = lens[i % lens.len()];
1247 (0..len).map(|j| ((i * 37 + j * 13 + len) & 0xff) as u8).collect()
1248 })
1249 .collect();
1250 let slices: Vec<&[u8]> = bufs.iter().map(Vec::as_slice).collect();
1251 let mut out = vec![[0u8; OUT_LEN]; count];
1252 crate::ffi_output::OUTPUT_CALLS.with(|c| c.borrow_mut().clear());
1253 hash_by_blocks(&slices, crate::IV, 0, &mut out, plat);
1254 let calls = crate::ffi_output::OUTPUT_CALLS.with(|c| c.borrow().clone());
1255 let mut want_calls = Vec::new();
1256 if pw > 0 {
1257 let mut rem = count;
1258 while rem >= 4 {
1259 let c = rem.min(pw);
1260 want_calls.push(if c <= 8 { 8 } else { 16 });
1261 rem -= c;
1262 }
1263 }
1264 assert_eq!(calls, want_calls, "hash_by_blocks output calls {plat:?} count={count}");
1265 for (i, buf) in bufs.iter().enumerate() {
1266 assert_eq!(out[i], *blake3::hash(buf).as_bytes(), "{plat:?} count={count} item {i}");
1267 }
1268 }
1269 let bufs: Vec<Vec<u8>> = (0..8).map(|i| vec![i as u8; 200]).collect();
1272 let slices: Vec<&[u8]> = bufs.iter().map(Vec::as_slice).collect();
1273 let mut out = [[0u8; OUT_LEN]; 8];
1274 crate::ffi_output::OUTPUT_CALLS.with(|c| c.borrow_mut().clear());
1275 by_blocks_at_once(&slices, crate::IV, 3, 0, CHUNK_END, &mut out, plat);
1276 assert!(crate::ffi_output::OUTPUT_CALLS.with(|c| c.borrow().is_empty()), "counter != 0 skips output16/output8");
1277 }
1278
1279 for p in crate::test::every_platform() {
1282 let w = crate::ffi_output::lanes(p);
1283 for n in [2usize, 3, 4, 7, 8, 9, 15, 16, 19, 20, 24, 25, 32] {
1284 let mut hashers: Vec<_> = (0..n)
1285 .map(|i| {
1286 let mut h = Hasher::new(if i % 3 == 1 { Mode::Keyed(&[0x55; 32]) } else { Mode::Plain }, None);
1287 h.update(&vec![i as u8; 32 + (i % 32)]);
1288 h
1289 })
1290 .collect();
1291 let which: Vec<usize> = (0..n).collect();
1292 let slots: Vec<u8> = (0..n).map(|i| i as u8).collect();
1293 let mut out = vec![[0u8; OUT_LEN]; n];
1294 crate::ffi_output::OUTPUT_CALLS.with(|c| c.borrow_mut().clear());
1295 let done = crate::ffi_output::finalize_output_slots(&hashers, &which, &slots, &mut out, p);
1296 for &k in &slots[done..] {
1297 let ku = usize::from(k);
1298 out[ku] = *hashers[ku].take_root_hash().as_bytes();
1299 }
1300 let calls = crate::ffi_output::OUTPUT_CALLS.with(|c| c.borrow().clone());
1301 let mut want = Vec::new();
1302 let mut want_done = 0usize;
1303 if w > 0 {
1304 let mut rem = n;
1305 if w == 16 {
1306 while rem >= 16 {
1307 want.push(16);
1308 rem -= 16;
1309 want_done += 16;
1310 }
1311 if rem >= 9 {
1312 want.push(16);
1313 want_done += rem;
1314 rem = 0;
1315 }
1316 }
1317 while rem >= 8 {
1318 want.push(8);
1319 rem -= 8;
1320 want_done += 8;
1321 }
1322 if rem >= 4 {
1323 want.push(8);
1324 want_done += rem;
1325 }
1326 }
1327 assert_eq!((done, calls), (want_done, want), "finalize_output_slots w={w} n={n}");
1328 for i in 0..n {
1329 let mode = if i % 3 == 1 { Mode::Keyed(&[0x55; 32]) } else { Mode::Plain };
1330 assert_eq!(out[i], crate::test::official::hash(mode, &vec![i as u8; 32 + (i % 32)]), "w={w} n={n} item {i}");
1331 }
1332 }
1333 }
1334 }
1335
1336 #[test]
1337 #[should_panic(expected = "each finalized index is distinct")]
1338 fn finalize_each_rejects_repeated_indices() {
1339 crate::initialize();
1340 let mut hashers = [Hasher::new(Mode::Plain, None)];
1341 finalize_each(&mut hashers, &[0, 0], &mut [[0; OUT_LEN]; 2]);
1342 }
1343
1344 #[test]
1347 fn finalize_each_leaves_no_hasher_marked() {
1348 crate::initialize();
1349 for n in [1, 2, 3, 15, 16, 17, 33] {
1350 for len in [0, 1, 64, 1024, 1025, 5000, 40_000] {
1351 let mut hashers: Vec<_> = (0..n).map(|k| Hasher::new(if k % 3 == 2 { Mode::Keyed(&[7; 32]) } else { Mode::Plain }, None)).collect();
1352 let which: Vec<_> = (0..n).rev().collect();
1353 let mut out = vec![[0u8; OUT_LEN]; n];
1354 for round in 0..2 {
1355 let message = vec![round as u8; len];
1356 let pieces: Vec<(usize, &[u8])> = (0..n).map(|i| (i, &message[..])).collect();
1357 update_each(&mut hashers, &pieces);
1358 finalize_each(&mut hashers, &which, &mut out);
1359 assert!(
1360 hashers.iter_mut().all(|h| {
1361 let was = h.mark_finishing();
1362 h.clear_finishing();
1363 !was
1364 }),
1365 "n={n} len={len}"
1366 );
1367 assert_eq!(out[n - 1], *crate::convenience::hash(&message).as_bytes(), "n={n} len={len}");
1368 }
1369 }
1370 }
1371 }
1372
1373 #[test]
1374 #[should_panic(expected = "each finalized index is distinct")]
1375 fn finalize_each_rejects_repeats_across_groups() {
1376 crate::initialize();
1377 let mut hashers: Vec<_> = (0..16).map(|_| Hasher::new(Mode::Plain, None)).collect();
1378 let which: Vec<_> = (0..16).chain(0..16).collect();
1379 finalize_each(&mut hashers, &which, &mut [[0; OUT_LEN]; 32]);
1380 }
1381
1382 #[test]
1383 #[should_panic(expected = "finalize_each names hasher 9 of 2")]
1384 fn finalize_each_refuses_an_index_that_names_no_hasher() {
1385 crate::initialize();
1386 let mut hashers = [Hasher::new(Mode::Plain, None), Hasher::new(Mode::Plain, None)];
1387 finalize_each(&mut hashers, &[0, 9], &mut [[0; OUT_LEN]; 2]);
1388 }
1389
1390 #[test]
1393 fn a_refused_finalize_each_leaves_no_hasher_marked() {
1394 crate::initialize();
1395 for refused in [&[0usize, 1, 0][..], &[0, 1, 9]] {
1396 let mut hashers = [Hasher::new(Mode::Plain, None), Hasher::new(Mode::Plain, None)];
1397 update_each(&mut hashers, &[(0, b"abc"), (1, b"xyz")]);
1398 let call = std::panic::catch_unwind(core::panic::AssertUnwindSafe(|| finalize_each(&mut hashers, refused, &mut [[0; OUT_LEN]; 3])));
1399 assert!(call.is_err(), "{refused:?} was accepted");
1400 assert!(
1401 hashers.iter_mut().all(|h| {
1402 let was = h.mark_finishing();
1403 h.clear_finishing();
1404 !was
1405 }),
1406 "{refused:?} left a mark"
1407 );
1408 let mut out = [[0; OUT_LEN]; 2];
1409 finalize_each(&mut hashers, &[1, 0], &mut out);
1410 assert_eq!(out, [*crate::convenience::hash(b"xyz").as_bytes(), *crate::convenience::hash(b"abc").as_bytes()]);
1411 }
1412 }
1413
1414 #[test]
1417 fn a_turn_that_unwinds_leaves_no_stage_held() {
1418 crate::initialize();
1419 let bytes: Vec<u8> = (0..2 * crate::STAGE_LEN).map(|i| (i % 251) as u8).collect();
1420 let half = crate::STAGE_LEN / 2;
1421 let then = |hashers: &mut [Hasher; 2], after: &str| {
1422 assert!(hashers[0].held_group().is_none(), "{after}: hasher 0 is left holding a full stage");
1423 assert_eq!(hashers[0].count(), crate::STAGE_LEN as u64, "{after}");
1426 hashers[0].update(b"y");
1427 hashers[1].reset();
1428 update_each(hashers, &[(0, b"z"), (1, b"abc")]);
1429 let mut fed = bytes[..crate::STAGE_LEN].to_vec();
1430 fed.extend_from_slice(b"yz");
1431 assert_eq!(hashers[0].finalize(), crate::convenience::hash(&fed), "{after}");
1432 assert_eq!(hashers[1].finalize(), crate::convenience::hash(b"abc"), "{after}");
1433 };
1434
1435 let mut hashers = [Hasher::new(Mode::Plain, None), Hasher::new(Mode::Plain, None)];
1437 let turn = [(0, &bytes[..half]), (0, &bytes[half..2 * half + 1]), (7, &bytes[..1])];
1438 let call = std::panic::catch_unwind(core::panic::AssertUnwindSafe(|| update_each(&mut hashers, &turn)));
1439 assert!(call.is_err(), "an index that names no hasher was accepted");
1440 then(&mut hashers, "an index out of range");
1441 }
1442
1443 fn block_groups_expected(platform: Platform) -> bool {
1446 #[cfg(target_arch = "x86_64")]
1447 return !matches!(platform, Platform::SSE41);
1448 #[cfg(not(target_arch = "x86_64"))]
1449 {
1450 let _ = platform;
1451 true
1452 }
1453 }
1454
1455 #[test]
1461 fn test_hash_each_small_items_by_blocks() {
1462 let mut golden = crate::test::Golden::new("hash_each_small_items");
1463 let mut x = 0x9e37_79b9u64;
1464 for count in [2usize, 7, 63, 64, 65, 200] {
1465 let mut lens: Vec<usize> = (0..count)
1466 .map(|_| {
1467 x ^= x << 13;
1468 x ^= x >> 7;
1469 x ^= x << 17;
1470 (x % (CHUNK_LEN as u64 + 1)) as usize
1471 })
1472 .collect();
1473 lens[count / 2] = 5 * CHUNK_LEN + 77;
1474 let data: Vec<Vec<u8>> = lens.iter().enumerate().map(|(m, &n)| (0..n).map(|i| ((m * 37 + i) % 249) as u8).collect()).collect();
1475 let items: Vec<&[u8]> = data.iter().map(|d| &d[..]).collect();
1476 let mut out = vec![[0u8; OUT_LEN]; count];
1477 for platform in crate::test::every_platform() {
1478 crate::COUNTED.with(|c| c[crate::Counted::ByBlocksCall as usize].set(0));
1479 hash_each_on(crate::IV, 0, &items, &mut out, platform, |item| crate::hash_serial(item, crate::IV, 0));
1480 let calls = crate::COUNTED.with(|c| c[crate::Counted::ByBlocksCall as usize].get());
1481 let small: Vec<usize> = lens.iter().copied().filter(|&n| n <= CHUNK_LEN).collect();
1484 #[cfg(target_arch = "aarch64")]
1485 let last_lanes = crate::neon_hybrid::sha3_detected();
1486 #[cfg(not(target_arch = "aarch64"))]
1487 let last_lanes = false;
1488 let calls_expected: u64 = if block_groups_expected(platform) && small.len() >= 2 {
1489 small
1490 .chunks(BY_BLOCKS_AT_ONCE)
1491 .map(|part| {
1492 let mut buckets = [0u64; 16];
1493 for &len in part {
1494 buckets[len.saturating_sub(1) / crate::BLOCK_LEN] += 1;
1495 }
1496 buckets.into_iter().enumerate().filter(|&(k, _)| last_lanes || k > 0).map(|(_, n)| n.div_ceil(16)).sum::<u64>()
1497 })
1498 .sum()
1499 } else {
1500 0
1501 };
1502 assert_eq!(calls, calls_expected, "{count} items on {platform:?}: exact block-group calls");
1503 let expected: Vec<[u8; OUT_LEN]> = items.iter().map(|i| *crate::convenience::hash(i).as_bytes()).collect();
1504 assert_eq!(out, expected, "{count} items");
1505 }
1506 golden.add(out.as_flattened(), || items.iter().flat_map(|i| crate::test::official::hash(Mode::Plain, i)).collect());
1507 }
1508 golden.check(0x8fa73f9dac40c559);
1509 }
1510
1511 #[test]
1518 fn test_hash_each_on_counts_its_alone_messages_and_rounds() {
1519 let input = vec![5u8; (ALONE_CHUNKS + 1) * CHUNK_LEN];
1520 let lens = [
1521 0,
1522 1,
1523 CHUNK_LEN,
1524 CHUNK_LEN + 1,
1525 2 * CHUNK_LEN,
1526 (ALONE_CHUNKS - 1) * CHUNK_LEN,
1527 (ALONE_CHUNKS - 1) * CHUNK_LEN + 1,
1528 ALONE_CHUNKS * CHUNK_LEN,
1529 ALONE_CHUNKS * CHUNK_LEN + 1,
1530 ];
1531 let items: Vec<&[u8]> = lens.iter().map(|&n| &input[..n]).collect();
1532 let alone = core::cell::RefCell::new(Vec::new());
1533 let mut out = vec![[0u8; OUT_LEN]; items.len()];
1534 crate::COUNTED.with(|c| c[crate::Counted::EachRound as usize].set(0));
1535 hash_each_on(crate::IV, 0, &items, &mut out, Platform::detect(), |item| {
1536 alone.borrow_mut().push(item.len());
1537 crate::hash_serial(item, crate::IV, 0)
1538 });
1539 let rounds = crate::COUNTED.with(|c| c[crate::Counted::EachRound as usize].get());
1540 let long = [(ALONE_CHUNKS - 1) * CHUNK_LEN + 1, ALONE_CHUNKS * CHUNK_LEN, ALONE_CHUNKS * CHUNK_LEN + 1];
1541 let expected: Vec<usize> = if block_groups_expected(Platform::detect()) { long.to_vec() } else { [0, 1, CHUNK_LEN].into_iter().chain(long).collect() };
1542 assert_eq!(alone.into_inner(), expected);
1543 assert_eq!(rounds, (ALONE_CHUNKS - 1) as u64);
1545 for (item, out) in items.iter().zip(&out) {
1546 assert_eq!(out, crate::convenience::hash(item).as_bytes(), "{} bytes", item.len());
1547 }
1548 }
1549
1550 #[test]
1557 fn test_hash_each_on_takes_a_round_of_many_lanes_in_several_calls() {
1558 crate::initialize();
1559 let mut input = vec![0u8; (ALONE_CHUNKS + 1) * CHUNK_LEN];
1560 crate::test::paint_test_input(&mut input);
1561 let shared_lens = [2 * CHUNK_LEN, 3 * CHUNK_LEN + 5, CHUNK_LEN + 1, 7 * CHUNK_LEN, (ALONE_CHUNKS - 1) * CHUNK_LEN - 3];
1562 let mut lens = Vec::new();
1563 for j in 0..2 * LANES_AT_ONCE + 10 {
1564 lens.push(shared_lens[j % shared_lens.len()]);
1565 if j % 7 == 0 {
1566 lens.extend([33, ALONE_CHUNKS * CHUNK_LEN + 9]);
1567 }
1568 }
1569 let items: Vec<&[u8]> = lens.iter().map(|&n| &input[..n]).collect();
1570 for pass in 0..2 {
1571 let mut out = vec![[0xAAu8; OUT_LEN]; items.len()];
1572 crate::COUNTED.with(|c| c[crate::Counted::EachRound as usize].set(0));
1573 hash_each_on(crate::IV, 0, &items, &mut out, Platform::detect(), |item| crate::hash_serial(item, crate::IV, 0));
1574 let rounds = crate::COUNTED.with(|c| c[crate::Counted::EachRound as usize].get());
1575 assert_eq!(rounds, (ALONE_CHUNKS - 2) as u64, "the longest holds fourteen whole chunks (pass {pass})");
1576 for (item, out) in items.iter().zip(&out) {
1577 assert_eq!(out, crate::convenience::hash(item).as_bytes(), "{} bytes (pass {pass})", item.len());
1578 }
1579 }
1580 }
1581
1582 #[test]
1587 fn test_update_each_holds_groups_together() {
1588 for platform in crate::test::every_platform() {
1589 holds_groups_together(platform);
1590 }
1591 }
1592
1593 fn holds_groups_together(platform: crate::platform::Platform) {
1594 let mut input = vec![0u8; 3 * crate::STAGE_LEN];
1595 crate::test::paint_test_input(&mut input);
1596 let keys = [[1u8; 32], [2u8; 32]];
1597 let on = |mut h: Hasher| {
1598 h.set_platform_for_test(platform);
1599 h
1600 };
1601 let mut hashers: Vec<Hasher> = (0..6).map(|i| on(Hasher::new(crate::Mode::Keyed(&keys[i % 2]), None))).collect();
1602 let start = |i: usize| i * 1000;
1606 let group = crate::STAGE_LEN;
1607 for (i, h) in hashers.iter_mut().enumerate() {
1608 h.update(&input[start(i)..start(i) + group]);
1609 }
1610 let turn: Vec<(usize, &[u8])> = (0..6)
1611 .flat_map(|i| [(i, &input[start(i) + group..start(i) + group + 100]), (i, &input[start(i) + group + 100..start(i) + 2 * group + 7])])
1612 .collect();
1613 crate::throughput::update_each(&mut hashers, &turn);
1614 for (i, h) in hashers.iter().enumerate() {
1615 let message = &input[start(i)..start(i) + 2 * crate::STAGE_LEN + 7];
1616 assert_eq!(h.clone().finalize(), crate::convenience::hash_with(crate::Mode::Keyed(&keys[i % 2]), message), "hasher {i}, {platform:?}");
1617 }
1618 let mut fresh: Vec<Hasher> = (0..6).map(|i| on(Hasher::new(crate::Mode::Keyed(&keys[i % 2]), None))).collect();
1622 let turn: Vec<(usize, &[u8])> =
1623 (0..6).flat_map(|i| [(i, &input[start(i)..start(i) + 1100]), (i, &input[start(i) + 1100..start(i) + group + 7])]).collect();
1624 crate::throughput::update_each(&mut fresh, &turn);
1625 for (i, h) in fresh.iter().enumerate() {
1626 assert_eq!(
1627 h.clone().finalize(),
1628 crate::convenience::hash_with(crate::Mode::Keyed(&keys[i % 2]), &input[start(i)..start(i) + group + 7]),
1629 "fresh hasher {i}, {platform:?}"
1630 );
1631 }
1632 }
1633
1634 #[test]
1639 fn a_turn_stages_a_first_chunk_on_aarch64_and_an_update_everywhere() {
1640 crate::initialize();
1641 let bytes = [7u8; 300];
1642 let key = [0x42u8; 32];
1643 let mut hashers = vec![Hasher::new(Mode::Plain, None), Hasher::new(Mode::Plain, None), Hasher::new(Mode::Keyed(&key), None)];
1644 update_each(&mut hashers, &[(0, &bytes[..100]), (0, &bytes[100..]), (2, &bytes[..100]), (2, &bytes[100..])]);
1645 hashers[1].update(&bytes);
1646 assert_eq!((hashers[0].staged_len(), hashers[0].count() - hashers[0].staged_len() as u64), (300, 0), "a plain turn's first chunk stays staged");
1647 assert_eq!((hashers[1].staged_len(), hashers[1].count() - hashers[1].staged_len() as u64), (300, 0), "an update's first chunk waits in the stage");
1648 let keyed_in_turn = if cfg!(target_arch = "aarch64") { (300, 0) } else { (0, 300) };
1649 assert_eq!((hashers[2].staged_len(), hashers[2].count() - hashers[2].staged_len() as u64), keyed_in_turn, "a keyed turn's first chunk");
1650 assert_eq!(hashers[0].finalize(), crate::test::official::hash(Mode::Plain, &bytes));
1651 assert_eq!(hashers[1].finalize(), crate::test::official::hash(Mode::Plain, &bytes));
1652 assert_eq!(hashers[2].finalize(), crate::test::official::hash(Mode::Keyed(&key), &bytes));
1653 }
1654
1655 #[cfg(target_arch = "x86_64")]
1661 #[test]
1662 fn x86_finalize_each_batches_staged_plain_chunks_and_short_blocks() {
1663 crate::initialize();
1664 let run_case = |lens: &[usize]| -> (u64, u64, bool) {
1665 let data: Vec<Vec<u8>> = lens.iter().enumerate().map(|(i, &n)| (0..n).map(|j| ((i * 41 + j * 13) & 0xff) as u8).collect()).collect();
1666 let mut hashers: Vec<_> = (0..lens.len()).map(|_| Hasher::new(Mode::Plain, None)).collect();
1667 for offset in (0..1024).step_by(256) {
1668 let pieces: Vec<_> =
1669 data.iter().enumerate().filter(|(_, d)| offset < d.len()).map(|(i, d)| (i, &d[offset..(offset + 256).min(d.len())])).collect();
1670 if !pieces.is_empty() {
1671 update_each(&mut hashers, &pieces);
1672 }
1673 }
1674 let which: Vec<usize> = (0..lens.len()).collect();
1675 let mut out = vec![[0u8; OUT_LEN]; lens.len()];
1676 crate::COUNTED.with(|c| {
1677 c[crate::Counted::HashManyCall as usize].set(0);
1678 c[crate::Counted::ByBlocksCall as usize].set(0);
1679 });
1680 crate::ROUNDED_WIDTH.with(|w| w.set(0));
1681 finalize_each(&mut hashers, &which, &mut out);
1682 for (d, got) in data.iter().zip(&out) {
1683 assert_eq!(*got, crate::test::official::hash(Mode::Plain, d), "len={}", d.len());
1684 }
1685 assert!(hashers.iter().all(|h| h.count() == 0));
1686 let rounded = crate::ROUNDED_WIDTH.with(|w| w.get()) != 0;
1687 (
1688 crate::COUNTED.with(|c| c[crate::Counted::HashManyCall as usize].get()),
1689 crate::COUNTED.with(|c| c[crate::Counted::ByBlocksCall as usize].get()),
1690 rounded,
1691 )
1692 };
1693 let block_lanes = matches!(Platform::detect(), Platform::AVX2 | Platform::AVX512);
1694 assert_eq!(run_case(&[1024]), (0, 0, false), "1 full chunk takes scalar root");
1695 assert_eq!(run_case(&[1024, 1024]), (1, 0, false), "2 full chunks call hash_many_rounded without padding");
1696 assert_eq!(run_case(&[1024; 3]), (1, 0, true), "3 full chunks round up via hash_many_rounded");
1697 assert_eq!(run_case(&[1024; 35]), (2, 0, true), "35 full chunks split into 32 + 3");
1698 assert_eq!(run_case(&[512]), (0, 0, false), "1 short plain message skips hash_by_blocks");
1699 assert_eq!(run_case(&[64, 128]), (0, 0, false), "64 B stays in rest so single 128 B skips hash_by_blocks");
1700 assert_eq!(run_case(&[64, 64, 64, 65]), (0, 0, false), "64 B stays in rest so lone 65 B skips hash_by_blocks");
1701 assert_eq!(run_case(&[65, 65]), (0, 0, false), "pair of 1-prefix-block 65 B messages stays scalar");
1702 assert_eq!(run_case(&[128, 128]), (0, 0, false), "pair of 128 B messages stays scalar");
1703 assert_eq!(run_case(&[65; 4]), (0, u64::from(block_lanes), false), "4 x 65 B batches via hash_by_blocks");
1704 assert_eq!(run_case(&[129, 129]), (0, u64::from(block_lanes), false), "pair of 129 B (2 prefix blocks) batches");
1705 assert_eq!(run_case(&[512, 512]), (0, u64::from(block_lanes), false), "pair of 512 B batches via hash_by_blocks");
1706 assert_eq!(run_case(&[1023, 1023]), (0, u64::from(block_lanes), false), "high endpoint 1023 B batches via hash_by_blocks");
1707 assert_eq!(run_case(&[65, 129, 512, 1023]), (0, if block_lanes { 4 } else { 0 }, false), "4 distinct prefix buckets batch each bucket");
1708 assert_eq!(run_case(&[512; 65]), (0, if block_lanes { 5 } else { 0 }, false), "65 short plain messages split across BY_BLOCKS_AT_ONCE");
1709 assert_eq!(run_case(&[1024; 131]), (5, 0, true), "131 full chunks cross the 128-index window and round window 2");
1711 assert_eq!(run_case(&[1024; 129]), (4, 0, false), "129 full chunks finish the 129th scalar in window 2");
1713 }
1714
1715 #[test]
1720 fn messages_fed_by_turns_finish_together_and_reset() {
1721 crate::initialize();
1722 let key = [37; 32];
1723 for n in [2, 16, 17, 64, 128, 130] {
1724 for len in [0, 1, 63, 64, 65, 255, 1023, 1024, 1025, 2048, 16385] {
1725 for width in [17, 256] {
1726 for mode in [Mode::Plain, Mode::Keyed(&key), Mode::DeriveKey("grouped first chunk")] {
1727 let data: Vec<Vec<u8>> = (0..n).map(|i| (0..len).map(|j| (i * 37 + j * 13) as u8).collect()).collect();
1728 let mut hashers: Vec<_> = (0..n).map(|_| Hasher::new(mode, None)).collect();
1729 for start in (0..len).step_by(width) {
1730 let pieces: Vec<_> = data.iter().enumerate().map(|(i, d)| (i, &d[start..(start + width).min(len)])).collect();
1731 update_each(&mut hashers, &pieces);
1732 }
1733 assert!(hashers.iter().all(|h| h.count() == len as u64));
1734 let which: Vec<_> = (0..n).rev().collect();
1735 let mut out = vec![[0; 32]; n];
1736 finalize_each(&mut hashers, &which, &mut out);
1737 for (&i, got) in which.iter().zip(&out) {
1738 assert_eq!(*got, crate::test::official::hash(mode, &data[i]), "n={n}, len={len}, width={width}");
1739 }
1740 assert!(hashers.iter().all(|h| h.count() == 0));
1741 finalize_each(&mut hashers, &which, &mut out);
1742 assert!(out.iter().all(|got| *got == crate::test::official::hash(mode, &[])));
1743 }
1744 }
1745 }
1746 }
1747 }
1748
1749 #[cfg(target_arch = "aarch64")]
1756 #[test]
1757 fn a_finish_takes_the_staged_first_chunks_from_among_the_others() {
1758 crate::initialize();
1759 let key = [91u8; 32];
1760 let lens = [511usize, 1, 1024, 64, 65, 0, 63];
1764 for n in [3usize, 17, 128, 200] {
1765 let data: Vec<Vec<u8>> =
1766 (0..n).map(|i| (0..if i % 5 == 3 { 3000 } else { lens[i % lens.len()] }).map(|j| (i * 37 + j * 13) as u8).collect()).collect();
1767 let mode = |i: usize| if i % 5 == 1 { Mode::Keyed(&key) } else { Mode::Plain };
1768 let mut hashers: Vec<_> = (0..n).map(|i| Hasher::new(mode(i), None)).collect();
1769 for (i, d) in data.iter().enumerate() {
1770 if i % 5 == 4 {
1771 hashers[i].update(d);
1772 }
1773 }
1774 for from in (0..3000).step_by(17) {
1775 let pieces: Vec<_> =
1776 data.iter().enumerate().filter(|(i, _)| i % 5 != 4).map(|(i, d)| (i, &d[from.min(d.len())..(from + 17).min(d.len())])).collect();
1777 update_each(&mut hashers, &pieces);
1778 }
1779 let which: Vec<_> = (0..n).rev().collect();
1780 let mut out = vec![[0; 32]; n];
1781 crate::COUNTED.with(|c| c[crate::Counted::ByBlocksCall as usize].set(0));
1782 finalize_each(&mut hashers, &which, &mut out);
1783 for (&i, got) in which.iter().zip(&out) {
1784 assert_eq!(*got, crate::test::official::hash(mode(i), &data[i]), "n={n}, message {i}");
1785 }
1786 assert!(crate::COUNTED.with(|c| c[crate::Counted::ByBlocksCall as usize].get()) > 0, "the staged first chunks went by their blocks");
1787 assert!(hashers.iter().all(|h| h.count() == 0));
1788 }
1789 let mut hashers = vec![Hasher::new(Mode::Plain, None), Hasher::new(Mode::Plain, None)];
1791 let long = [5u8; 3000];
1792 update_each(&mut hashers, &[(0, &long[..700]), (1, &long)]);
1793 let mut out = [[0; 32]; 2];
1794 crate::COUNTED.with(|c| c[crate::Counted::ByBlocksCall as usize].set(0));
1795 finalize_each(&mut hashers, &[0, 1], &mut out);
1796 assert_eq!(out, [crate::test::official::hash(Mode::Plain, &long[..700]), crate::test::official::hash(Mode::Plain, &long)]);
1797 assert_eq!(crate::COUNTED.with(|c| c[crate::Counted::ByBlocksCall as usize].get()), 0, "one message of up to a chunk finishes alone");
1798 }
1799
1800 #[cfg(target_arch = "aarch64")]
1806 #[test]
1807 fn a_sized_table_of_whole_block_messages_takes_the_sme2_message_kernel() {
1808 if !crate::platform::sme2_detected() {
1809 return;
1810 }
1811 crate::initialize();
1812 let secret = [0x9du8; crate::KEY_LEN];
1813 let entry = crate::sme2::ffi::blake3_servil_sme2_hash16_messages_512 as *const () as usize;
1814 let ran = || crate::RAN_ENTRIES.with(|r| r.borrow().contains(&entry));
1815 for mode in [Mode::Plain, Mode::Keyed(&secret), Mode::DeriveKey("a table of whole blocks")] {
1816 let mut room = core::mem::MaybeUninit::uninit();
1817 let (key, flags) = mode.key(&mut room);
1818 for len in (64usize..=1024).step_by(64) {
1820 for count in [1usize, 15, 16, 17, 31, 32, 63, 64, 127, 128] {
1821 let data: Vec<Vec<u8>> = (0..count).map(|i| (0..len).map(|j| (i * 37 + j * 11) as u8).collect()).collect();
1822 let items: Vec<&[u8]> = data.iter().map(|d| &d[..]).collect();
1823 let expected: Vec<_> = items.iter().map(|i| crate::test::official::hash(mode, i)).collect();
1824 let mut out = vec![[0u8; OUT_LEN]; count];
1825 crate::RAN_ENTRIES.with(|r| r.borrow_mut().clear());
1826 hash_by_blocks(&items, key, flags, &mut out, Platform::SME2);
1827 assert_eq!(out, expected, "{count} x {len}");
1828 assert_eq!(ran(), count * len >= crate::SME2_SIZED_LEN, "the message kernel at {count} x {len}");
1829 }
1830 }
1831 let mut data: Vec<Vec<u8>> = (0..128).map(|i| (0..1024).map(|j| (i * 37 + j * 11) as u8).collect()).collect();
1833 data[1].pop();
1834 let items: Vec<&[u8]> = data.iter().map(|d| &d[..]).collect();
1835 let expected: Vec<_> = items.iter().map(|i| crate::test::official::hash(mode, i)).collect();
1836 let mut out = vec![[0u8; OUT_LEN]; 128];
1837 crate::RAN_ENTRIES.with(|r| r.borrow_mut().clear());
1838 hash_by_blocks(&items, key, flags, &mut out, Platform::SME2);
1839 assert_eq!(out, expected);
1840 assert!(!ran(), "the message kernel takes messages of one length");
1841 }
1842 }
1843
1844 #[test]
1852 fn outlasting_pieces_wait_for_a_full_table() {
1853 crate::initialize();
1854 const N: usize = 256;
1855 let mut input = vec![0u8; 1448 + crate::STAGE_LEN];
1856 crate::test::paint_test_input(&mut input);
1857 let mut hashers: Vec<Hasher> = (0..N).map(|_| Hasher::new(Mode::Plain, None)).collect();
1858 let first: Vec<(usize, &[u8])> = (0..N).map(|i| (i, &input[..1448])).collect();
1859 update_each(&mut hashers, &first);
1860 let second: Vec<(usize, &[u8])> = (0..N).map(|i| (i, &input[1448..])).collect();
1861 crate::COUNTED.with(|c| c[crate::Counted::HeldPass as usize].set(0));
1862 update_each(&mut hashers, &second);
1863 let passes = crate::COUNTED.with(|c| c[crate::Counted::HeldPass as usize].get());
1864 assert_eq!(passes, (N / TABLE) as u64, "every stage hashed in full passes of the table");
1865 for h in &hashers {
1866 assert_eq!(h.clone().finalize(), crate::test::official::hash(Mode::Plain, &input));
1867 }
1868 let mut pair = vec![Hasher::new(Mode::Plain, None), Hasher::new(Mode::Plain, None)];
1871 let (a, b) = input.split_at(crate::STAGE_LEN + 100);
1872 update_each(&mut pair, &[(0, a), (1, &input[..7]), (0, b), (1, &input[7..])]);
1873 assert_eq!(pair[0].clone().finalize(), crate::test::official::hash(Mode::Plain, &input));
1874 assert_eq!(pair[1].clone().finalize(), crate::test::official::hash(Mode::Plain, &input));
1875 }
1876
1877 #[test]
1880 fn held_groups_pass_by_mode_not_key() {
1881 crate::initialize();
1882 let mut input = vec![0u8; crate::STAGE_LEN];
1883 crate::test::paint_test_input(&mut input);
1884 let (a, b, c) = ([1u8; 32], [2u8; 32], [3u8; 32]);
1885 let passes = |modes: &[Mode]| {
1886 let mut hashers: Vec<Hasher> = modes.iter().map(|&m| Hasher::new(m, None)).collect();
1887 let pieces: Vec<(usize, &[u8])> = input.chunks(4096).flat_map(|piece| (0..modes.len()).map(move |i| (i, piece))).collect();
1890 crate::COUNTED.with(|c| c[crate::Counted::HeldPass as usize].set(0));
1891 update_each(&mut hashers, &pieces);
1892 let passes = crate::COUNTED.with(|c| c[crate::Counted::HeldPass as usize].get());
1893 for (h, &m) in hashers.iter().zip(modes) {
1894 assert_eq!(h.clone().finalize(), crate::test::official::hash(m, &input));
1895 }
1896 passes
1897 };
1898 let independent = crate::ffi_output::lanes(Platform::detect()) != 0;
1899 assert_eq!(passes(&[Mode::Plain; 3]), 1, "plain hashers hash together");
1900 assert_eq!(passes(&[Mode::Plain, Mode::Keyed(&a), Mode::Plain]), if independent { 1 } else { 2 }, "public mixed-mode route");
1901 let same = passes(&[Mode::Keyed(&a); 3]);
1902 assert_eq!(same, passes(&[Mode::Keyed(&a), Mode::Keyed(&b), Mode::Keyed(&c)]), "equal keys take the passes distinct keys take");
1903 assert_eq!(same, if independent { 1 } else { 3 });
1904 assert_eq!(passes(&[Mode::Keyed(&a), Mode::Keyed(&b)]), 2, "a pair of keyed hashers, on either route");
1906 assert_eq!(passes(&[Mode::Keyed(&a); 2]), 2, "equal keys take the same two passes");
1907 let derived = passes(&[Mode::DeriveKey("shared context"); 3]);
1908 assert_eq!(derived, passes(&[Mode::DeriveKey("context a"), Mode::DeriveKey("context b"), Mode::DeriveKey("context c")]));
1909 assert_eq!(derived, if independent { 1 } else { 3 }, "derived-key equality stays private");
1910 let bounded = 600usize.div_ceil(TABLE) as u64;
1912 assert_eq!(passes(&[Mode::Keyed(&a); 600]), if independent { bounded } else { 600 }, "600 keyed hashers, bounded public route");
1913 assert_eq!(passes(&[Mode::Plain; 600]), bounded, "600 plain hashers, bounded passes");
1914 }
1915
1916 #[test]
1919 fn held_workspace_preserves_distinct_message_rows() {
1920 crate::initialize();
1921 for n in [2usize, 15, 16, 17, 31, 32, 33, 127, 128, 129, 257] {
1922 let count = n.min(TABLE);
1923 let mut workspace = HeldWorkspace::<TABLE>::new();
1924 let (level, next) = workspace.buffers(count);
1925 assert_eq!((level.len(), next.len()), (16 * count, 8 * count), "workspace CV capacities");
1926 let inputs: Vec<Vec<u8>> =
1927 (0..n).map(|i| (0..2 * crate::STAGE_LEN + i % 71).map(|j| ((i * 37 + j * 17 + (j >> 8)) % 251) as u8).collect()).collect();
1928 let keys: Vec<[u8; 32]> = (0..n).map(|i| core::array::from_fn(|j| (i * 37 + j * 11) as u8)).collect();
1929 for flavor in 0..4 {
1930 let mode = |i: usize| match flavor {
1931 0 => Mode::Plain,
1932 1 => Mode::Keyed(&keys[0]),
1933 2 => Mode::Keyed(&keys[i]),
1934 _ => match i % 3 {
1935 0 => Mode::Plain,
1936 1 => Mode::Keyed(&keys[i]),
1937 _ => Mode::DeriveKey("distinct held rows"),
1938 },
1939 };
1940 let mut hashers: Vec<_> = (0..n).map(|i| Hasher::new(mode(i), None)).collect();
1941 let mut pieces = Vec::with_capacity(n);
1942 for start in (0..2 * crate::STAGE_LEN).step_by(4096) {
1943 pieces.clear();
1944 pieces.extend(inputs.iter().enumerate().map(|(i, b)| (i, &b[start..start + 4096])));
1945 update_each(&mut hashers, &pieces);
1946 assert!(hashers.iter().all(|h| h.held_group().is_none()), "each turn completes its held stages");
1947 }
1948 for (i, (h, input)) in hashers.iter_mut().zip(&inputs).enumerate() {
1949 h.update(&input[2 * crate::STAGE_LEN..]);
1950 assert_eq!(h.clone().finalize(), crate::test::official::hash(mode(i), input), "n={n} flavor={flavor} row={i}");
1951 }
1952 }
1953 }
1954 }
1955
1956 #[test]
1960 fn held_dispatch_ignores_key_equality_and_prefixes() {
1961 crate::initialize();
1962 let input = vec![42u8; 2 * crate::STAGE_LEN];
1963 for platform in crate::test::every_platform() {
1964 for n in [3usize, 8, 16, 17, 33] {
1965 for mixed in [false, true] {
1966 let mut reference = None;
1967 for prefix in (0..=8).rev() {
1970 let keys: Vec<[u8; 32]> = (0..n)
1971 .map(|i| {
1972 let mut key = [0x6du8; 32];
1973 if prefix < 8 {
1974 key[4 * prefix..4 * prefix + 4].copy_from_slice(&(i as u32 + 1).to_le_bytes());
1975 }
1976 key
1977 })
1978 .collect();
1979 let mode = |i: usize| {
1980 if !mixed || i % 3 == 1 {
1981 Mode::Keyed(&keys[i])
1982 } else if i % 3 == 0 {
1983 Mode::Plain
1984 } else {
1985 Mode::DeriveKey("held key-prefix regression")
1986 }
1987 };
1988 let mut hashers: Vec<_> = (0..n)
1989 .map(|i| {
1990 let mut h = Hasher::new(mode(i), None);
1991 h.set_platform_for_test(platform);
1992 h
1993 })
1994 .collect();
1995 HELD_GROUPS.with(|g| g.borrow_mut().clear());
1996 crate::RAN_ENTRIES.with(|e| e.borrow_mut().clear());
1997 crate::COUNTED.with(|c| c[crate::Counted::HeldPass as usize].set(0));
1998 for piece in input.chunks(4096) {
1999 let pieces: Vec<_> = (0..n).map(|i| (i, piece)).collect();
2000 update_each(&mut hashers, &pieces);
2001 }
2002 let groups = HELD_GROUPS.with(|g| g.borrow().clone());
2004 let entries = crate::RAN_ENTRIES.with(|e| e.borrow().clone());
2005 let passes = crate::COUNTED.with(|c| c[crate::Counted::HeldPass as usize].get());
2006 assert_eq!(groups.iter().map(Vec::len).sum::<usize>(), 2 * n, "both held stages observed");
2007 let work = (groups, entries, passes);
2008 if let Some(expected) = &reference {
2009 assert_eq!(
2010 &work, expected,
2011 "dispatch work independent of key equality and prefix: {platform:?} n={n} mixed={mixed} prefix={prefix}"
2012 );
2013 } else {
2014 reference = Some(work);
2015 }
2016 for (i, h) in hashers.iter().enumerate() {
2017 assert_eq!(h.clone().finalize(), crate::test::official::hash(mode(i), &input));
2018 }
2019 }
2020 }
2021 }
2022 }
2023 }
2024
2025 #[test]
2028 fn test_held_key_groups_take_one_partition_pass() {
2029 let entry = |width| if width == 8 { crate::ffi_output::entry8() } else { crate::ffi_output::entry() };
2030 for platform in crate::test::every_platform() {
2031 let width = crate::ffi_output::lanes(platform);
2032 if width == 0 {
2033 continue;
2034 }
2035 for n in [2usize, 7, 8, 9, 15, 16, 17, 31, 32, 33] {
2036 for flavor in 0..4 {
2037 let keys: Vec<[u8; 32]> = (0..n).map(|i| core::array::from_fn(|j| (i * 37 + j * 11) as u8)).collect();
2038 let modes: Vec<Mode<'_>> = (0..n)
2039 .map(|i| match flavor {
2040 0 => Mode::Plain,
2041 1 => Mode::Keyed(&keys[0]),
2042 2 => Mode::Keyed(&keys[i]),
2043 _ => match i % 3 {
2044 0 => Mode::Plain,
2045 1 => Mode::Keyed(&keys[i]),
2046 _ => Mode::DeriveKey("held parent lanes"),
2047 },
2048 })
2049 .collect();
2050 let offsets: Vec<_> = (0..n).map(|i| (i % 3) * crate::STAGE_LEN).collect();
2051 let data: Vec<Vec<u8>> =
2052 (0..n).map(|i| (0..offsets[i] + crate::STAGE_LEN + 97).map(|j| ((i * 37 + j * 17) % 251) as u8).collect()).collect();
2053 let mut hashers: Vec<_> = (0..n)
2054 .map(|i| {
2055 let mut h = Hasher::new(modes[i], None);
2056 h.set_platform_for_test(platform);
2057 h.update(&data[i][..offsets[i]]);
2058 h
2059 })
2060 .collect();
2061 crate::COUNTED.with(|c| c[crate::Counted::HeldPass as usize].set(0));
2062 crate::RAN_ENTRIES.with(|r| r.borrow_mut().clear());
2063 for start in (0..crate::STAGE_LEN).step_by(4096) {
2064 let pieces: Vec<_> = (0..n).map(|i| (i, &data[i][offsets[i] + start..offsets[i] + start + 4096])).collect();
2065 update_each(&mut hashers, &pieces);
2066 }
2067 let parent_entries = crate::RAN_ENTRIES.with(|r| r.borrow().clone());
2068 for i in 0..n {
2069 let end = offsets[i] + crate::STAGE_LEN;
2070 assert_eq!(hashers[i].staged_len(), 0);
2071 assert_eq!(hashers[i].count(), end as u64);
2072 assert_eq!(
2073 *hashers[i].clone().finalize().as_bytes(),
2074 crate::test::official::hash(modes[i], &data[i][..end]),
2075 "{platform:?} n={n} lane={i} flavor={flavor}"
2076 );
2077 hashers[i].update(&data[i][end..]);
2078 assert_eq!(*hashers[i].clone().finalize().as_bytes(), crate::test::official::hash(modes[i], &data[i]));
2079 let mut reader = hashers[i].clone().finalize_xof();
2080 reader.set_position(13);
2081 let mut out = [0u8; 129];
2082 reader.fill(&mut out);
2083 assert_eq!(out.as_slice(), crate::test::official::xof(modes[i], &data[i], 13, out.len()));
2084 }
2085 let partitions = crate::COUNTED.with(|c| c[crate::Counted::HeldPass as usize].get());
2086 let lanes = flavor != 0 && n >= INDEPENDENT_MIN;
2088 assert_eq!(partitions, if flavor != 0 && !lanes { n as u64 } else { 1 }, "held partitions: {platform:?} n={n} flavor={flavor}");
2089 #[cfg(target_arch = "x86_64")]
2090 {
2091 assert_eq!(parent_entries.contains(&(entry(width) as usize)), lanes, "independent parent entry: {platform:?} n={n}");
2092 if lanes && platform == crate::platform::Platform::AVX512 && crate::platform::avx2_detected() {
2093 let eight_needed = (1..=4).any(|shift| ((n * (crate::STAGE_LEN / crate::CHUNK_LEN)) >> shift) % 16 >= 8);
2094 assert_eq!(
2095 parent_entries.contains(&(entry(8) as usize)),
2096 eight_needed,
2097 "eight-wide parent remainder: {platform:?} n={n} flavor={flavor}"
2098 );
2099 }
2100 }
2101 #[cfg(target_arch = "aarch64")]
2102 {
2103 if matches!(platform, crate::platform::Platform::SME2) {
2104 assert_eq!(
2105 parent_entries.contains(&(crate::ffi_output::entry_chunks_keyed() as usize)),
2106 lanes,
2107 "SME2 chunks_keyed entry: n={n} flavor={flavor}"
2108 );
2109 }
2110 assert_eq!(parent_entries.contains(&(entry(8) as usize)), lanes, "NEON output8 parent entry: {platform:?} n={n} flavor={flavor}");
2111 }
2112 }
2113 }
2114 }
2115 }
2116
2117 #[test]
2120 fn held_passes_do_not_depend_on_keys() {
2121 crate::initialize();
2122 let input = vec![42u8; crate::STAGE_LEN];
2123 let keys: Vec<[u8; 32]> = (0..600u64)
2124 .map(|i| {
2125 let mut key = [7u8; 32];
2126 key[..8].copy_from_slice(&i.to_le_bytes());
2127 key
2128 })
2129 .collect();
2130 for platform in crate::test::every_platform() {
2131 let independent = crate::ffi_output::lanes(platform) != 0;
2132 for n in [3, 600] {
2133 for flavor in 0..3 {
2134 let mode = |i| match flavor {
2135 0 => Mode::Plain,
2136 1 => Mode::Keyed(&keys[0]),
2137 _ => Mode::Keyed(&keys[i]),
2138 };
2139 let mut hashers: Vec<_> = (0..n)
2140 .map(|i| {
2141 let mut h = Hasher::new(mode(i), None);
2142 h.set_platform_for_test(platform);
2143 h
2144 })
2145 .collect();
2146 crate::COUNTED.with(|c| c[crate::Counted::HeldPass as usize].set(0));
2147 for piece in input.chunks(4096) {
2148 let pieces: Vec<_> = (0..n).map(|i| (i, piece)).collect();
2149 update_each(&mut hashers, &pieces);
2150 }
2151 let passes = crate::COUNTED.with(|c| c[crate::Counted::HeldPass as usize].get());
2152 assert_eq!(
2153 passes,
2154 if independent || flavor == 0 { n.div_ceil(TABLE) as u64 } else { n as u64 },
2155 "key-independent passes: {platform:?} n={n} flavor={flavor}"
2156 );
2157 for (i, h) in hashers.iter().enumerate() {
2158 assert_eq!(h.clone().finalize(), crate::test::official::hash(mode(i), &input));
2159 }
2160 }
2161 }
2162 }
2163 }
2164
2165 #[test]
2166 fn test_update_each() {
2167 let mut input = vec![0u8; 1 << 20];
2168 crate::test::paint_test_input(&mut input);
2169 let lens = [0, 1, 63, 64, 1023, 1024, 1025, 2048, 4470, 8191, 16384, 16385, 65536, 100_000, 300_000];
2170 let piece_lens = [1, 1448, 4096, 1448, 16384, 31, 65536];
2171 let key = [5u8; 32];
2172 let mut hashers: Vec<Hasher> =
2174 (0..lens.len()).map(|i| if i % 3 == 1 { Hasher::new(crate::Mode::Keyed(&key), None) } else { Hasher::new(crate::Mode::Plain, None) }).collect();
2175 let mut done = vec![0usize; lens.len()];
2176 let mut k = 0;
2177 while done.iter().zip(&lens).any(|(d, l)| d < l) {
2178 let mut pieces: Vec<(usize, &[u8])> = Vec::new();
2179 for _ in 0..23 {
2180 let i = k % lens.len();
2181 let n = piece_lens[k % piece_lens.len()].min(lens[i] - done[i]);
2182 pieces.push((i, &input[done[i]..done[i] + n]));
2183 done[i] += n;
2184 k += 1;
2185 }
2186 crate::throughput::update_each(&mut hashers, &pieces);
2187 }
2188 let which: Vec<usize> = (0..lens.len()).rev().collect();
2189 let mut out = vec![[0u8; OUT_LEN]; lens.len()];
2190 crate::throughput::finalize_each(&mut hashers, &which, &mut out);
2191 for (k, &i) in which.iter().enumerate() {
2192 let want = if i % 3 == 1 {
2193 crate::convenience::hash_with(crate::Mode::Keyed(&key), &input[..lens[i]])
2194 } else {
2195 crate::convenience::hash(&input[..lens[i]])
2196 };
2197 assert_eq!(&out[k], want.as_bytes(), "len {}", lens[i]);
2198 }
2199 }
2200
2201 #[test]
2206 fn test_hash_each_matches_hash_with() {
2207 let mut input = vec![0u8; 40 * CHUNK_LEN];
2208 crate::test::paint_test_input(&mut input);
2209 let mut lens = vec![
2210 0,
2211 1,
2212 63,
2213 64,
2214 65,
2215 1023,
2216 1024,
2217 1025,
2218 2047,
2219 2048,
2220 2049,
2221 3000,
2222 4096,
2223 5000,
2224 15 * CHUNK_LEN,
2225 15 * CHUNK_LEN + 1,
2226 16 * CHUNK_LEN - 1,
2227 16 * CHUNK_LEN,
2228 16 * CHUNK_LEN + 1,
2229 40 * CHUNK_LEN,
2230 ];
2231 for n in 2..16 {
2232 lens.push(n * CHUNK_LEN);
2233 lens.push(n * CHUNK_LEN - 7);
2234 }
2235 let items: Vec<&[u8]> = lens.iter().enumerate().map(|(j, &l)| &input[j % 3..j % 3 + l.min(input.len() - 2)]).collect();
2236 let key = [9u8; 32];
2237 for mode in [Mode::Plain, Mode::Keyed(&key), Mode::DeriveKey("hash_each test")] {
2238 let mut out = vec![[0u8; OUT_LEN]; items.len()];
2239 crate::throughput::hash_each(mode, &crate::test::items(&crate::test::messages(&items), &items), &mut out);
2240 for (item, digest) in items.iter().zip(&out) {
2241 assert_eq!(digest, crate::convenience::hash_with(mode, item).as_bytes(), "length {}", item.len());
2242 }
2243 }
2244 }
2245
2246 #[test]
2251 fn hash_each_works_during_thread_local_teardown() {
2252 use std::sync::Arc;
2253 use std::sync::atomic::{AtomicBool, Ordering};
2254 crate::initialize();
2255 let ran = Arc::new(AtomicBool::new(false));
2256 let ok = Arc::new(AtomicBool::new(false));
2257 struct OnExit {
2258 ran: Arc<AtomicBool>,
2259 ok: Arc<AtomicBool>,
2260 }
2261 impl Drop for OnExit {
2262 fn drop(&mut self) {
2263 self.ran.store(true, Ordering::SeqCst);
2264 let tree = crate::throughput::TreeHasher::new(Mode::Plain);
2265 let mut empty: [[u8; OUT_LEN]; 0] = [];
2267 tree.hash_each(&[], &mut empty);
2268 let msg_a = [0x11u8; 2 * CHUNK_LEN + 7];
2271 let msg_b = [0x22u8; 3 * CHUNK_LEN + 13];
2272 let slices = [&msg_a[..], &msg_b[..]];
2273 let blocks = crate::test::messages(&slices);
2274 let items = crate::test::items(&blocks, &slices);
2275 let mut out = [[0u8; OUT_LEN]; 2];
2276 prepare_thread();
2277 tree.hash_each(&items, &mut out);
2278 let matched = out[0] == *blake3::hash(&msg_a).as_bytes() && out[1] == *blake3::hash(&msg_b).as_bytes();
2279 self.ok.store(matched, Ordering::SeqCst);
2280 }
2281 }
2282 std::thread_local! {
2283 static EARLIER: core::cell::RefCell<Option<OnExit>> = const { core::cell::RefCell::new(None) };
2284 }
2285 let ran_c = Arc::clone(&ran);
2286 let ok_c = Arc::clone(&ok);
2287 std::thread::spawn(move || {
2288 EARLIER.with(|slot| *slot.borrow_mut() = Some(OnExit { ran: ran_c, ok: ok_c }));
2291 let msg = [0x33u8; 2 * CHUNK_LEN];
2293 let slices = [&msg[..]];
2294 let blocks = crate::test::messages(&slices);
2295 let items = crate::test::items(&blocks, &slices);
2296 let mut out = [[0u8; OUT_LEN]; 1];
2297 crate::throughput::hash_each(Mode::Plain, &items, &mut out);
2298 assert_eq!(out[0], *blake3::hash(&msg).as_bytes());
2299 })
2300 .join()
2301 .expect("thread teardown with hash_each must not panic");
2302 assert!(ran.load(Ordering::SeqCst), "TLS destructor must have run");
2303 assert!(ok.load(Ordering::SeqCst), "TLS destructor digests must match");
2304 }
2305
2306 #[test]
2310 fn hash_held_selects_smallest_cohort_tier() {
2311 crate::initialize();
2312 let data = std::vec![0x42u8; crate::STAGE_LEN + 17];
2313 let expected = *blake3::hash(&data).as_bytes();
2314 for (count, expected_tier) in [(1usize, 1usize), (2, 16), (16, 16), (17, 16), (33, 16)] {
2315 let mut hashers: std::vec::Vec<Hasher> = (0..count).map(|_| Hasher::new(Mode::Plain, None)).collect();
2316 LAST_COHORT_TIER.with(|t| t.set(0));
2317 for piece in data.chunks(4096) {
2318 let pieces: std::vec::Vec<(usize, &[u8])> = (0..count).map(|i| (i, piece)).collect();
2319 update_each(&mut hashers[..], &pieces);
2320 }
2321 assert_eq!(LAST_COHORT_TIER.with(|t| t.get()), expected_tier, "count={count}");
2322 assert_eq!(*hashers[0].finalize().as_bytes(), expected);
2323 }
2324 }
2325
2326 #[cfg(any(target_arch = "x86_64", target_os = "macos"))]
2335 #[test]
2336 fn small_held_cohorts_fit_in_64kib_stack() {
2337 crate::initialize();
2338 let data = std::vec![0x42u8; crate::STAGE_LEN + 97];
2339 let expected_plain = *blake3::hash(&data).as_bytes();
2340 let key = [0x5Au8; 32];
2341 let expected_keyed = *blake3::keyed_hash(&key, &data).as_bytes();
2342 for (count, keyed_first, piece_len) in [
2343 (1usize, false, 4096usize),
2344 (2, false, 4096),
2345 (3, true, 4096),
2346 (16, true, 4096),
2347 (17, false, 1024),
2348 (17, true, 4096),
2349 (33, false, 1024),
2350 (33, true, 4096),
2351 ] {
2352 let data_c = data.clone();
2353 let mut hashers: std::vec::Vec<Hasher> =
2354 (0..count).map(|i| if keyed_first && i == 0 { Hasher::new(Mode::Keyed(&key), None) } else { Hasher::new(Mode::Plain, None) }).collect();
2355 let (first, last, saw_independent) = std::thread::Builder::new()
2356 .stack_size(64 * 1024)
2357 .spawn(move || {
2358 HELD_GROUPS.with(|g| g.borrow_mut().clear());
2359 for piece in data_c.chunks(piece_len) {
2360 let pieces: std::vec::Vec<(usize, &[u8])> = (0..count).map(|i| (i, piece)).collect();
2361 update_each(&mut hashers[..], &pieces);
2362 }
2363 let saw = HELD_GROUPS.with(|g| g.borrow().iter().any(|h| h.len() == count));
2364 (*hashers[0].finalize().as_bytes(), *hashers[count - 1].finalize().as_bytes(), saw)
2365 })
2366 .expect("spawn 64 KiB thread")
2367 .join()
2368 .expect("held cohort must fit in 64 KiB stack");
2369 assert_eq!(first, if keyed_first { expected_keyed } else { expected_plain }, "cohort of {count} (keyed={keyed_first}) first");
2370 assert_eq!(last, expected_plain, "cohort of {count} (keyed={keyed_first}) last");
2371 #[cfg(target_arch = "x86_64")]
2372 if keyed_first && count >= INDEPENDENT_MIN && matches!(Platform::detect(), Platform::AVX2 | Platform::AVX512) {
2373 assert!(saw_independent, "mixed cohort of {count} must actually run held_groups (>16 tiled on 64 KiB stack)");
2374 }
2375 let _ = saw_independent;
2376 }
2377 }
2378
2379 #[test]
2386 fn hash_each_middle_all_chunk_counts_partial_tails_and_modes() {
2387 crate::initialize();
2388 let key = [0x3cu8; crate::KEY_LEN];
2389 let mut x = 0x9e37_79b9_7f4a_7c15u64;
2390 let mut fill = |n: usize| -> std::vec::Vec<u8> {
2391 (0..n)
2392 .map(|_| {
2393 x ^= x << 13;
2394 x ^= x >> 7;
2395 x ^= x << 17;
2396 x as u8
2397 })
2398 .collect()
2399 };
2400
2401 let tails = [0usize, 1, 63, 64, 65, 512, 1023];
2406 let mut raw: std::vec::Vec<std::vec::Vec<u8>> = std::vec![fill(0), fill(1), fill(64), fill(1024), fill(16 * CHUNK_LEN), fill(16 * CHUNK_LEN + 37)];
2407 for chunks in 2..ALONE_CHUNKS {
2408 for &tail in &tails {
2409 let len = if tail == 0 { chunks * CHUNK_LEN } else { (chunks - 1) * CHUNK_LEN + tail };
2410 raw.push(fill(len));
2411 }
2412 }
2413 while raw.len() < LANES_AT_ONCE + 20 {
2415 raw.push(fill(4 * CHUNK_LEN + 333));
2416 }
2417 let slices: std::vec::Vec<&[u8]> = raw.iter().map(|v| v.as_slice()).collect();
2418 let blocks = crate::test::messages(&slices);
2419 let items = crate::test::items(&blocks, &slices);
2420 for (m, mode) in [Mode::Plain, Mode::Keyed(&key), Mode::DeriveKey("each middle simd")].into_iter().enumerate() {
2421 let mut out = std::vec![[0u8; OUT_LEN]; items.len()];
2422 crate::throughput::hash_each(mode, &items, &mut out);
2423 for (i, s) in slices.iter().enumerate() {
2424 assert_eq!(out[i], crate::test::official::hash(mode, s), "mode={m} item {i} len={}", s.len());
2425 }
2426 }
2427
2428 #[cfg(target_arch = "x86_64")]
2431 let block_lanes = crate::pair::takes_platform(Platform::detect());
2432 #[cfg(target_arch = "aarch64")]
2433 let block_lanes = true;
2434 #[cfg(target_arch = "aarch64")]
2435 let last_lanes = crate::neon_hybrid::sha3_detected();
2436 #[cfg(not(target_arch = "aarch64"))]
2437 let last_lanes = false;
2438
2439 for count in [1usize, 2, 3, 17] {
2440 let bufs: std::vec::Vec<std::vec::Vec<u8>> = (0..count).map(|k| fill(14 * CHUNK_LEN + 100 + k * 7)).collect();
2441 let s: std::vec::Vec<&[u8]> = bufs.iter().map(|v| v.as_slice()).collect();
2442 let b = crate::test::messages(&s);
2443 let it = crate::test::items(&b, &s);
2444 let mut out = std::vec![[0u8; OUT_LEN]; count];
2445 crate::COUNTED.with(|c| {
2446 c[crate::Counted::ByBlocksCall as usize].set(0);
2447 c[crate::Counted::HashManyCall as usize].set(0);
2448 });
2449 crate::throughput::hash_each(Mode::Plain, &it, &mut out);
2450 for (i, msg) in s.iter().enumerate() {
2451 assert_eq!(out[i], crate::test::official::hash(Mode::Plain, msg), "15-chunk count={count} i={i}");
2452 }
2453 let by_blocks = crate::COUNTED.with(|c| c[crate::Counted::ByBlocksCall as usize].get());
2454 let hash_many = crate::COUNTED.with(|c| c[crate::Counted::HashManyCall as usize].get());
2455 if count == 1 {
2456 assert_eq!(by_blocks, 0, "single partial tail skips hash_chunks_by_blocks");
2457 assert_eq!(hash_many, 14, "single 15-chunk message runs 14 chunk rounds only");
2458 } else {
2459 assert_eq!(hash_many, 18, "count={count} 15-chunk messages batch all 3 parent + 1 root rounds");
2461 if block_lanes {
2462 assert!(by_blocks > 0, "count={count} >= 2 shared-prefix partial tails batch via hash_chunks_by_blocks");
2463 }
2464 }
2465 }
2466
2467 let partial_cases: &[(&str, &[usize], u64)] = &[
2478 ("incompatible k=1,2", &[CHUNK_LEN + 103, CHUNK_LEN + 167], 0),
2479 ("shared k=1 pair", &[CHUNK_LEN + 103, CHUNK_LEN + 103], if block_lanes { 1 } else { 0 }),
2480 ("shared k=7 at 511/512 boundary", &[CHUNK_LEN + 511, CHUNK_LEN + 512], if block_lanes { 1 } else { 0 }),
2481 ("split k=7/8 at 512/513 boundary", &[CHUNK_LEN + 512, CHUNK_LEN + 513], 0),
2482 ("k=0 pair + singleton k=1", &[CHUNK_LEN + 32, CHUNK_LEN + 32, CHUNK_LEN + 103], if block_lanes && last_lanes { 2 } else { 0 }),
2483 ("shared c=2 tails + trailing exact 2-chunk", &[2 * CHUNK_LEN + 512, 2 * CHUNK_LEN + 512, 2 * CHUNK_LEN], if block_lanes { 1 } else { 0 }),
2484 ("single c=2 tail + trailing exact 2-chunk", &[2 * CHUNK_LEN + 512, 2 * CHUNK_LEN], 0),
2485 ];
2486 for &(label, lens, want_calls) in partial_cases {
2487 let bufs: std::vec::Vec<std::vec::Vec<u8>> = lens.iter().map(|&n| fill(n)).collect();
2488 let s: std::vec::Vec<&[u8]> = bufs.iter().map(|v| v.as_slice()).collect();
2489 let b = crate::test::messages(&s);
2490 let it = crate::test::items(&b, &s);
2491 let mut out = std::vec![[0u8; OUT_LEN]; lens.len()];
2492 crate::COUNTED.with(|c| c[crate::Counted::ByBlocksCall as usize].set(0));
2493 crate::throughput::hash_each(Mode::Plain, &it, &mut out);
2494 for (i, msg) in s.iter().enumerate() {
2495 assert_eq!(out[i], crate::test::official::hash(Mode::Plain, msg), "{label} i={i}");
2496 }
2497 let got_calls = crate::COUNTED.with(|c| c[crate::Counted::ByBlocksCall as usize].get());
2498 assert_eq!(got_calls, want_calls, "{label}: exact ByBlocksCall count");
2499 }
2500
2501 if block_lanes {
2503 let small_bufs = [fill(64), fill(128)];
2504 let s: std::vec::Vec<&[u8]> = small_bufs.iter().map(|v| v.as_slice()).collect();
2505 let b = crate::test::messages(&s);
2506 let it = crate::test::items(&b, &s);
2507 let mut out = [[0u8; OUT_LEN]; 2];
2508 SHARED.with(|shared| {
2509 let _held = shared.borrow_mut();
2510 crate::throughput::hash_each(Mode::Plain, &it, &mut out);
2511 });
2512 for (i, msg) in s.iter().enumerate() {
2513 assert_eq!(out[i], crate::test::official::hash(Mode::Plain, msg), "all-small fast exit i={i}");
2514 }
2515 }
2516
2517 let over_full = BY_BLOCKS_AT_ONCE + 1;
2519 let bufs: std::vec::Vec<std::vec::Vec<u8>> = (0..over_full).map(|_| fill(CHUNK_LEN + 512)).collect();
2520 let s: std::vec::Vec<&[u8]> = bufs.iter().map(|v| v.as_slice()).collect();
2521 let b = crate::test::messages(&s);
2522 let it = crate::test::items(&b, &s);
2523 let mut out = std::vec![[0u8; OUT_LEN]; over_full];
2524 crate::COUNTED.with(|c| c[crate::Counted::ByBlocksCall as usize].set(0));
2525 crate::throughput::hash_each(Mode::Plain, &it, &mut out);
2526 for (i, msg) in s.iter().enumerate() {
2527 assert_eq!(out[i], crate::test::official::hash(Mode::Plain, msg), "over_full i={i}");
2528 }
2529 let got_calls = crate::COUNTED.with(|c| c[crate::Counted::ByBlocksCall as usize].get());
2530 let want_over_full = if block_lanes { (BY_BLOCKS_AT_ONCE as u64 / 16) + 1 } else { 0 };
2531 assert_eq!(got_calls, want_over_full, "BY_BLOCKS_AT_ONCE + 1 same-counter partial tails flush exactly");
2532 }
2533}