Skip to main content

blake3_servil_core/
block.rs

1//! The calls' input: [`Block`]s, 64 bytes each on a 64-byte boundary, and
2//! [`Batch`], the batch calls' only input, which holds messages of one
3//! length in them with every byte past each message zero (BLAKE3 #146,
4//! John Servil's proposal; the owning builder, Zooko's choice of October
5//! 24; the batch calls taking it, so that a nonzero byte there cannot be
6//! written, Zooko's of October 28, BLAKE3 #205).
7
8use crate::BLOCK_LEN;
9
10/// 64 bytes on a 64-byte boundary: the unit the calls read, so every
11/// message starts on a cache line. A [`Batch`] holds its messages in
12/// blocks, each message starting a block and taking whole blocks (one for
13/// an empty message).
14///
15/// # Trait implementations
16///
17/// - `Clone` duplicates all 64 bytes in another aligned block.
18/// - `Copy` preserves every byte, including any padding of a message within
19///   the block.
20/// - `Debug` prints every byte in hexadecimal, including message padding.
21/// - `Eq` treats blocks as equal exactly when their byte arrays agree.
22/// - `PartialEq` compares all contents as ordinary byte arrays, without a
23///   constant-time guarantee.
24#[repr(C, align(64))]
25#[derive(Clone, Copy, PartialEq, Eq)]
26pub struct Block(pub [u8; BLOCK_LEN]);
27
28impl Block {
29    /// A block of zeros.
30    pub const ZERO: Block = Block([0; BLOCK_LEN]);
31
32    /// The blocks' bytes, in order.
33    pub fn bytes(blocks: &[Block]) -> &[u8] {
34        // Sound: a Block is 64 bytes with no padding, and u8 needs no alignment.
35        unsafe { core::slice::from_raw_parts(blocks.as_ptr().cast(), blocks.len() * BLOCK_LEN) }
36    }
37
38    /// The blocks' bytes, in order, for writing.
39    pub fn bytes_mut(blocks: &mut [Block]) -> &mut [u8] {
40        // Sound: as in bytes, and the borrow is exclusive.
41        unsafe { core::slice::from_raw_parts_mut(blocks.as_mut_ptr().cast(), blocks.len() * BLOCK_LEN) }
42    }
43
44    /// `bytes` as blocks, without a copy, when they start on a 64-byte
45    /// boundary and are whole blocks (bytes already in place, such as a
46    /// mapped file's records), or are empty: `None` otherwise.
47    pub fn from_bytes(bytes: &[u8]) -> Option<&[Block]> {
48        // An empty slice's pointer says nothing of placement.
49        if bytes.is_empty() {
50            return Some(&[]);
51        }
52        if bytes.as_ptr().align_offset(BLOCK_LEN) != 0 || bytes.len() % BLOCK_LEN != 0 {
53            return None;
54        }
55        // Sound: aligned and whole blocks, just checked; Block has no padding.
56        Some(unsafe { core::slice::from_raw_parts(bytes.as_ptr().cast(), bytes.len() / BLOCK_LEN) })
57    }
58}
59
60impl core::fmt::Debug for Block {
61    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
62        write!(f, "Block({:02x?})", &self.0[..])
63    }
64}
65
66/// Messages of one length in [`Block`]s, the batch calls' input: each
67/// message starts a block, and every byte past each message's end is zero,
68/// since a `Batch` lets the program write only the messages' own bytes (so
69/// the bytes the batch kernels read in place, past a message, can never be
70/// wrong). It owns its blocks (`Batch::new`), or borrows blocks
71/// already in place whose messages fill them, with no bytes past their ends
72/// ([`Batch::from_blocks`]: a Merkle layer's 64-byte nodes, a mapped file's
73/// records).
74///
75/// ```
76/// # blake3_servil_core::initialize();
77/// use blake3_servil_core::{Mode, convenience, throughput::{self, Batch}};
78/// let mut batch = Batch::new(100, 3);
79/// for i in 0..3 {
80///     batch.set(i, &[i as u8; 100]);
81/// }
82/// let mut out = [[0u8; 32]; 3];
83/// throughput::hash_many(Mode::Plain, &batch, &mut out);
84/// assert_eq!(out[2], *convenience::hash(&[2u8; 100]).as_bytes());
85///
86/// // Read straight into a message's own bytes.
87/// batch.message_mut(1).copy_from_slice(&[9u8; 100]);
88/// throughput::hash_many(Mode::Plain, &batch, &mut out);
89/// assert_eq!(out[1], *convenience::hash(&[9u8; 100]).as_bytes());
90/// ```
91///
92/// # Trait implementations
93///
94/// - `Clone` copies owned blocks or shares a read-only borrow, keeping the
95///   same messages and padding.
96/// - `Prepared` presents the messages in order in whole-block slots, with
97///   at least one block per slot.
98#[derive(Clone)]
99pub struct Batch<'a> {
100    blocks: std::borrow::Cow<'a, [Block]>,
101    message_len: usize,
102}
103
104/// The blocks each message of `message_len` bytes takes: its bytes in
105/// whole blocks, one for an empty message.
106#[inline]
107fn blocks_per(message_len: usize) -> usize {
108    message_len.div_ceil(BLOCK_LEN).max(1)
109}
110
111impl Batch<'static> {
112    /// `count` messages of `message_len` bytes, every byte zero. The zeros
113    /// are written now, so all of a `Batch`'s memory is resident from its
114    /// making, not as its pages are first touched: make one and refill it.
115    #[inline]
116    pub fn new(message_len: usize, count: usize) -> Self {
117        // A message's blocks have a length in bytes, even where there are
118        // none of them: every call that hashes a batch multiplies it out.
119        let slot = message_len.checked_next_multiple_of(BLOCK_LEN);
120        let blocks = slot.and_then(|_| blocks_per(message_len).checked_mul(count)).expect("batch capacity overflow");
121        Batch { blocks: std::vec![Block::ZERO; blocks].into(), message_len }
122    }
123}
124
125impl<'a> Batch<'a> {
126    /// The messages of `message_len` bytes that `blocks` holds, borrowed
127    /// with no copy, where they fill their blocks: `message_len` a
128    /// multiple of 64 (no byte past a message's end to keep zero; an empty
129    /// message's block, which hashing ignores, counts as one), and `blocks`
130    /// a whole number of messages (checked here in every build).
131    #[inline]
132    pub fn from_blocks(blocks: &'a [Block], message_len: usize) -> Self {
133        assert!(
134            message_len % BLOCK_LEN == 0,
135            "Batch::from_blocks takes messages that fill their blocks, not {message_len} B (Batch::new makes one for any length)"
136        );
137        let per = blocks_per(message_len);
138        assert!(blocks.len() % per == 0, "{} blocks hold no whole number of {message_len}-byte messages", blocks.len());
139        Batch { blocks: blocks.into(), message_len }
140    }
141
142    /// For the crate's own tests: `blocks` as a batch of `message_len`-byte
143    /// messages in place, whatever their length, each at the start of its
144    /// blocks and every byte past it zero (checked): the tests' layouts,
145    /// batches beside guard pages among them.
146    #[doc(hidden)]
147    pub fn in_place(blocks: &'a [Block], message_len: usize) -> Self {
148        let per = blocks_per(message_len);
149        assert!(blocks.len() % per == 0, "{} blocks hold no whole number of {message_len}-byte messages", blocks.len());
150        let slot = per.checked_mul(BLOCK_LEN).expect("batch slot overflow");
151        assert!(
152            Block::bytes(blocks).chunks_exact(slot).all(|s| message_len == 0 || s[message_len..].iter().all(|&b| b == 0)),
153            "a test's batch has a nonzero byte past a message"
154        );
155        Batch { blocks: blocks.into(), message_len }
156    }
157
158    /// The messages' length.
159    #[inline]
160    pub fn message_len(&self) -> usize {
161        self.message_len
162    }
163
164    /// How many whole messages it holds.
165    #[inline]
166    pub fn len(&self) -> usize {
167        self.blocks.len() / blocks_per(self.message_len)
168    }
169
170    /// Whether it holds no messages.
171    #[inline]
172    pub fn is_empty(&self) -> bool {
173        self.blocks.is_empty()
174    }
175
176    /// Its blocks, as the kernels read them: each message at the start of
177    /// its blocks, with every byte past a nonempty message's end zero (a
178    /// borrowed zero-length batch preserves its caller's original block
179    /// bytes, which empty-message hashing ignores).
180    #[inline]
181    pub fn blocks(&self) -> &[Block] {
182        &self.blocks
183    }
184}
185
186/// A line of the cache, the unit [`Packed`] storage is allocated in: 128
187/// bytes on a 128-byte boundary (Apple silicon's line; two of x86-64's,
188/// which its prefetchers fetch as a pair).
189#[repr(C, align(128))]
190#[derive(Clone, Copy)]
191struct Line([u8; 128]);
192
193/// `count` messages of `N` bytes each, packed end to end with nothing
194/// between them, on a 128-byte boundary: a compact layout for many
195/// short messages of one length (a Merkle layer's leaves or digests)
196/// without per-message block padding in caller memory (`N` is 16, 32, or 48;
197/// backing storage is `N` bytes per message rounded up once to a
198/// 128-byte line). It reads and writes as a `[[u8; N]]`
199/// (`leaves[i] = digest`), and the batch calls take it as they take a
200/// [`Batch`]. For `Packed<32>` with an even count, the digests can also
201/// be borrowed directly as 64-byte parent pairs via [`Packed::as_blocks`]
202/// (carry or pad an odd last digest according to your tree).
203///
204/// **Speed vs. [`Batch`]:** full SIMD groups run directly on zero-padding-free
205/// packed kernels (AVX-512, AVX2, SME2, and AArch64 NEON `8+3`) that load the
206/// 16-, 32-, or 48-byte messages straight from caller memory and skip the
207/// guaranteed-zero message words, making `Packed<N>` both smaller in memory
208/// and faster than [`Batch`] for whole-group batches; only a short trailing
209/// remainder (or SSE4.1) expands into a 1 KiB stack buffer. The alignment is
210/// the type's: only this constructor makes one, so a call checks nothing
211/// about alignment.
212///
213/// # Trait implementations
214///
215/// - `Deref` borrows exactly the message arrays in order, excluding the
216///   allocation's trailing padding.
217/// - `DerefMut` lets the caller replace message bytes without changing the
218///   count or accessing trailing padding.
219/// - `Prepared` lends the contiguous 16-, 32-, or 48-byte messages directly to
220///   batch calls.
221pub struct Packed<const N: usize> {
222    lines: std::vec::Vec<Line>,
223    count: usize,
224}
225
226impl<const N: usize> Packed<N> {
227    const FITS: () = assert!(N == 16 || N == 32 || N == 48, "Packed holds messages of 16, 32, or 48 bytes");
228
229    /// `count` messages of zeros, resident from the making.
230    pub fn new(count: usize) -> Self {
231        let () = Self::FITS;
232        let bytes = count.checked_mul(N).expect("Packed byte length overflow");
233        let lines = bytes.div_ceil(128);
234        Packed { lines: std::vec![Line([0; 128]); lines], count }
235    }
236
237    /// Its bytes: the messages end to end.
238    #[inline]
239    pub(crate) fn bytes(&self) -> &[u8] {
240        self[..].as_flattened()
241    }
242}
243
244impl Packed<32> {
245    /// Its digests two by two as 64-byte blocks: a Merkle layer's parents,
246    /// each the pair of its children's digests, borrowed as a
247    /// [`Batch`] with [`Batch::from_blocks`]`(.., 64)`. Requires an even
248    /// count (a layer of an odd count pads or carries its last digest).
249    /// Hash a tree's nodes apart from its leaves ([`hash_many`](crate::throughput::hash_many)).
250    pub fn as_blocks(&self) -> &[Block] {
251        assert!(self.count % 2 == 0, "pairs of digests: an even count, not {}", self.count);
252        Block::from_bytes(self.bytes()).expect("128-byte aligned even count of 32-byte digests")
253    }
254}
255
256impl<const N: usize> core::ops::Deref for Packed<N> {
257    type Target = [[u8; N]];
258    #[inline]
259    fn deref(&self) -> &[[u8; N]] {
260        // Sound: `lines` holds at least `count * N` initialized bytes, and
261        // `[u8; N]` has alignment 1; using `self.count` directly keeps
262        // `Packed::len()` a single load without multiplying/dividing by N (#565).
263        unsafe { core::slice::from_raw_parts(self.lines.as_ptr().cast(), self.count) }
264    }
265}
266
267impl<const N: usize> core::ops::DerefMut for Packed<N> {
268    #[inline]
269    fn deref_mut(&mut self) -> &mut [[u8; N]] {
270        // Sound: as in `deref`, with exclusive access to `self.lines`.
271        unsafe { core::slice::from_raw_parts_mut(self.lines.as_mut_ptr().cast(), self.count) }
272    }
273}
274
275/// The batch calls' input: messages of one length, prepared so that a
276/// call reads them as they are. [`Batch`] holds them in blocks, any
277/// length; `Packed`, owned `Vec<[u8; N]>` / `Box<[[u8; N]]>`
278/// and borrowed `&[[u8; N]]` slices (`N` = 16, 32, or 48)
279/// hold fixed-width messages end to end. Sealed: the crate's types and
280/// fixed-width byte-array collections/slices alone.
281pub trait Prepared: sealed::Sealed {
282    /// The messages' bytes, one every `slot` bytes.
283    #[doc(hidden)]
284    fn bytes(&self) -> &[u8];
285    /// Each message's length.
286    #[doc(hidden)]
287    fn message_len(&self) -> usize;
288    /// The stride from one message to the next.
289    #[doc(hidden)]
290    fn slot(&self) -> usize;
291    /// The messages `messages` of this batch, as a batch: for a program
292    /// that hashes a batch in parts (each part on a thread of its own).
293    ///
294    /// Requires a range within the batch.
295    ///
296    /// ```
297    /// # blake3_servil_core::initialize();
298    /// use blake3_servil_core::{Mode, throughput::{self, Batch, Prepared}};
299    /// let mut batch = Batch::new(100, 8);
300    /// for i in 0..8 {
301    ///     batch.set(i, &[i as u8; 100]);
302    /// }
303    /// let (mut whole, mut parts) = ([[0u8; 32]; 8], [[0u8; 32]; 8]);
304    /// throughput::hash_many(Mode::Plain, &batch, &mut whole);
305    /// throughput::hash_many(Mode::Plain, &batch.part(0..3), &mut parts[..3]);
306    /// throughput::hash_many(Mode::Plain, &batch.part(3..8), &mut parts[3..]);
307    /// assert_eq!(whole, parts);
308    /// ```
309    fn part(&self, messages: core::ops::Range<usize>) -> Part<'_> {
310        let slot = self.slot();
311        assert!(messages.start <= messages.end && messages.end <= self.bytes().len() / slot, "the part {messages:?} lies within the batch");
312        Part { bytes: &self.bytes()[messages.start * slot..messages.end * slot], message_len: self.message_len(), slot }
313    }
314}
315
316/// Some of a batch's messages, in place: [`Prepared::part`] makes it.
317///
318/// # Trait implementations
319///
320/// - `Clone` borrows the same range without copying its messages.
321/// - `Copy` preserves the read-only view and its stride.
322/// - `Prepared` presents the selected messages in their original order and
323///   layout.
324#[derive(Clone, Copy)]
325pub struct Part<'a> {
326    bytes: &'a [u8],
327    message_len: usize,
328    slot: usize,
329}
330
331impl<'a> Part<'a> {
332    /// Reconstruct a checked `Part` from raw bytes, message length, and slot
333    /// width previously obtained from a validated [`Prepared`] batch (such as
334    /// `blake3-servil`'s `Pipeline` worker tasks; BLAKE3 #458).
335    ///
336    /// # Safety
337    ///
338    /// `bytes`, `message_len`, and `slot` must designate a slot-aligned
339    /// subrange (starting on a message boundary, whole `slot` bytes per
340    /// message) of a single validated [`Prepared`] batch whose padding
341    /// invariant holds (for every nonempty block-padded message, every byte
342    /// past `message_len` within its `slot` is zero).
343    #[doc(hidden)]
344    #[inline]
345    pub unsafe fn from_checked_slots(bytes: &'a [u8], message_len: usize, slot: usize) -> Self {
346        assert!(slot > 0 && bytes.len() % slot == 0, "checked part must hold whole slots");
347        Part { bytes, message_len, slot }
348    }
349}
350
351impl Prepared for Part<'_> {
352    #[inline]
353    fn bytes(&self) -> &[u8] {
354        self.bytes
355    }
356    #[inline]
357    fn message_len(&self) -> usize {
358        self.message_len
359    }
360    #[inline]
361    fn slot(&self) -> usize {
362        self.slot
363    }
364}
365
366mod sealed {
367    pub trait Sealed {}
368    impl Sealed for super::Batch<'_> {}
369    impl Sealed for super::Part<'_> {}
370    impl<const N: usize> Sealed for super::Packed<N> {}
371}
372
373impl Prepared for Batch<'_> {
374    #[inline]
375    fn bytes(&self) -> &[u8] {
376        Block::bytes(self.blocks())
377    }
378    #[inline]
379    fn message_len(&self) -> usize {
380        self.message_len
381    }
382    #[inline]
383    fn slot(&self) -> usize {
384        blocks_per(self.message_len) * BLOCK_LEN
385    }
386}
387
388impl<const N: usize> Prepared for Packed<N> {
389    #[inline]
390    fn bytes(&self) -> &[u8] {
391        Packed::bytes(self)
392    }
393    #[inline]
394    fn message_len(&self) -> usize {
395        N
396    }
397    #[inline]
398    fn slot(&self) -> usize {
399        N
400    }
401}
402
403macro_rules! impl_prepared_slice {
404    ($($n:literal),+) => {
405        $(
406            impl sealed::Sealed for [[u8; $n]] {}
407            impl Prepared for [[u8; $n]] {
408                #[inline]
409                fn bytes(&self) -> &[u8] {
410                    self.as_flattened()
411                }
412                #[inline]
413                fn message_len(&self) -> usize {
414                    $n
415                }
416                #[inline]
417                fn slot(&self) -> usize {
418                    $n
419                }
420            }
421            impl sealed::Sealed for std::vec::Vec<[u8; $n]> {}
422            impl Prepared for std::vec::Vec<[u8; $n]> {
423                #[inline]
424                fn bytes(&self) -> &[u8] {
425                    self.as_flattened()
426                }
427                #[inline]
428                fn message_len(&self) -> usize {
429                    $n
430                }
431                #[inline]
432                fn slot(&self) -> usize {
433                    $n
434                }
435            }
436            impl sealed::Sealed for std::boxed::Box<[[u8; $n]]> {}
437            impl Prepared for std::boxed::Box<[[u8; $n]]> {
438                #[inline]
439                fn bytes(&self) -> &[u8] {
440                    self.as_flattened()
441                }
442                #[inline]
443                fn message_len(&self) -> usize {
444                    $n
445                }
446                #[inline]
447                fn slot(&self) -> usize {
448                    $n
449                }
450            }
451        )+
452    };
453}
454
455impl_prepared_slice!(16, 32, 48);
456
457impl Batch<'_> {
458    /// Message `i`'s bytes, for writing: `message_len` of them, no more (a
459    /// borrowed batch copies its blocks first).
460    #[inline]
461    pub fn message_mut(&mut self, i: usize) -> &mut [u8] {
462        let per = blocks_per(self.message_len);
463        // Checked in every build: an index whose blocks wrapped around the
464        // address space would name another message's.
465        let end = i.checked_add(1).and_then(|next| next.checked_mul(per));
466        assert!(end.is_some_and(|end| end <= self.blocks.len()), "message {i} of a batch of {}", self.len());
467        let len = self.message_len;
468        &mut Block::bytes_mut(&mut self.blocks.to_mut()[i * per..][..per])[..len]
469    }
470
471    /// Message `i` becomes `message`, `message_len` bytes.
472    #[inline]
473    pub fn set(&mut self, i: usize, message: &[u8]) {
474        self.message_mut(i).copy_from_slice(message);
475    }
476
477    /// Mutable slices of every message's own bytes (`message_len` bytes each),
478    /// with one copy-on-write check and one stride calculation for the whole
479    /// batch (BLAKE3 #503).
480    ///
481    /// Every byte past `message_len` in each block remains inaccessible and
482    /// untouched (staying zero on owned batches and preserving caller bytes on
483    /// borrowed zero-length slots), so sub-block batches (such as 32-byte
484    /// messages) can be refilled in a tight loop without repeating per-element
485    /// copy-on-write checks.
486    #[inline]
487    pub fn messages_mut(&mut self) -> impl ExactSizeIterator<Item = &mut [u8]> {
488        let len = self.message_len;
489        let slot = blocks_per(len) * BLOCK_LEN;
490        Block::bytes_mut(self.blocks.to_mut()).chunks_exact_mut(slot).map(move |s| &mut s[..len])
491    }
492
493    /// Every byte for writing, where no message has bytes past its end to
494    /// keep zero: `message_len` a multiple of 64 and not 0.
495    pub fn blocks_mut(&mut self) -> &mut [Block] {
496        assert!(self.message_len % BLOCK_LEN == 0 && self.message_len > 0, "a batch whose messages leave no bytes past their ends ({} B)", self.message_len);
497        self.blocks.to_mut()
498    }
499
500    /// Its 64-byte messages as 32-byte digests, two a message: a Merkle
501    /// layer's digests written straight into the next layer, whose
502    /// messages are pairs of children. A layer of an odd count leaves a
503    /// digest to spare: slice it, `&mut batch.digests_mut()[..count]`.
504    pub fn digests_mut(&mut self) -> &mut [[u8; 32]] {
505        assert!(self.message_len == 2 * 32, "digests_mut takes a batch of 64-byte messages, two digests each, not {} B", self.message_len);
506        let blocks = self.blocks.to_mut();
507        // Sound: a [u8; 32] is 32 bytes with alignment 1; two fill a Block.
508        unsafe { core::slice::from_raw_parts_mut(blocks.as_mut_ptr().cast(), blocks.len() * 2) }
509    }
510}
511
512#[cfg(test)]
513mod test {
514    use super::*;
515    use crate::Mode;
516    use crate::throughput::hash_many;
517
518    /// In every build: `(i + 1) * per` wrapped where overflow is not
519    /// checked, and these indices named messages 0 and 1.
520    #[test]
521    fn message_mut_refuses_an_index_whose_blocks_wrap() {
522        for (message_len, i) in [(100, 1usize << 63), (100, (1 << 63) + 1), (1000, 1 << 60), (64, usize::MAX)] {
523            let mut batch = Batch::new(message_len, 4);
524            let call = std::panic::catch_unwind(core::panic::AssertUnwindSafe(|| batch.message_mut(i).len()));
525            let said = *call.expect_err("an index out of range was accepted").downcast::<String>().unwrap();
526            assert_eq!(said, std::format!("message {i} of a batch of 4"));
527        }
528    }
529
530    /// A batch of no messages still has a message length whose blocks
531    /// have a length in bytes.
532    #[test]
533    #[should_panic(expected = "batch capacity overflow")]
534    fn a_batch_of_no_messages_needs_a_message_length_that_fits() {
535        let _ = Batch::new(usize::MAX, 0);
536    }
537
538    #[test]
539    fn batch_capacity_rejects_wrapping_block_counts() {
540        for message_len in [128, 256] {
541            let count = usize::MAX / blocks_per(message_len) + 1;
542            assert!(
543                std::panic::catch_unwind(|| Batch::new(message_len, count)).is_err(),
544                "Batch rejects {count} messages of {message_len} bytes before constructing a value"
545            );
546        }
547    }
548
549    /// Every byte a Batch lets the program write, written nonzero: every
550    /// byte past each message's end stays zero, and each digest is the
551    /// message's own (convenience::hash, an independent path).
552    #[test]
553    fn test_a_batch_keeps_the_bytes_past_its_messages_zero() {
554        crate::initialize();
555        for len in [0, 1, 63, 64, 65, 100, 1000, 1024, 1025] {
556            let mut batch = Batch::new(len, 5);
557            for round in 1..=2u8 {
558                for i in 0..batch.len() {
559                    batch.message_mut(i).fill(round * 16 + i as u8);
560                }
561                let per = len.div_ceil(BLOCK_LEN).max(1) * BLOCK_LEN;
562                for (i, slot) in Block::bytes(batch.blocks()).chunks(per).enumerate() {
563                    assert!(slot[len..].iter().all(|&b| b == 0), "{len} B, message {i}: its padding");
564                }
565                let mut out = [[0u8; 32]; 5];
566                hash_many(Mode::Plain, &batch, &mut out);
567                for (i, d) in out.iter().enumerate() {
568                    assert_eq!(*d, *crate::convenience::hash(&std::vec![round * 16 + i as u8; len]).as_bytes(), "{len} B, message {i}, round {round}");
569                }
570            }
571        }
572    }
573
574    #[test]
575    fn test_from_bytes_takes_aligned_whole_blocks_only() {
576        let blocks = [Block::ZERO; 3];
577        let bytes = Block::bytes(&blocks);
578        assert_eq!(Block::from_bytes(bytes).map(<[Block]>::len), Some(3));
579        assert_eq!(Block::from_bytes(&bytes[..128]).map(<[Block]>::len), Some(2));
580        assert!(Block::from_bytes(&bytes[16..80]).is_none(), "16 bytes into a line");
581        assert!(Block::from_bytes(&bytes[..100]).is_none(), "a partial block");
582        assert_eq!(Block::from_bytes(&[]).map(<[Block]>::len), Some(0));
583    }
584
585    /// Blocks already in place, borrowed with no copy where the messages
586    /// fill them; a length that leaves bytes past a message is refused (only
587    /// Batch::new makes one), and blocks of no whole message count are
588    /// refused at construction so `len()` and `is_empty()` always agree.
589    #[test]
590    fn test_from_blocks_borrows_messages_that_fill_their_blocks() {
591        crate::initialize();
592        let blocks: std::vec::Vec<Block> = (0..4).map(|i| Block([i as u8; 64])).collect();
593        let batch = Batch::from_blocks(&blocks, 128);
594        assert_eq!((batch.len(), batch.is_empty(), batch.blocks().as_ptr()), (2, false, blocks.as_ptr()), "borrowed, not copied");
595        let empty = Batch::from_blocks(&[], 128);
596        assert_eq!((empty.len(), empty.is_empty()), (0, true));
597        let mut out = [[0u8; 32]; 2];
598        hash_many(Mode::Plain, &batch, &mut out);
599        assert_eq!(out[1], *crate::convenience::hash(Block::bytes(&blocks[2..])).as_bytes());
600        assert!(std::panic::catch_unwind(|| Batch::from_blocks(&blocks, 100)).is_err(), "100-byte messages");
601        assert!(std::panic::catch_unwind(|| Batch::from_blocks(&blocks[..1], 128)).is_err(), "one block of 128-byte messages");
602        assert!(std::panic::catch_unwind(|| Batch::from_blocks(&blocks[..3], 128)).is_err(), "three blocks of 128-byte messages");
603    }
604
605    #[test]
606    fn test_messages_mut_refills_all_sizes_and_preserves_padding() {
607        crate::initialize();
608        for len in [0usize, 1, 32, 63, 64, 100] {
609            let mut batch = Batch::new(len, 5);
610            let iter = batch.messages_mut();
611            assert_eq!(iter.len(), 5);
612            for (i, msg) in iter.enumerate() {
613                assert_eq!(msg.len(), len);
614                msg.fill(0x30 + i as u8);
615            }
616            let per = blocks_per(len) * BLOCK_LEN;
617            for slot in Block::bytes(batch.blocks()).chunks_exact(per) {
618                assert!(slot[len..].iter().all(|&b| b == 0), "{len} B padding must remain zero");
619            }
620            let mut out = [[0u8; 32]; 5];
621            hash_many(Mode::Plain, &batch, &mut out);
622            for (i, d) in out.iter().enumerate() {
623                assert_eq!(*d, *blake3::hash(&std::vec![0x30 + i as u8; len]).as_bytes());
624            }
625        }
626        // Borrowed batch copies on write and leaves caller blocks untouched.
627        let blocks = [Block([0x77; 64]); 2];
628        let mut borrowed = Batch::from_blocks(&blocks, 64);
629        for (i, msg) in borrowed.messages_mut().enumerate() {
630            msg.fill(i as u8 + 1);
631        }
632        assert_eq!(blocks, [Block([0x77; 64]); 2]);
633        assert_eq!(borrowed.blocks()[0], Block([1; 64]));
634        assert_eq!(borrowed.blocks()[1], Block([2; 64]));
635        // Borrowed zero-length slots yield empty slices, preserve their ignored
636        // backing bytes, and still hash to the empty digest.
637        let mut borrowed_empty = Batch::from_blocks(&blocks[..1], 0);
638        let mut yielded = 0;
639        for msg in borrowed_empty.messages_mut() {
640            assert!(msg.is_empty());
641            yielded += 1;
642        }
643        assert_eq!(yielded, 1);
644        assert_eq!(borrowed_empty.blocks()[0], Block([0x77; 64]));
645        let mut out = [[0u8; 32]; 1];
646        hash_many(Mode::Plain, &borrowed_empty, &mut out);
647        assert_eq!(out[0], *blake3::hash(&[]).as_bytes());
648    }
649
650    #[test]
651    #[should_panic(expected = "digests_mut takes a batch of 64-byte messages")]
652    fn test_digests_mut_takes_64_byte_messages() {
653        Batch::new(128, 2).digests_mut();
654    }
655
656    /// blocks_mut writes the messages themselves: the digests are of what it
657    /// wrote, and a borrowed batch copies its blocks first, leaving the
658    /// program's untouched (BLAKE3 #238: no test wrote through it).
659    #[test]
660    fn test_blocks_mut_writes_the_messages() {
661        crate::initialize();
662        let mut batch = Batch::new(128, 3);
663        for (i, b) in Block::bytes_mut(batch.blocks_mut()).iter_mut().enumerate() {
664            *b = (i / 128) as u8 + 1;
665        }
666        let mut golden = crate::test::Golden::new("blocks_mut");
667        let mut out = [[0u8; 32]; 3];
668        hash_many(Mode::Plain, &batch, &mut out);
669        golden.add(out.as_flattened(), || (1..=3u8).flat_map(|v| crate::test::official::hash(Mode::Plain, &[v; 128])).collect());
670        let mine = std::vec![Block([7u8; 64]); 2];
671        let mut borrowed = Batch::from_blocks(&mine, 64);
672        Block::bytes_mut(borrowed.blocks_mut())[..64].fill(9);
673        assert_eq!(Block::bytes(&mine)[0], 7, "the program's blocks untouched");
674        hash_many(Mode::Plain, &borrowed, &mut out[..2]);
675        golden.add(out[..2].as_flattened(), || [9u8, 7].iter().flat_map(|&v| crate::test::official::hash(Mode::Plain, &[v; 64])).collect());
676        golden.check(0x82788877fe5281c8);
677    }
678
679    #[test]
680    #[should_panic(expected = "leave no bytes past their ends")]
681    fn test_blocks_mut_refuses_messages_with_padding() {
682        Batch::new(100, 2).blocks_mut();
683    }
684
685    /// A Merkle layer: leaves' digests written by hash_many straight into
686    /// the parents' batch, two a block, then the parents hashed: the root
687    /// of four leaves is a parent of parents, keyed alike (as a tree's
688    /// caller keys its nodes).
689    #[test]
690    fn test_a_merkle_layer_lands_in_the_next_layers_blocks() {
691        crate::initialize();
692        let key = [5u8; 32];
693        let mut leaves = Batch::new(256, 4);
694        (0..4).for_each(|i| leaves.set(i, &[i as u8; 256]));
695        let mut parents = Batch::new(64, 2);
696        hash_many(Mode::Keyed(&key), &leaves, parents.digests_mut());
697        let mut root = [[0u8; 32]; 2];
698        hash_many(Mode::Keyed(&key), &parents, &mut root);
699        let leaf = |i: u8| *crate::convenience::hash_with(Mode::Keyed(&key), &[i; 256]).as_bytes();
700        let parent = |a: [u8; 32], b: [u8; 32]| *crate::convenience::hash_with(Mode::Keyed(&key), &[a, b].concat()).as_bytes();
701        assert_eq!(root[0], parent(leaf(0), leaf(1)));
702        assert_eq!(root[1], parent(leaf(2), leaf(3)));
703    }
704
705    /// What a Batch says of itself: its message length and count, empty at
706    /// zero messages; two digests a 64-byte message from digests_mut, each landing on
707    /// its own 32 bytes; a Block's Debug form names its bytes.
708    #[test]
709    fn test_a_batch_describes_itself() {
710        let batch = Batch::new(100, 3);
711        assert_eq!((batch.message_len(), batch.len(), batch.is_empty()), (100, 3, false));
712        assert_eq!(batch.blocks().len(), 6, "two blocks a 100-byte message");
713        let none = Batch::new(100, 0);
714        assert_eq!((none.len(), none.is_empty()), (0, true));
715        let mut parents = Batch::new(64, 3);
716        let digests = parents.digests_mut();
717        assert_eq!(digests.len(), 6);
718        digests[5] = [7; 32];
719        assert_eq!(&parents.blocks()[2].0[32..], &[7u8; 32][..], "the sixth digest is block 2's second half");
720        assert_eq!(&parents.blocks()[2].0[..32], &[0u8; 32][..]);
721        assert!(std::format!("{:?}", Block::ZERO).starts_with("Block([00, 00"));
722    }
723}
724
725#[cfg(test)]
726mod packed_test {
727    use super::*;
728    use crate::Mode;
729    use crate::throughput::hash_many;
730
731    #[test]
732    fn packed_capacity_rejects_wrapping_message_counts() {
733        fn check<const N: usize>() {
734            for count in [usize::MAX / N + 1, usize::MAX / N + 2] {
735                // Constructor and drop only: the old value's slices are invalid.
736                assert!(std::panic::catch_unwind(|| Packed::<N>::new(count)).is_err(), "Packed<{N}> rejects {count} messages before constructing a value");
737            }
738        }
739        check::<16>();
740        check::<32>();
741        check::<48>();
742    }
743
744    fn packed<const N: usize>(count: usize, seed: u8) -> Packed<N> {
745        let mut leaves = Packed::<N>::new(count);
746        assert_eq!(leaves.count, count);
747        assert_eq!(leaves.lines.len(), (count * N).div_ceil(128));
748        for (i, leaf) in leaves.iter_mut().enumerate() {
749            for (j, b) in leaf.iter_mut().enumerate() {
750                *b = (i as u8).wrapping_mul(31).wrapping_add(j as u8).wrapping_add(seed);
751            }
752        }
753        leaves
754    }
755
756    /// A packed batch's digests are each message's hash, in every mode,
757    /// at counts around the kernels' group of sixteen and beyond the
758    /// thread crate's split, 16 and 32 bytes a message.
759    #[test]
760    fn packed_messages_hash_as_each_message_alone() {
761        let key = [9u8; 32];
762        for (name, mode) in [("plain", Mode::Plain), ("keyed", Mode::Keyed(&key)), ("derive", Mode::DeriveKey("packed test"))] {
763            for count in [0, 1, 2, 3, 4, 5, 7, 8, 9, 15, 16, 17, 31, 33, 100, 1000, 40_000] {
764                let leaves = packed::<32>(count, 3);
765                let mut out = vec![[0u8; 32]; count];
766                hash_many(mode, &leaves, &mut out);
767                for (i, leaf) in leaves.iter().enumerate() {
768                    let want = *crate::convenience::hash_with(mode, leaf).as_bytes();
769                    assert_eq!(out[i], want, "32 B, {count} messages, message {i}, {name}");
770                }
771                let short = packed::<16>(count, 5);
772                let mut out = vec![[0u8; 32]; count];
773                hash_many(mode, &short, &mut out);
774                for (i, leaf) in short.iter().enumerate() {
775                    let want = *crate::convenience::hash_with(mode, leaf).as_bytes();
776                    assert_eq!(out[i], want, "16 B, {count} messages, message {i}, {name}");
777                }
778                let mid = packed::<48>(count, 9);
779                let mut out = vec![[0u8; 32]; count];
780                hash_many(mode, &mid, &mut out);
781                for (i, leaf) in mid.iter().enumerate() {
782                    let want = *crate::convenience::hash_with(mode, leaf).as_bytes();
783                    assert_eq!(out[i], want, "48 B, {count} messages, message {i}, {name}");
784                }
785            }
786        }
787    }
788
789    /// Borrowed `&[[u8; 16]]`, `&[[u8; 32]]`, and `&[[u8; 48]]` slices
790    /// implement `Prepared` directly (zero copy, works without `Packed`).
791    #[test]
792    fn borrowed_array_slices_hash_as_packed() {
793        crate::initialize();
794        let key = [0x42u8; 32];
795        for mode in [Mode::Plain, Mode::Keyed(&key), Mode::DeriveKey("slice packed")] {
796            for count in [0, 1, 2, 7, 16, 17, 129, 260] {
797                let s16: Vec<[u8; 16]> = (0..count).map(|i| [(i as u8).wrapping_mul(3); 16]).collect();
798                let mut out16 = vec![[0u8; 32]; count];
799                hash_many(mode, s16.as_slice(), &mut out16);
800                for (i, m) in s16.iter().enumerate() {
801                    assert_eq!(out16[i], *crate::convenience::hash_with(mode, m).as_bytes());
802                }
803
804                let s32: Vec<[u8; 32]> = (0..count).map(|i| [(i as u8).wrapping_mul(5); 32]).collect();
805                let mut out32 = vec![[0u8; 32]; count];
806                hash_many(mode, s32.as_slice(), &mut out32);
807                for (i, m) in s32.iter().enumerate() {
808                    assert_eq!(out32[i], *crate::convenience::hash_with(mode, m).as_bytes());
809                }
810
811                let s48: Vec<[u8; 48]> = (0..count).map(|i| [(i as u8).wrapping_mul(7); 48]).collect();
812                let mut out48 = vec![[0u8; 32]; count];
813                hash_many(mode, s48.as_slice(), &mut out48);
814                for (i, m) in s48.iter().enumerate() {
815                    assert_eq!(out48[i], *crate::convenience::hash_with(mode, m).as_bytes());
816                }
817            }
818        }
819    }
820
821    /// Packed storage starts on a 128-byte boundary, holds exactly its
822    /// messages end to end, and a layer's digests written into one are the
823    /// next layer's packed input (a Merkle tree of 32-byte leaves).
824    #[test]
825    fn packed_storage_is_aligned_and_chains_into_a_tree() {
826        crate::initialize();
827        let leaves = packed::<32>(1000, 7);
828        assert_eq!(leaves.as_ptr() as usize % 128, 0);
829        assert_eq!(leaves.len(), 1000);
830        assert_eq!(Prepared::bytes(&leaves).len(), 32_000);
831        assert_eq!(Prepared::bytes(&leaves)[32..64], leaves[1]);
832        // Leaves to parents: each parent is the hash of two digests, a
833        // 64-byte message, which Batch holds; parents' digests go into the
834        // next Packed layer.
835        let mut digests = Packed::<32>::new(1000);
836        hash_many(Mode::Plain, &leaves, &mut digests);
837        let parents = Batch::from_blocks(digests.as_blocks(), 64);
838        let mut next = Packed::<32>::new(500);
839        hash_many(Mode::Plain, &parents, &mut next);
840        for i in 0..500 {
841            let mut pair = [0u8; 64];
842            pair[..32].copy_from_slice(crate::convenience::hash(&leaves[2 * i]).as_bytes());
843            pair[32..].copy_from_slice(crate::convenience::hash(&leaves[2 * i + 1]).as_bytes());
844            assert_eq!(next[i], *crate::convenience::hash(&pair).as_bytes(), "parent {i}");
845        }
846    }
847}