Skip to main content

blake3_servil_core/
lib.rs

1//! `blake3-servil-core` is BLAKE3-Servil on one thread: a fast [BLAKE3]
2//! implementation for 64-bit Arm and x86-64, its assembly kernels (each
3//! proved against the specification) and every call that hashes on the
4//! thread that makes it. It produces the same digests as official BLAKE3.
5//! It starts no thread and uses no other core: the crate `blake3-servil`
6//! is this one, whole, with the calls that do.
7//!
8//! # Examples
9//!
10//! ```
11//! # fn main() -> Result<(), Box<dyn std::error::Error>> {
12//! // Once per process, before any other call (see Startup self-test).
13//! blake3_servil_core::initialize();
14//!
15//! // Hash an input all at once.
16//! let hash1 = blake3_servil_core::convenience::hash(b"foobarbaz");
17//!
18//! // Hash an input incrementally.
19//! let mut hasher = blake3_servil_core::convenience::Hasher::new(blake3_servil_core::Mode::Plain, None);
20//! hasher.update(b"foo");
21//! hasher.update(b"bar");
22//! hasher.update(b"baz");
23//! // finalize leaves the Hasher as it is: more updates may follow it.
24//! let hash2 = hasher.finalize();
25//! assert_eq!(hash1, hash2);
26//!
27//! // Extended output. OutputReader also implements Read and Seek.
28//! let mut output = [0; 1000];
29//! let mut hasher = blake3_servil_core::convenience::Hasher::new(blake3_servil_core::Mode::Plain, None);
30//! hasher.update(b"foobarbaz");
31//! let mut output_reader = hasher.finalize_xof();
32//! output_reader.fill(&mut output);
33//! assert_eq!(hash1, output[..32]);
34//!
35//! // Print a hash as hex.
36//! println!("{}", hash1);
37//!
38//! // Many short messages in one call: a Batch lays them out in Blocks.
39//! use blake3_servil_core::{throughput::{self, Batch}, Mode};
40//! let mut batch = Batch::new(64, 3);
41//! for i in 0..3 {
42//!     batch.set(i, &[i as u8; 64]);
43//! }
44//! let mut hashes = [[0u8; 32]; 3];
45//! throughput::hash_many(Mode::Plain, &batch, &mut hashes);
46//! assert_eq!(hashes[2], *blake3_servil_core::convenience::hash(&[2u8; 64]).as_bytes());
47//! # Ok(())
48//! # }
49//! ```
50//!
51//! # Two kinds of call
52//!
53//! - **[`convenience`]**: one call per hash, every feature of BLAKE3 (the
54//!   plain hash, the keyed hash, key derivation, extended output), any
55//!   slice, the result returned, and the [`Hasher`]
56//!   for a message fed in pieces. Tuned for a hash now and then, amid
57//!   other work: where it helps, a call fetches its code back into the
58//!   caches before it starts.
59//! - **[`throughput`]**, for power users: every way this crate makes
60//!   hashing fast (batches, collections, many hashers fed in turns), tuned for
61//!   call after call: an occasional call amid other work may run slower
62//!   than a convenience call would. The
63//!   program takes on more of the work: inputs come as
64//!   [`Block`](throughput::Block)s (64 bytes on a 64-byte boundary, so
65//!   alignment is the type's), digests go into the program's places, and
66//!   every call takes a [`Mode`].
67//!
68//! The [`Hasher`] runs on the calling thread; its
69//! first update is treated as a call now and then (its code fetched first
70//! where that helps), and its later updates as call after call. The
71//! throughput call that takes it, [`throughput::update_each`], is tuned as
72//! a throughput call.
73//!
74//! Start with the convenience calls; when a program needs more speed, it
75//! moves to the throughput ones.
76//!
77//! | Your data | Call |
78//! |---|---|
79//! | One message in memory (now and then) | [`convenience::hash`] (or [`convenience::hash_with`]) |
80//! | One message in memory, repeated call after call | [`throughput::hash`] (on aligned [`Block`](throughput::Block)s), or [`throughput::TreeHasher::hash`] directly on caller-owned `&[u8]` slices without copying into aligned blocks |
81//! | One message arriving in pieces | [`convenience::Hasher`] |
82//! | Many messages of one length, in one buffer | [`throughput::hash_many`] over a [`throughput::Batch`] |
83//! | Many 16-, 32-, or 48-byte messages (a Merkle layer's leaves or digests) | [`throughput::hash_many`] over [`throughput::Packed`] / `&[[u8; N]]` (compact storage; avoids refill copies in chains; full groups loaded directly on AVX2, AVX-512, NEON, and SME2; short tails and SSE4.1 expand on the stack) or an owned [`throughput::Batch::new`] (note [`Batch::from_blocks`](throughput::Batch::from_blocks) requires whole-block lengths) |
84//! | Many messages of different lengths, in memory | [`throughput::hash_each`] |
85//! | Many messages arriving at once (a server's uploads) | [`throughput::update_each`], then [`throughput::finalize_each`] |
86//!
87//! Each call returns once its hash is done, on the calling thread. For
88//! long inputs and large batches on several cores, the crate
89//! `blake3-servil` adds a multithreaded form of each, and for messages
90//! that keep arriving its Pipeline
91//! (`throughput::update_each` says when each is the one to use).
92//!
93//! Short messages hash fastest together: 1024 messages of 64 bytes in one
94//! [`throughput::hash_many`] call take about a fifth of the time of 1024
95//! [`convenience::hash`] calls.
96//!
97//! Select **keyed hashing or key derivation** with [`Mode`], supplied to
98//! throughput calls and the [`Hasher`] constructor. See [Key-dependent
99//! timing](#key-dependent-timing) for the key-independence contract.
100//!
101//! **Hashing now and then** (rather than nonstop) is slower per byte on
102//! every hash function, since its code and data must come back into the
103//! CPU's caches and a resting core runs slower at first: hashing 64 KiB
104//! after a pause takes about three times as long as nonstop on an Apple M4
105//! Max.
106//!
107//! **Apple M4 and later** have one matrix unit that this crate uses for
108//! inputs of 16 KiB and more; when several threads of a program hash such
109//! inputs at the same moment, one runs at full speed and the others at
110//! about two thirds of it.
111//!
112//! # Key-dependent timing
113//!
114//! Hashing code treats secret key bytes, including derived keys, as data:
115//! they select neither branches, memory-access addresses, nor kernels.
116//! For a fixed public call shape, grouped calls do the same work whether
117//! their hashers' keys are equal or different. Key equality selects neither
118//! groups nor temporary storage sizes.
119//!
120//! Public call shape includes the mode kind (plain, keyed, or key derivation),
121//! message and output lengths, input layout, update boundaries, hasher indices,
122//! and size hints. Dispatch may also depend on CPU features and available
123//! processing resources. A batch supplied with one [`Mode`] shares a key by
124//! construction. Plain mode's fixed key is public.
125//!
126//! This is a software-level key-independence contract. Elapsed time varies
127//! with public call shape, scheduling, clock speed, and machine load. Caller
128//! callbacks and I/O have their own timing properties. Applications choose
129//! which lengths, modes, and operation patterns they expose to observers.
130//!
131//! # Memory
132//!
133//! - **A [`Hasher`] is 26 KiB**; box it where that matters.
134//! - **These single-threaded calls allocate nothing** (except on 512-bit SME2
135//!   CPUs, where the first flat-walk tree of 32 KiB or more on each thread
136//!   lazily allocates one reusable 64 KiB thread-local scratch block; during
137//!   thread-local teardown after that block is destroyed, a bounded stack
138//!   scratch is used instead — 8 KiB up to 64 KiB inputs, 64 KiB above):
139//!   [`convenience::hash`], [`throughput::hash`], [`throughput::hash_many`],
140//!   [`throughput::hash_counter_range`], [`throughput::hash_chains_32_trunc16`],
141//!   [`Hasher::update`](convenience::Hasher::update) and
142//!   [`Hasher::finalize`](convenience::Hasher::finalize), and [`OutputReader`].
143//!   [`throughput::hash_chains_varlen_32_trunc16`] uses stack storage when at
144//!   most 128 chains have nonzero step counts, and allocates a call-local
145//!   `Vec<usize>` (freed on return) when more than 128 chains have nonzero
146//!   steps.
147//!   `Hasher::update_reader` uses a 64 KiB stack buffer for the first read
148//!   (even on immediate EOF), and promotes to a 1 MiB heap buffer once
149//!   65,536 bytes or more are read before EOF, freed when it returns.
150//!   `throughput::hash_each` keeps reusable per-thread `Vec` storage for
151//!   messages of 2 to 15 chunks (16 bytes per message and 32 bytes per chunk
152//!   of payload, plus `Vec` capacity): its first such collection and a larger
153//!   one grow that storage, and a repeated collection on a live thread
154//!   allocates nothing; during thread-local teardown after that storage is
155//!   destroyed, a collection with multi-chunk items falls back to call-local
156//!   `Vec`s.
157//! - **Grouped incremental calls** use bounded stack tables and tree buffers.
158//!   `throughput::update_each` allocates and frees nothing beyond the one-time
159//!   per-thread SME2 flat-walk scratch noted above if a fresh thread hashes a
160//!   whole 32 KiB+ piece on a 512-bit SME2 CPU.
161//! - **Once per process**: the startup self-test uses stack buffers on the
162//!   calling thread while it runs (it does not touch the thread-local SME2
163//!   flat-walk scratch, which is initialized on a thread's first post-init
164//!   whole 32 KiB+ walk — or when `blake3-servil`'s `initialize_multithreaded`
165//!   prepares the calling thread, even with `Some(1)`, or starts the SME2
166//!   worker — on a 512-bit SME2 CPU).
167//! - **Nothing is wiped**: this crate does not clear what it held from
168//!   memory, and offers no call that does. A key, the message bytes a
169//!   [`Hasher`] holds and the chaining values made from them stay in the
170//!   value, in the copies the kernels leave on the stack, and in the
171//!   storage a thread keeps (`hash_each`'s, above; on CPUs with SME2,
172//!   a 64 KiB block for the chaining values of the inputs the thread
173//!   hashes, keyed ones included), until something else overwrites
174//!   them. Official BLAKE3 offers `Zeroize` for its types.
175//!
176//! # Panics
177//!
178//! A broken precondition of a call panics on the calling thread, and
179//! unwinds as usual.
180//!
181//! # Startup self-test
182//!
183//! **Every program calls [`initialize`] once, before hashing**: any call
184//! that loads the detected platform (including [`convenience::hash`],
185//! [`Hasher::new`](convenience::Hasher::new), `Mode::DeriveKey` context
186//! hashing, and hashing methods on [`TreeHasher`](throughput::TreeHasher))
187//! panics before `initialize` completes, in every build, saying so. Pure
188//! constructors and `const` coordinate helpers that need no runtime platform
189//! (such as [`TreeHasher::new`](throughput::TreeHasher::new) for `Plain`,
190//! `Keyed`, or `DeriveKeyWith`, an empty `parent_cvs` call, and
191//! [`throughput::left_len`]) do not load the platform. The check costs
192//! nothing: it is part of the platform load made when selecting kernels.
193//!
194//! `initialize` runs a minimal "outside-the-box" self-test before the process
195//! first hashes, well under a millisecond: one unified six-case chained pass
196//! (~5.5 KiB total input, shared across x86-64 and AArch64) exercises the
197//! scalar ALU, `.rodata` IV, active SIMD vector unit (NEON+SHA-3 / SSE4.1 /
198//! AVX2 / AVX-512), and on SME2 hosts the 512-bit streaming matrix unit plus
199//! live `rdsvl` check, comparing each folded result with reference values from
200//! official BLAKE3 1.8.7 (and checking compiled x86-64 `LZCNT`/`BMI1` features
201//! on the host CPU). Individual unrolled static assembly variants are proved by
202//! Z3 and verified by unit tests rather than exercised on every process start.
203//! A mismatch stops the process, which no
204//! caller can catch: it attempts a best-effort diagnostic directly to file
205//! descriptor 2 (bypassing Rust's stderr lock, arming a best-effort `alarm(1)`
206//! watchdog around `poll(0)` and `write`, skipping already-full or
207//! already-closed pipes, and disarming `alarm(0)` before aborting) and calls
208//! `std::process::abort` when control returns. Arming and disarming `alarm`
209//! takes over (and clears) any pre-existing process real-time alarm even when
210//! the write to fd 2 is skipped. Other threads that call `initialize` meanwhile wait
211//! for it (parked via `std::sync::Once`; programs that `fork` should finish
212//! `initialize` before forking).
213//!
214//! # Build requirements
215//!
216//! This crate requires `std` (it has no `std` Cargo feature and no `no_std`
217//! mode; callers upgrading from `0.11.0` should drop `features = ["std"]` or
218//! `blake3-servil-core/std`, and `default-features = false` does not opt out
219//! of `std`). It runs on 64-bit little-endian x86-64 Linux and AArch64
220//! Linux/macOS. All kernels are assembled directly by `rustc` via
221//! `core::arch::global_asm!` (no external C compiler or `cc` build dependency
222//! is required for the Rust libraries). This crate runs its assembly or not at
223//! all: for `no_std`, portable Rust, or other targets, use official BLAKE3.
224//!
225//! [BLAKE3]: https://blake3.io
226//! [`Read`]: https://doc.rust-lang.org/std/io/trait.Read.html
227//! [`Write`]: https://doc.rust-lang.org/std/io/trait.Write.html
228//! [`Seek`]: https://doc.rust-lang.org/std/io/trait.Seek.html
229
230#[cfg(test)]
231mod lifecycle_counts;
232#[cfg(test)]
233mod test;
234#[cfg(test)]
235mod test_support;
236
237mod asm;
238mod block;
239pub mod convenience;
240mod ct;
241mod each;
242pub mod throughput;
243
244mod platform;
245
246// Platform-specific implementations of the compression function, gated on
247// `target_arch` (build.rs restricts supported targets to x86-64 Linux and
248// AArch64 Linux/macOS).
249#[cfg(target_arch = "x86_64")]
250#[path = "ffi_avx2.rs"]
251mod avx2;
252#[cfg(target_arch = "x86_64")]
253#[path = "ffi_avx512.rs"]
254mod avx512;
255#[cfg(target_arch = "x86_64")]
256#[path = "ffi_avx512_32.rs"]
257mod avx512_32;
258#[cfg(target_arch = "x86_64")]
259#[path = "ffi_chunk_root.rs"]
260mod chunk_root;
261mod ffi_chain;
262mod ffi_counter;
263#[cfg(target_arch = "x86_64")]
264mod ffi_output;
265#[cfg(target_arch = "aarch64")]
266#[path = "ffi_output_aarch64.rs"]
267mod ffi_output;
268mod ffi_packed;
269#[cfg(target_arch = "aarch64")]
270#[path = "ffi_neon_hybrid.rs"]
271mod neon_hybrid;
272#[cfg(target_arch = "aarch64")]
273#[path = "ffi_sme2.rs"]
274mod sme2;
275// Whole chunks and a partial one in one pass, on x86-64 (generated by
276// tools/gen_x86.py, built with the SSE4.1 and AVX2 assembly).
277#[cfg(target_arch = "x86_64")]
278mod ffi_partial;
279#[cfg(target_arch = "x86_64")]
280#[path = "ffi_sse41.rs"]
281mod sse41;
282
283mod io;
284mod many;
285mod output_common;
286#[cfg(target_arch = "x86_64")]
287mod pair;
288mod self_test;
289mod stack_vec;
290mod tree;
291
292/// A kind of kernel or path a call ran, for the tests that check which
293/// path a call took. Each build notes the kinds it has.
294#[derive(Clone, Copy)]
295#[allow(dead_code)]
296pub(crate) enum Ran {
297    /// The call wanted SME2 and another thread held the turn.
298    TurnTaken = 2,
299    /// A batch of one-block messages ran on the kernels' table a run at a
300    /// time (many::hash_many_on's first path).
301    BlockRun = 16,
302    /// A batch's messages of 2 to 15 chunks ran across messages
303    /// (`many::hash_across`). A batch with a serial tail records both `Across`
304    /// and `MessageAlone`.
305    Across = 32,
306    /// A batch's messages ran one at a time (many::hash_long_or_single).
307    MessageAlone = 64,
308    /// A batch of messages of up to a chunk, two or more, ran on the
309    /// kernels' table a run at a time (many::hash_many_on's short path).
310    ShortRun = 128,
311    /// Whole chunks, parents, or x86-64 multi-block batches were hashed on a
312    /// wider kernel than their count, the spare lanes a copy of the last
313    /// (rounded_lanes / round_x86_blocks).
314    RoundedUp = 256,
315    /// A table's one-block inputs were copied into one buffer for SME2's
316    /// parent kernel (sme2::hash_many): a copy of the input that blocks
317    /// handed over as the one buffer they lie in do not take
318    /// (sme2::hash_block_run).
319    Gathered = 512,
320}
321
322#[cfg(test)]
323std::thread_local! {
324    /// The kinds this thread's calls ran since the test last cleared it.
325    pub(crate) static RAN: core::cell::Cell<u32> = const { core::cell::Cell::new(0) };
326    /// The lanes the rounded-up hash_many calls ran at since the test last
327    /// cleared it, as a mask of widths (4 | 8 = 12: both).
328    pub(crate) static ROUNDED_WIDTH: core::cell::Cell<usize> = const { core::cell::Cell::new(0) };
329    /// `(blocks, inputs.len())` recorded at `Platform::hash_many` and
330    /// `pair::hash_many_blocks`, for verifying actual kernel dispatch widths.
331    pub(crate) static KERNEL_HASH_MANY_CALLS: core::cell::RefCell<std::vec::Vec<(usize, usize)>> = const { core::cell::RefCell::new(std::vec::Vec::new()) };
332}
333
334#[cfg(test)]
335#[inline(always)]
336pub(crate) fn record_hash_many_call(blocks: usize, count: usize) {
337    let _ = KERNEL_HASH_MANY_CALLS.try_with(|v| v.borrow_mut().push((blocks, count)));
338}
339
340/// Note that `kind` happened: in the tests' record, and nothing in any
341/// other build (some of which have no kernel to note).
342#[inline(always)]
343#[allow(dead_code)]
344pub(crate) fn ran(kind: Ran) {
345    #[cfg(test)]
346    let _ = RAN.try_with(|r| r.set(r.get() | kind as u32));
347    let _ = kind;
348}
349
350/// The work the tests count, for a mutant that only costs work (BLAKE3
351/// #219): an exact count on the calling thread, the same on every machine,
352/// where the digests are the same either way.
353#[derive(Clone, Copy)]
354#[allow(dead_code)]
355pub(crate) enum Counted {
356    /// A round of hash_each_on's shared lanes: one hash_many call over the
357    /// k-th chunk of every message that has one.
358    EachRound = 0,
359    /// One root output block computed alone (Output::root_output_block):
360    /// OutputReader::fill's tails, where its whole blocks go to xof_many.
361    RootBlock = 1,
362    /// One group of short collection items hashed together by blocks.
363    ByBlocksCall = 2,
364    /// One x86-64 AVX-512/AVX2 finalize_each output dispatch turn (four or
365    /// more eligible counter-zero hashers).
366    OutputGroupTurn = 3,
367    /// One pass of update_each's held groups hashed together.
368    HeldPass = 4,
369    /// One update of a block or less staged as a padded block
370    /// (Hasher::update's path for an empty stage).
371    PaddedFirstBlock = 5,
372    /// One copy of bytes into a Hasher's stage (Hasher::stage): what an
373    /// update's whole groups skip.
374    Staged = 6,
375    /// One whole subtree cut into a row for the Hasher's stack.
376    Row = 7,
377    /// One `finalize` that hashed the staged bytes apart and read the
378    /// stack, the core not copied.
379    TailApart = 8,
380    /// One whole subtree a Hasher's update hashed on SME2's flat walk, to
381    /// its one chaining value (the Hasher's hook `subtree_cv`).
382    Flat = 9,
383    /// One multi-lane SIMD `Platform::hash_many` dispatch call (#497).
384    HashManyCall = 10,
385    /// One single-block compression dispatch (`Platform::compress_in_place`, #219).
386    CompressInPlace = 11,
387    /// One multi-block compression dispatch (`Platform::compress_blocks`, #219).
388    CompressBlocks = 12,
389}
390
391#[cfg(test)]
392std::thread_local! {
393    /// This thread's counts since the test last cleared them, by Counted.
394    pub(crate) static COUNTED: [core::cell::Cell<u64>; 13] = const { [const { core::cell::Cell::new(0) }; 13] };
395}
396
397/// Count one of `what`: in the tests' record, and nothing in any other
398/// build.
399#[inline(always)]
400#[allow(dead_code)]
401pub(crate) fn counted(what: Counted) {
402    #[cfg(test)]
403    let _ = COUNTED.try_with(|c| c[what as usize].set(c[what as usize].get() + 1));
404    let _ = what;
405}
406
407#[cfg(test)]
408std::thread_local! {
409    /// The assembly entry points this thread's calls ran since the test
410    /// last cleared it, by address.
411    pub(crate) static RAN_ENTRIES: core::cell::RefCell<std::collections::BTreeSet<usize>> = const { core::cell::RefCell::new(std::collections::BTreeSet::new()) };
412    /// Number of assembly entry-point invocations recorded by `ran_kernel`
413    /// since the test last reset it.
414    pub(crate) static RAN_KERNEL_CALLS: core::cell::Cell<usize> = const { core::cell::Cell::new(0) };
415}
416
417/// Note that the assembly entry point at `entry` ran (in the tests'
418/// record; nothing in any other build).
419#[inline(always)]
420#[allow(dead_code)]
421pub(crate) fn ran_kernel(entry: *const ()) {
422    #[cfg(test)]
423    {
424        let _ = RAN_ENTRIES.try_with(|r| r.borrow_mut().insert(entry as usize));
425        let _ = RAN_KERNEL_CALLS.try_with(|c| c.set(c.get() + 1));
426    }
427    let _ = entry;
428}
429
430use core::cmp;
431use core::fmt;
432use platform::{MAX_SIMD_DEGREE, Platform};
433use stack_vec::StackVec;
434
435/// This build's version: the crate's version, and for any build but a
436/// release's own commit, the commit built and, from a dirty tree, the Git
437/// tree id of its working tree, e.g. `0.8.0+dev.<commit>.dirty.<tree>`.
438/// The C library's `b3_version()` prints it (the standalone
439/// `servil-software-factory/b3sum` tool prints its own build version).
440pub use blake3_servil_version::BUILD_VERSION;
441
442/// The number of bytes in a [`struct@Hash`], 32.
443pub const OUT_LEN: usize = 32;
444
445/// The number of bytes in a key, 32.
446pub const KEY_LEN: usize = 32;
447
448/// The number of bytes in a block, 64.
449///
450/// You don't usually need to think about this number. One case where it matters is calling
451/// [`OutputReader::fill`] in a loop, where using a `buf` argument that's a multiple of `BLOCK_LEN`
452/// avoids repeating work.
453pub const BLOCK_LEN: usize = 64;
454
455/// The number of bytes in a chunk, 1024.
456///
457/// You don't usually need to think about this number, but it often comes up in benchmarks, because
458/// the maximum degree of parallelism used by the implementation equals the number of chunks.
459pub const CHUNK_LEN: usize = 1024;
460
461pub(crate) const MAX_DEPTH: usize = 54; // 2^54 * CHUNK_LEN = 2^64
462
463// A chunk's CV is words while its blocks compress (the kernels' form); the
464// hash_many interface hashes input bytes and parent nodes alike, so its
465// output CVs are bytes.
466pub(crate) type CVWords = [u32; 8];
467pub(crate) type CVBytes = [u8; 32]; // little-endian
468
469pub(crate) const IV: &CVWords = &[0x6A09E667, 0xBB67AE85, 0x3C6EF372, 0xA54FF53A, 0x510E527F, 0x9B05688C, 0x1F83D9AB, 0x5BE0CD19];
470
471// These are the internal domain-separation flags in the low bits (0 through 6)
472// of the block flags word in the compression function.
473pub(crate) const CHUNK_START: u8 = 1 << 0;
474pub(crate) const CHUNK_END: u8 = 1 << 1;
475const PARENT: u8 = 1 << 2;
476pub(crate) const ROOT: u8 = 1 << 3;
477pub(crate) const KEYED_HASH: u8 = 1 << 4;
478const DERIVE_KEY_CONTEXT: u8 = 1 << 5;
479pub(crate) const DERIVE_KEY_MATERIAL: u8 = 1 << 6;
480
481/// An output of the default size, 32 bytes, which provides constant-time
482/// equality checking.
483///
484/// `Hash` implements [`From`] and [`Into`] for `[u8; 32]`, and it provides
485/// [`from_bytes`] and [`as_bytes`] for explicit conversions between itself and
486/// `[u8; 32]`. However, byte arrays and slices don't provide constant-time
487/// equality checking, which is often a security requirement in software that
488/// handles private data. `Hash` doesn't implement [`Deref`] or [`AsRef`], to
489/// avoid situations where a type conversion happens implicitly and the
490/// constant-time property is accidentally lost.
491///
492/// `Hash` provides the [`to_hex`] and [`from_hex`] methods for converting to
493/// and from hexadecimal. It also implements [`Display`] and [`FromStr`].
494///
495/// [`From`]: https://doc.rust-lang.org/std/convert/trait.From.html
496/// [`Into`]: https://doc.rust-lang.org/std/convert/trait.Into.html
497/// [`as_bytes`]: #method.as_bytes
498/// [`from_bytes`]: #method.from_bytes
499/// [`Deref`]: https://doc.rust-lang.org/stable/std/ops/trait.Deref.html
500/// [`AsRef`]: https://doc.rust-lang.org/std/convert/trait.AsRef.html
501/// [`to_hex`]: #method.to_hex
502/// [`from_hex`]: #method.from_hex
503/// [`Display`]: https://doc.rust-lang.org/std/fmt/trait.Display.html
504/// [`FromStr`]: https://doc.rust-lang.org/std/str/trait.FromStr.html
505///
506/// # Trait implementations
507///
508/// - `Clone` reproduces the digest byte for byte.
509/// - `Copy` leaves the same digest available at both places.
510/// - `Debug` includes the full digest in hexadecimal, even for a derived
511///   key.
512/// - `Display` prints all 32 bytes in lowercase hexadecimal, even for a
513///   derived key.
514/// - `Eq` treats digests with identical bytes as equal.
515/// - `From` converts between the digest and its 32-byte array without
516///   changing the bytes; array equality is not constant-time.
517/// - `FromStr` decodes exactly 64 hexadecimal digits, accepting either
518///   case.
519/// - `Hash` feeds the length 32 and then the 32 digest bytes to whatever
520///   `core::hash::Hasher` the caller supplies, whose running time may
521///   depend on those bytes.
522/// - `PartialEq` compares digests, arrays and slices in constant time for
523///   32-byte operands; a different length is unequal.
524#[derive(Clone, Copy, Eq)]
525#[repr(transparent)]
526pub struct Hash([u8; OUT_LEN]);
527
528/// The 64 lowercase hexadecimal characters of a [`Hash`](struct@Hash), held
529/// inline with no heap allocation.
530///
531/// Dereferences to `&str` and implements `Display`, `AsRef<str>`, `AsRef<[u8]>`,
532/// and `PartialEq<&str>` / `PartialEq<str>`. Equality on `HexHash` is not
533/// constant-time; compare [`Hash`](struct@Hash) values directly for secret tags or keys.
534///
535/// # Trait implementations
536///
537/// - `AsRef` borrows the 64 hexadecimal characters as `&str` or `&[u8]`.
538/// - `Borrow` lends the 64 hexadecimal characters as `&str`, with the `str`'s own hash, equality and order, so a map keyed by `HexHash` finds a key by its `&str`.
539/// - `Clone` copies the 64 ASCII bytes.
540/// - `Copy` leaves the same 64 ASCII bytes available at both places.
541/// - `Debug` formats the 64 hexadecimal characters as a quoted Rust string.
542/// - `Deref` borrows the 64 hexadecimal characters as `&str`.
543/// - `Display` formats the 64 lowercase hexadecimal characters as their `str` does, width and precision included.
544/// - `Eq` reflects `PartialEq` over the 64 ASCII bytes (not constant-time).
545/// - `Hash` feeds the hasher what the `str` of the 64 characters feeds it.
546/// - `Ord` compares the 64 ASCII bytes lexicographically (not constant-time).
547/// - `PartialEq` compares the 64 ASCII bytes against another `HexHash`, `str`, or `&str` (not constant-time).
548/// - `PartialOrd` compares the 64 ASCII bytes lexicographically (not constant-time).
549#[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
550pub struct HexHash([u8; 2 * OUT_LEN]);
551
552impl HexHash {
553    /// View the 64 hexadecimal characters as a `&str`.
554    #[inline]
555    pub fn as_str(&self) -> &str {
556        // Sound: `Hash::to_hex` writes only ASCII '0'..='9' and 'a'..='f'.
557        unsafe { core::str::from_utf8_unchecked(&self.0) }
558    }
559
560    /// View the 64 ASCII hexadecimal bytes.
561    #[inline]
562    pub fn as_bytes(&self) -> &[u8; 2 * OUT_LEN] {
563        &self.0
564    }
565}
566
567impl core::ops::Deref for HexHash {
568    type Target = str;
569    #[inline]
570    fn deref(&self) -> &str {
571        self.as_str()
572    }
573}
574
575impl AsRef<str> for HexHash {
576    #[inline]
577    fn as_ref(&self) -> &str {
578        self.as_str()
579    }
580}
581
582impl AsRef<[u8]> for HexHash {
583    #[inline]
584    fn as_ref(&self) -> &[u8] {
585        &self.0
586    }
587}
588
589impl core::borrow::Borrow<str> for HexHash {
590    #[inline]
591    fn borrow(&self) -> &str {
592        self.as_str()
593    }
594}
595
596// As the str hashes, which `Borrow<str>` requires: a derived hash of the
597// byte array feeds the hasher other bytes, and a lookup by `&str` misses.
598impl core::hash::Hash for HexHash {
599    #[inline]
600    fn hash<H: core::hash::Hasher>(&self, state: &mut H) {
601        self.as_str().hash(state)
602    }
603}
604
605impl fmt::Display for HexHash {
606    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
607        fmt::Display::fmt(self.as_str(), f)
608    }
609}
610
611impl fmt::Debug for HexHash {
612    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
613        fmt::Debug::fmt(self.as_str(), f)
614    }
615}
616
617impl PartialEq<str> for HexHash {
618    #[inline]
619    fn eq(&self, other: &str) -> bool {
620        self.as_str() == other
621    }
622}
623
624impl PartialEq<&str> for HexHash {
625    #[inline]
626    fn eq(&self, other: &&str) -> bool {
627        self.as_str() == *other
628    }
629}
630
631impl Hash {
632    /// The raw bytes of the `Hash`. Note that byte arrays don't provide
633    /// constant-time equality checking, so if you need to compare hashes,
634    /// prefer the `Hash` type.
635    #[inline]
636    pub const fn as_bytes(&self) -> &[u8; OUT_LEN] {
637        &self.0
638    }
639
640    /// Create a `Hash` from its raw bytes representation.
641    pub const fn from_bytes(bytes: [u8; OUT_LEN]) -> Self {
642        Self(bytes)
643    }
644
645    /// The raw bytes of the `Hash`, as a slice. Useful for serialization. Note that byte arrays
646    /// don't provide constant-time equality checking, so if you need to compare hashes, prefer
647    /// the `Hash` type.
648    #[inline]
649    pub const fn as_slice(&self) -> &[u8] {
650        self.0.as_slice()
651    }
652
653    /// Create a `Hash` from its raw bytes representation as a slice.
654    ///
655    /// Returns an error if the slice is not exactly 32 bytes long.
656    pub fn from_slice(bytes: &[u8]) -> Result<Self, core::array::TryFromSliceError> {
657        Ok(Self::from_bytes(bytes.try_into()?))
658    }
659
660    /// Encode a `Hash` in lowercase hexadecimal.
661    ///
662    /// Each character is computed from its four bits by arithmetic: no
663    /// table is indexed by the hash and no branch is taken on it, so the
664    /// call's time and memory accesses are the same for every hash (a
665    /// hash may be a secret: a keyed hash's tag, a derived key).
666    ///
667    /// The returned [`HexHash`] holds the 64 ASCII hexadecimal bytes inline
668    /// with no heap allocation and dereferences to `&str`. Note that
669    /// [`HexHash`] doesn't provide constant-time equality checking, so if you
670    /// need to compare hashes, prefer the [`Hash`](struct@Hash) type.
671    pub fn to_hex(&self) -> HexHash {
672        // 0..=9 are '0' + n; 10..=15 are 'a' + n - 10, which is '0' + n + 39:
673        // (n + 6) >> 4 is 1 exactly for those.
674        let nibble = |n: u8| b'0' + n + ((n + 6) >> 4) * 39;
675        let mut bytes = [0u8; 2 * OUT_LEN];
676        for (i, &b) in self.0.iter().enumerate() {
677            bytes[2 * i] = nibble(b >> 4);
678            bytes[2 * i + 1] = nibble(b & 0xf);
679        }
680        HexHash(bytes)
681    }
682
683    /// Decode a `Hash` from hexadecimal. Both uppercase and lowercase ASCII
684    /// bytes are supported.
685    ///
686    /// Any byte outside the ranges `'0'...'9'`, `'a'...'f'`, and `'A'...'F'`
687    /// results in an error. An input length other than 64 also results in an
688    /// error.
689    ///
690    /// For 64 hexadecimal characters, the call's time and memory accesses
691    /// are the same whatever they are: each is decoded by arithmetic, all
692    /// 64 always. An input that is refused is then searched for the
693    /// character the error names.
694    ///
695    /// Note that `Hash` also implements `FromStr`, so `Hash::from_hex("...")`
696    /// is equivalent to `"...".parse()`.
697    pub fn from_hex(hex: impl AsRef<[u8]>) -> Result<Self, HexError> {
698        /// (the character's value, 0xff where it is a hex character and 0
699        /// where not), with no branch: a difference below its range's size
700        /// leaves the subtraction negative, whose sign fills the mask.
701        fn hex_val(byte: u8) -> (u8, u8) {
702            let digit = byte.wrapping_sub(b'0');
703            let letter = (byte | 0x20).wrapping_sub(b'a');
704            let is_digit = ((digit as i16 - 10) >> 8) as u8;
705            let is_letter = ((letter as i16 - 6) >> 8) as u8;
706            ((digit & is_digit) | (letter.wrapping_add(10) & is_letter), is_digit | is_letter)
707        }
708        let hex_bytes: &[u8] = hex.as_ref();
709        if hex_bytes.len() != OUT_LEN * 2 {
710            return Err(HexError(HexErrorInner::InvalidLen(hex_bytes.len())));
711        }
712        let mut hash_bytes: [u8; OUT_LEN] = [0; OUT_LEN];
713        let mut all = 0xff;
714        for i in 0..OUT_LEN {
715            let (high, high_is) = hex_val(hex_bytes[2 * i]);
716            let (low, low_is) = hex_val(hex_bytes[2 * i + 1]);
717            hash_bytes[i] = high << 4 | low;
718            all &= high_is & low_is;
719        }
720        if all != 0xff {
721            // Refused: the first character that is none, for the error.
722            let byte = *hex_bytes.iter().find(|&&b| hex_val(b).1 == 0).expect("a refused input holds a character that is no hex character");
723            return Err(HexError(HexErrorInner::InvalidByte(byte)));
724        }
725        Ok(Hash::from(hash_bytes))
726    }
727}
728
729impl From<[u8; OUT_LEN]> for Hash {
730    #[inline]
731    fn from(bytes: [u8; OUT_LEN]) -> Self {
732        Self::from_bytes(bytes)
733    }
734}
735
736impl From<Hash> for [u8; OUT_LEN] {
737    #[inline]
738    fn from(hash: Hash) -> Self {
739        hash.0
740    }
741}
742
743impl core::str::FromStr for Hash {
744    type Err = HexError;
745
746    fn from_str(s: &str) -> Result<Self, Self::Err> {
747        Hash::from_hex(s)
748    }
749}
750
751/// This implementation is constant-time (branchless integer assembly; on Arm
752/// it leaves `PSTATE.DIT` as the calling thread has it, matching hashing).
753impl PartialEq for Hash {
754    #[inline]
755    fn eq(&self, other: &Hash) -> bool {
756        ct::eq_32(&self.0, &other.0)
757    }
758}
759
760impl core::hash::Hash for Hash {
761    #[inline]
762    fn hash<H: core::hash::Hasher>(&self, state: &mut H) {
763        self.0.hash(state);
764    }
765}
766
767/// This implementation is constant-time (branchless integer assembly; on Arm
768/// it leaves `PSTATE.DIT` as the calling thread has it, matching hashing).
769impl PartialEq<[u8; OUT_LEN]> for Hash {
770    #[inline]
771    fn eq(&self, other: &[u8; OUT_LEN]) -> bool {
772        ct::eq_32(&self.0, other)
773    }
774}
775
776/// This implementation is constant-time if the target is 32 bytes long
777/// (branchless integer assembly; on Arm it leaves `PSTATE.DIT` as the calling
778/// thread has it, matching hashing).
779impl PartialEq<[u8]> for Hash {
780    #[inline]
781    fn eq(&self, other: &[u8]) -> bool {
782        ct::eq_slice_32(&self.0, other)
783    }
784}
785
786impl fmt::Display for Hash {
787    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
788        // Formatting field as `&str` to reduce code size since the `Debug`
789        // dynamic dispatch table for `&str` is likely needed elsewhere already,
790        // but that for `HexHash` is not.
791        let hex = self.to_hex();
792        let hex: &str = hex.as_str();
793
794        f.write_str(hex)
795    }
796}
797
798impl fmt::Debug for Hash {
799    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
800        // Formatting field as `&str` to reduce code size since the `Debug`
801        // dynamic dispatch table for `&str` is likely needed elsewhere already,
802        // but that for `HexHash` is not.
803        let hex = self.to_hex();
804        let hex: &str = hex.as_str();
805
806        f.debug_tuple("Hash").field(&hex).finish()
807    }
808}
809
810/// The error type for [`Hash::from_hex`].
811///
812/// The `.to_string()` representation of this error currently distinguishes between bad length
813/// errors and bad character errors. This is to help with logging and debugging, but it isn't a
814/// stable API detail, and it may change at any time.
815///
816/// # Trait implementations
817///
818/// - `Clone` copies the reason decoding failed.
819/// - `Debug` shows the error variant and its invalid byte or length.
820/// - `Display` describes the invalid byte or length without promising
821///   stable wording.
822/// - `Error` lets a caller report the decoding failure as a standard error.
823#[derive(Clone, Debug)]
824pub struct HexError(HexErrorInner);
825
826#[derive(Clone, Debug)]
827enum HexErrorInner {
828    InvalidByte(u8),
829    InvalidLen(usize),
830}
831
832impl fmt::Display for HexError {
833    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
834        match self.0 {
835            HexErrorInner::InvalidByte(byte) => {
836                if byte < 128 {
837                    write!(f, "invalid hex character: {:?}", byte as char)
838                } else {
839                    write!(f, "invalid hex character: 0x{:x}", byte)
840                }
841            }
842            HexErrorInner::InvalidLen(len) => {
843                write!(f, "expected 64 hex bytes, received {}", len)
844            }
845        }
846    }
847}
848
849impl std::error::Error for HexError {}
850
851/// Whether `hash_many` increments the chunk counter across inputs (`Yes` for
852/// chunks, `No` for parent nodes and root blocks).
853#[derive(Clone, Copy)]
854pub(crate) enum IncrementCounter {
855    Yes,
856    No,
857}
858
859impl IncrementCounter {
860    #[inline]
861    fn yes(&self) -> bool {
862        match self {
863            IncrementCounter::Yes => true,
864            IncrementCounter::No => false,
865        }
866    }
867}
868
869/// The widths the platform's many-lane kernels run at, in one pass each,
870/// rising: SSE4.1 four lanes; AVX2 eight (and four); AVX-512 sixteen (and
871/// eight, four), and thirty-two where the 32-input kernel runs
872/// (wide_avx512, Zen 5 on Linux). Below the smallest, one and two lanes
873/// have passes of their own as cheap as one.
874/// `platform.hash_many` over `inputs`, on `rounded_lanes` where a wider
875/// kernel takes the count in one pass: the spare lanes hash a copy of the
876/// last input, into scratch. Past the widest kernel, the whole groups of
877/// its width first, then the rest rounded.
878///
879/// On x86-64, every power of two from 4 through the platform's widest kernel
880/// is a native lane width (so powers of two never pad and larger powers of two
881/// divide evenly by the widest kernel). Taking `platform.hash_many` directly on
882/// powers of two keeps the 1 KiB scratch buffer and extra dispatch copies out
883/// of hot callers' stack frames and cold instruction cache lines (`#376`).
884/// Non-x86 architectures have no rounding tables and call `platform.hash_many`
885/// directly with no extra branch.
886#[inline]
887#[allow(clippy::too_many_arguments)]
888pub(crate) fn hash_many_rounded<const N: usize>(
889    platform: Platform,
890    inputs: &[&[u8; N]],
891    key: &CVWords,
892    counter: u64,
893    increment_counter: IncrementCounter,
894    flags: u8,
895    flags_start: u8,
896    flags_end: u8,
897    out: &mut [u8],
898) {
899    #[cfg(target_arch = "x86_64")]
900    ffi_partial::hash_many_rounded(platform, inputs, key, counter, increment_counter, flags, flags_start, flags_end, out);
901    #[cfg(not(target_arch = "x86_64"))]
902    platform.hash_many(inputs, key, counter, increment_counter, flags, flags_start, flags_end, out);
903}
904
905#[cfg(all(test, target_arch = "x86_64"))]
906use ffi_partial::{lane_widths, rounded_lanes};
907
908/// Intentional low-byte extraction for test byte patterns (wrapping is
909/// the point, unlike length/count narrowing which uses `u8::try_from`).
910#[cfg(test)]
911#[inline(always)]
912pub(crate) const fn low_byte(x: usize) -> u8 {
913    x.to_le_bytes()[0]
914}
915
916/// Intentional low-byte extraction from `platform::DETECTED`'s packed `u16`.
917#[inline(always)]
918pub(crate) const fn low_byte_u16(x: u16) -> u8 {
919    x.to_le_bytes()[0]
920}
921
922// Use SIMD parallelism to hash up to MAX_SIMD_DEGREE chunks at the same time
923// on a single thread. Write out the chunk chaining values and return the
924// number of chunks hashed. These chunks are never the root and never empty;
925// those cases use a different codepath.
926fn compress_chunks_parallel(input: &[u8], key: &CVWords, chunk_counter: u64, flags: u8, platform: Platform, out: &mut [u8]) -> usize {
927    assert!(!input.is_empty(), "empty chunks below the root");
928    assert!(input.len() <= MAX_SIMD_DEGREE * CHUNK_LEN, "compress_chunks_parallel exceeds MAX_SIMD_DEGREE chunks");
929
930    let mut chunks_exact = input.chunks_exact(CHUNK_LEN);
931    let mut chunks_array = StackVec::<&[u8; CHUNK_LEN], MAX_SIMD_DEGREE>::new();
932    for chunk in &mut chunks_exact {
933        chunks_array.push(chunk.try_into().unwrap());
934    }
935    // A whole chunk and a partial one, on AVX2 or AVX-512: their first
936    // blocks side by side (pair.rs).
937    #[cfg(target_arch = "x86_64")]
938    if pair::takes(platform, input.len()) {
939        out[..2 * OUT_LEN].copy_from_slice(&pair::parent(input, key, chunk_counter, flags, platform));
940        return 2;
941    }
942    // Whole chunks that leave a lane spare, and a partial one: one pass,
943    // the partial chunk in the spare lane.
944    #[cfg(target_arch = "x86_64")]
945    if ffi_partial::try_hash_chunks_with_partial(platform, &chunks_array, chunks_exact.remainder(), key, chunk_counter, flags, out) {
946        return chunks_array.len() + 1;
947    }
948    // Whole chunks and a partial one, on the NEON hybrids: where a q kernel
949    // covers the count, the partial chunk runs on the scalar units beside
950    // the whole chunks rather than after them.
951    #[cfg(target_arch = "aarch64")]
952    if !chunks_exact.remainder().is_empty() && neon_hybrid::partial_pays(chunks_array.len(), chunks_exact.remainder().len()) && neon_hybrid::sha3_detected() {
953        // Sound: `partial_pays` verified the chunk count and `sha3_detected()` verified SHA-3 support; `out` holds enough room for `chunks_array.len() + 1` CVs.
954        unsafe {
955            neon_hybrid::hash_chunks_with_partial(&chunks_array, chunks_exact.remainder(), key, chunk_counter, flags, CHUNK_START, CHUNK_END, out);
956        }
957        return chunks_array.len() + 1;
958    }
959    hash_many_rounded(platform, &chunks_array, key, chunk_counter, IncrementCounter::Yes, flags, CHUNK_START, CHUNK_END, out);
960
961    // Hash the remaining partial chunk, if there is one. Note that the empty
962    // chunk (meaning the empty message) is a different codepath.
963    let chunks_so_far = chunks_array.len();
964    if !chunks_exact.remainder().is_empty() {
965        let counter = chunk_counter + chunks_so_far as u64;
966        let mut chunk_state = ChunkState::new(key, counter, flags, platform);
967        chunk_state.update(chunks_exact.remainder());
968        *<&mut [u8; OUT_LEN]>::try_from(&mut out[chunks_so_far * OUT_LEN..][..OUT_LEN]).unwrap() = chunk_state.output().chaining_value();
969        chunks_so_far + 1
970    } else {
971        chunks_so_far
972    }
973}
974
975// Use SIMD parallelism to hash up to MAX_SIMD_DEGREE parents at the same time
976// on a single thread. Write out the parent chaining values and return the
977// number of parents hashed. (If there's an odd input chaining value left over,
978// return it as an additional output.) These parents are never the root and
979// never empty; those cases use a different codepath.
980pub(crate) fn compress_parents_parallel(child_chaining_values: &[u8], key: &CVWords, flags: u8, platform: Platform, out: &mut [u8]) -> usize {
981    assert_eq!(child_chaining_values.len() % OUT_LEN, 0, "chaining values are 32 bytes each");
982    let num_children = child_chaining_values.len() / OUT_LEN;
983    assert!((2..=2 * MAX_SIMD_DEGREE).contains(&num_children), "compress_parents_parallel expects 2..=2*MAX_SIMD_DEGREE children");
984
985    let (parent_blocks, remainder) = child_chaining_values.as_chunks::<BLOCK_LEN>();
986    let parents_so_far = parent_blocks.len();
987    let flags = flags | PARENT;
988    #[cfg(target_arch = "aarch64")]
989    let on_sme2 = matches!(platform, Platform::SME2);
990    #[cfg(not(target_arch = "aarch64"))]
991    let on_sme2 = false;
992    if on_sme2 {
993        // SME2's parent kernel reads a contiguous run of 64-byte parent blocks
994        // directly, without constructing a pointer table.
995        #[cfg(target_arch = "aarch64")]
996        // Sound: the platform is SME2 only where detection found SME2
997        // with 512-bit streaming vectors.
998        unsafe {
999            sme2::hash_block_run(parent_blocks.as_flattened(), key, flags, out)
1000        };
1001    } else {
1002        let mut parents_array = StackVec::<&[u8; BLOCK_LEN], MAX_SIMD_DEGREE>::new();
1003        for parent in parent_blocks {
1004            parents_array.push(parent);
1005        }
1006        hash_many_rounded(
1007            platform,
1008            &parents_array,
1009            key,
1010            0, // Parents always use counter 0.
1011            IncrementCounter::No,
1012            flags,
1013            0, // Parents have no start flags.
1014            0, // Parents have no end flags.
1015            out,
1016        );
1017    }
1018
1019    // If there's an odd child left over, it becomes an output.
1020    if !remainder.is_empty() {
1021        out[parents_so_far * OUT_LEN..][..OUT_LEN].copy_from_slice(remainder);
1022        parents_so_far + 1
1023    } else {
1024        parents_so_far
1025    }
1026}
1027
1028// Hash a subtree with the walk (src/tree.rs, `children`), returning its two
1029// child chaining values directly without flattening and splitting a 64-byte
1030// block. This function is not used on inputs of 1 chunk or less.
1031#[inline]
1032pub(crate) fn compress_subtree_to_parent_node(input: &[u8], ahead: usize, key: &CVWords, chunk_counter: u64, flags: u8, platform: Platform) -> [CVBytes; 2] {
1033    assert!(input.len() > CHUNK_LEN, "compress_subtree_wide requires more than one chunk");
1034    let kernels = tree::PlatformKernels { key, flags, platform };
1035    tree::root_children(&kernels, input, ahead, chunk_counter)
1036}
1037
1038// The root hash of a single-block input (`<= 64` bytes), in one kernel call
1039// without multi-block length arithmetic or 64-byte stack realignment; short
1040// inputs zero-fill `padded` lazily only on the `< 64` arm so exact 64-byte
1041// dynamic slices skip both 32-byte zeroing stores while preserving
1042// shrink-wrapped `TreeHasher::hash(&[u8])` codegen (#586, #589).
1043#[cfg(target_arch = "aarch64")]
1044#[inline]
1045pub(crate) fn hash_one_block_root(input: &[u8], key: &CVWords, flags: u8) -> Hash {
1046    assert!(input.len() <= BLOCK_LEN, "one block or less");
1047    let mut padded;
1048    let last: &[u8; BLOCK_LEN] = match input.try_into() {
1049        Ok(full) => full,
1050        Err(_) => {
1051            padded = [0u8; BLOCK_LEN];
1052            padded[..input.len()].copy_from_slice(input);
1053            &padded
1054        }
1055    };
1056    let mut out = [0u8; OUT_LEN];
1057    // Sound: `blocks == 1`, so `c1` selects `last` before loading and reads
1058    // only the 64-byte `last` block and `key`, writing 32 bytes to `out`.
1059    unsafe {
1060        neon_hybrid::hash_chunk(
1061            last.as_ptr(),
1062            1,
1063            last,
1064            u8::try_from(input.len()).expect("block <= 64"),
1065            key,
1066            0,
1067            flags,
1068            CHUNK_START,
1069            CHUNK_END | ROOT,
1070            &mut out,
1071        );
1072    }
1073    Hash(out)
1074}
1075
1076// The root hash of an input of one chunk or less, in one kernel call. The
1077// whole blocks are read in place, the final one too when it is full; a
1078// short final block (and the empty block for the empty input) is copied
1079// into a zero-padded stack buffer only on the short-tail arm (so exact
1080// 64/128/.../1024-byte dynamic slices avoid unnecessary zero-fill stores).
1081// Kept out of line so general cold callers (`convenience::hash` and
1082// `throughput::hash_multithreaded`) keep their small frames and I-cache
1083// footprint. The scalar kernel runs on every AArch64 core, so this path
1084// needs no platform check (#589).
1085#[cfg(target_arch = "aarch64")]
1086#[inline(never)]
1087fn hash_one_chunk_root(input: &[u8], key: &CVWords, flags: u8) -> Hash {
1088    assert!(input.len() <= CHUNK_LEN, "one chunk or less");
1089    let blocks = cmp::max(1, input.len().div_ceil(BLOCK_LEN));
1090    let whole = (blocks - 1) * BLOCK_LEN;
1091    let tail = &input[whole..];
1092    let mut padded;
1093    let last: &[u8; BLOCK_LEN] = match tail.try_into() {
1094        Ok(full) => full,
1095        Err(_) => {
1096            padded = [0u8; BLOCK_LEN];
1097            padded[..tail.len()].copy_from_slice(tail);
1098            &padded
1099        }
1100    };
1101    let mut out = [0u8; OUT_LEN];
1102    // Sound: `blocks` is in 1..=16 and `last` is 64 readable bytes; when
1103    // `blocks == 1`, `c1` selects `last` before loading and never reads
1104    // `input.as_ptr()`; when `blocks >= 2`, `input` holds `(blocks - 1) * BLOCK_LEN`
1105    // readable bytes before `tail`.
1106    unsafe {
1107        neon_hybrid::hash_chunk(
1108            input.as_ptr(),
1109            blocks,
1110            last,
1111            u8::try_from(tail.len()).expect("tail block <= 64"),
1112            key,
1113            0,
1114            flags,
1115            CHUNK_START,
1116            CHUNK_END | ROOT,
1117            &mut out,
1118        );
1119    }
1120    Hash(out)
1121}
1122
1123/// Run the startup self-test and detect the CPU: every program calls this
1124/// once before hashing (any call that loads the detected platform before
1125/// `initialize` completes panics). Under 0.2 ms, once per process
1126/// (see the crate's documentation); later calls return at once.
1127///
1128/// ```
1129/// blake3_servil_core::initialize();
1130/// let hash = blake3_servil_core::convenience::hash(b"foo");
1131/// # let mut hasher = blake3_servil_core::convenience::Hasher::new(blake3_servil_core::Mode::Plain, None);
1132/// # hasher.update(b"foo");
1133/// # assert_eq!(hash, hasher.finalize());
1134/// ```
1135pub fn initialize() {
1136    self_test::ensure();
1137}
1138
1139/// Scheduling and storage setup shared with `blake3-servil`'s workers.
1140/// Hashing goes through the checked calls on `throughput::TreeHasher`;
1141/// no raw kernels, keys, flags, or `Platform` values cross this boundary (#460).
1142///
1143/// Positive control (opaque turn still exists):
1144/// ```no_run
1145/// blake3_servil_core::initialize();
1146/// let turn = blake3_servil_core::thread_support::Sme2Turn::acquire();
1147/// let _ = (turn.is_sme2(), turn.simd_degree(), blake3_servil_core::thread_support::has_sme2());
1148/// ```
1149///
1150/// Retired platform/bypass items cannot be named from outside the crate:
1151/// ```compile_fail,E0432
1152/// use blake3_servil_core::thread_support::Platform;
1153/// ```
1154/// ```compile_fail,E0425
1155/// let _ = blake3_servil_core::thread_support::MAX_SIMD_DEGREE;
1156/// ```
1157/// ```compile_fail,E0425
1158/// let _ = blake3_servil_core::thread_support::slot_len(64);
1159/// ```
1160/// ```compile_fail,E0599
1161/// use blake3_servil_core::throughput::TreeHasher;
1162/// let _ = TreeHasher::hash_on;
1163/// ```
1164/// ```compile_fail,E0599
1165/// use blake3_servil_core::throughput::TreeHasher;
1166/// let _ = TreeHasher::hash_many_on;
1167/// ```
1168/// ```compile_fail,E0599
1169/// use blake3_servil_core::throughput::TreeHasher;
1170/// let _ = TreeHasher::subtree_cv_on;
1171/// ```
1172/// ```compile_fail,E0599
1173/// use blake3_servil_core::throughput::TreeHasher;
1174/// let _ = TreeHasher::subtree_halves_on;
1175/// ```
1176/// ```compile_fail,E0599
1177/// use blake3_servil_core::throughput::TreeHasher;
1178/// let _ = TreeHasher::last_cv_on;
1179/// ```
1180#[doc(hidden)]
1181pub mod thread_support {
1182    pub use crate::each::prepare_thread as prepare_collection_thread;
1183    pub use crate::many::assert_slots;
1184    pub use crate::platform::Sme2Turn;
1185    #[cfg(target_arch = "aarch64")]
1186    pub use crate::sme2::prepare_thread_scratch as prepare_sme2_scratch;
1187
1188    /// Whether this process's detected platform uses a shared SME2 unit.
1189    #[inline]
1190    pub fn has_sme2() -> bool {
1191        crate::platform::Platform::detect().is_sme2()
1192    }
1193
1194    /// Best-effort diagnostic to fd 2 (delegates to `self_test::fail_stop_bytes`),
1195    /// then `std::process::abort()`. Shared with `blake3-servil` so both crates
1196    /// use one fail-stop implementation.
1197    #[cold]
1198    pub fn fail_stop(why: &str) -> ! {
1199        crate::self_test::fail_stop_bytes(why.as_bytes())
1200    }
1201}
1202
1203/// An alias to distinguish [`context_key`](throughput::context_key) outputs from other keys.
1204/// It is a plain byte array, and so are its traits: its `Debug` prints the
1205/// key, and its `==` promises no constant time.
1206pub type ContextKey = [u8; KEY_LEN];
1207
1208/// Prepared BLAKE3 mode (immutable key words + domain flags), private so
1209/// nothing outside `domain` can mutate them independently or pair non-IV
1210/// words with plain-mode flags.
1211pub(crate) mod domain {
1212    use super::{CVWords, DERIVE_KEY_MATERIAL, IV, KEYED_HASH, Mode, platform, throughput};
1213
1214    #[derive(Clone, Copy)]
1215    pub(crate) struct Domain {
1216        key: CVWords,
1217        flags: u8,
1218    }
1219
1220    impl Domain {
1221        #[inline(always)]
1222        pub(crate) const fn plain() -> Self {
1223            Self { key: *IV, flags: 0 }
1224        }
1225
1226        #[inline]
1227        pub(crate) fn from_mode(mode: Mode<'_>) -> Self {
1228            match mode {
1229                Mode::Plain => Self::plain(),
1230                Mode::Keyed(key) => Self { key: platform::words_from_le_bytes_32(key), flags: KEYED_HASH },
1231                Mode::DeriveKey(context) => Self { key: platform::words_from_le_bytes_32(&throughput::context_key(context)), flags: DERIVE_KEY_MATERIAL },
1232                Mode::DeriveKeyWith(context_key) => Self { key: platform::words_from_le_bytes_32(context_key), flags: DERIVE_KEY_MATERIAL },
1233            }
1234        }
1235
1236        #[inline(always)]
1237        pub(crate) const fn key(&self) -> &CVWords {
1238            &self.key
1239        }
1240
1241        #[inline(always)]
1242        pub(crate) const fn flags(&self) -> u8 {
1243            self.flags
1244        }
1245
1246        #[inline(always)]
1247        pub(crate) const fn is_plain(&self) -> bool {
1248            self.flags == 0
1249        }
1250    }
1251}
1252
1253pub(crate) use domain::Domain;
1254
1255/// Which of BLAKE3's three functions a call computes: the plain hash
1256/// ([`hash`](convenience::hash)), the keyed hash, or key derivation. Every call that takes a mode runs each one at the same
1257/// speed, but for `DeriveKey`, which first hashes its context string (once
1258/// per call; [`DeriveKeyWith`](Mode::DeriveKeyWith) takes it hashed
1259/// once for many calls).
1260///
1261/// # Trait implementations
1262///
1263/// - `Clone` preserves the function selected and any borrowed key or
1264///   context.
1265/// - `Copy` copies the selection without copying the bytes it borrows.
1266#[derive(Clone, Copy)]
1267pub enum Mode<'a> {
1268    /// The plain hash function, as [`hash`](convenience::hash).
1269    Plain,
1270    /// The keyed hash function with this key.
1271    Keyed(&'a [u8; KEY_LEN]),
1272    /// The key derivation function with this context string; the input
1273    /// is the key material.
1274    DeriveKey(&'a str),
1275    /// The key derivation function with its context string already hashed
1276    /// ([`context_key`](throughput::context_key)); the input is the key material.
1277    DeriveKeyWith(&'a ContextKey),
1278}
1279
1280impl Mode<'_> {
1281    /// The key words and flags this mode hashes with, the plain mode's IV
1282    /// where it is: a public call's one way to its key. A copy of the IV
1283    /// put 32 bytes of stores on the stack before the message's loads of
1284    /// every call (October 24, the i7's disassembly of a caller); a
1285    /// constant mode folds to its constants, inlined.
1286    #[inline]
1287    pub(crate) fn key(self, room: &mut core::mem::MaybeUninit<CVWords>) -> (&CVWords, u8) {
1288        match self {
1289            Mode::Plain => (IV, 0),
1290            _ => {
1291                let (key, flags) = self.key_and_flags();
1292                (room.write(key), flags)
1293            }
1294        }
1295    }
1296
1297    /// The key words and flags this mode hashes with.
1298    #[inline]
1299    pub(crate) fn key_and_flags(self) -> (CVWords, u8) {
1300        let domain = Domain::from_mode(self);
1301        (*domain.key(), domain.flags())
1302    }
1303}
1304
1305/// The whole input on the calling thread, in the given mode: the one-chunk
1306/// kernel call up to CHUNK_LEN, the subtree walk above. hash(),
1307/// hash() in its modes and hash_multithreaded()'s short path all come
1308/// through here.
1309#[inline]
1310pub(crate) fn hash_serial(input: &[u8], key: &CVWords, flags: u8) -> Hash {
1311    hash_serial_from(Platform::detect(), input, key, flags, false)
1312}
1313
1314/// [`hash_serial`] for occasional cold calls (`convenience`): prefetches the
1315/// kernel code first where that helps a call whose code has left the caches.
1316#[inline]
1317fn hash_serial_cold(input: &[u8], key: &CVWords, flags: u8) -> Hash {
1318    hash_serial_from(Platform::detect(), input, key, flags, true)
1319}
1320
1321/// [`hash_serial`] from `platform`, and `cold` for a call now and then:
1322/// the startup self-test's way in, which has not run `Platform::detect`'s
1323/// check (it is that check). Always inlined, so each entry point has its
1324/// own copy with `cold` a constant, as hash_serial alone did before cold
1325/// calls had their path (one out-of-line copy taking `cold` as an argument
1326/// made convenience::hash of 512 B after other work 11.5% slower, the VM's
1327/// check).
1328#[inline(always)]
1329fn hash_serial_from(platform: Platform, input: &[u8], key: &CVWords, flags: u8, cold: bool) -> Hash {
1330    let turn = platform::Sme2Turn::take(platform, input.len() >= SME2_SIZED_LEN);
1331    // One comparison on the path of a chunk or less: everything else is
1332    // out of line, so that path's code stays as small as it was (a call
1333    // after other work fetches every line of it from DRAM).
1334    #[cfg(target_arch = "aarch64")]
1335    if cold && (CHUNK_LEN + 1..PREFETCH_BELOW).contains(&input.len()) {
1336        prefetch_cold(input.len(), turn.platform(), false);
1337    }
1338    #[cfg(not(target_arch = "aarch64"))]
1339    let _ = cold;
1340    hash_serial_on(input, key, flags, turn.platform())
1341}
1342
1343/// Below this length a call now and then (`convenience`'s, and a fresh
1344/// Hasher's first update) prefetches its kernels' code: after other work
1345/// the call then fetches it from DRAM in parallel, not one miss at a time
1346/// (M4 Max, after other work: 4 KiB x0.61, 8 KiB x0.51, 16 KiB x0.66;
1347/// 32 KiB and up level, the hashing's own time dwarfing it; jobs
1348/// 971-975). It costs a call whose code is near 2-4%, which is why the
1349/// throughput calls, for call after call, take no prefetch.
1350/// A cold call of 2-8 KiB spends about a third of its time on its code
1351/// (10-24 KB of kernels and glue); from 3 KiB what remains is the kernels
1352/// starting before their lines arrive. Tried and set aside: prefetching
1353/// for a chunk or less (2-10% gained, less than the pause check costs);
1354/// prefetching the 16 KiB of Rust around the kernels too (every call
1355/// 400-500 ns slower: prefetches beyond some number in flight are
1356/// dropped); a rolled four-lane NEON path for calls after a pause (1.3 KB,
1357/// 1.2-1.5x slower: a four-lane NEON BLAKE3 is bound by its chains'
1358/// latency, where the hybrids' integer lanes fill the idle issue slots).
1359#[cfg(target_arch = "aarch64")]
1360const PREFETCH_BELOW: usize = 64 * 1024;
1361
1362/// Prefetch the kernels hashing `len` bytes runs, for a call now and then:
1363/// a one-shot call's (prefetch_kernels), or with `fresh_hasher` a fresh
1364/// Hasher's first update's (prefetch_update_kernels).
1365#[cfg(target_arch = "aarch64")]
1366// Cold for layout: the path of a chunk or less falls through past its
1367// call, on the lines it had before the call existed.
1368#[cold]
1369#[inline(never)]
1370fn prefetch_cold(len: usize, platform: Platform, fresh_hasher: bool) {
1371    if fresh_hasher {
1372        prefetch_update_kernels(len, platform);
1373    } else {
1374        prefetch_kernels(len, platform);
1375    }
1376}
1377
1378/// Prefetch the code of the kernels hashing `len` bytes on `platform`
1379/// runs: SME2's from 16 chunks, else the hybrids', chunks to root.
1380#[cfg(target_arch = "aarch64")]
1381fn prefetch_kernels(len: usize, platform: Platform) {
1382    #[cfg(target_arch = "aarch64")]
1383    if matches!(platform, Platform::SME2) && len >= SME2_SIZED_LEN {
1384        sme2::prefetch_code();
1385        // Below the flat walk, sixteen chunks' values merge on the hybrids.
1386        if !sme2::flat_takes(len) {
1387            neon_hybrid::prefetch_parent_code(16);
1388        }
1389        return;
1390    }
1391    // Below 16 chunks the SME2 platform runs the hybrids too.
1392    if matches!(platform, Platform::NEON | Platform::SME2) && neon_hybrid::sha3_detected() {
1393        let total_chunks = len.div_ceil(CHUNK_LEN);
1394        let whole = (len / CHUNK_LEN).min(16);
1395        let partial = if whole == 16 { 0 } else { len % CHUNK_LEN };
1396        neon_hybrid::prefetch_tree_code(whole, partial, total_chunks);
1397    }
1398}
1399
1400/// Prefetch the code a fresh Hasher's update of `len` bytes runs: the
1401/// subtrees its loop cuts (hasher::subtree_len from counter 0, up to the last
1402/// chunk, which waits in the chunk state), each one's kernels.
1403#[cfg(target_arch = "aarch64")]
1404fn prefetch_update_kernels(len: usize, platform: Platform) {
1405    if !neon_hybrid::sha3_detected() {
1406        return;
1407    }
1408    let (mut counter, mut left) = (0u64, len);
1409    while left > CHUNK_LEN {
1410        let subtree = hasher::subtree_len(counter, left);
1411        let chunks = subtree / CHUNK_LEN;
1412        if matches!(platform, Platform::SME2) && chunks >= 16 {
1413            sme2::prefetch_code();
1414            if !sme2::flat_takes(subtree) {
1415                neon_hybrid::prefetch_parent_code(16);
1416            }
1417            counter += chunks as u64;
1418            left -= subtree;
1419            continue;
1420        }
1421        neon_hybrid::prefetch_tree_code(chunks.min(16), 0, chunks);
1422        counter += chunks as u64;
1423        left -= subtree;
1424    }
1425}
1426
1427/// The smallest input the SME2 kernels take part in: one group of sixteen
1428/// chunks. Below it the SME2 platform runs the NEON hybrids.
1429pub(crate) const SME2_SIZED_LEN: usize = 16 * CHUNK_LEN;
1430
1431/// The fewest messages a batch has when the SME2 kernels take part: one
1432/// group of sixteen messages.
1433pub(crate) const SME2_SIZED_BATCH: usize = 16;
1434
1435/// [`hash_serial`] with the tree's kernels chosen by the caller (a pool
1436/// piece runs the NEON hybrids); one chunk or less runs the scalar kernel
1437/// on every platform.
1438#[inline]
1439pub(crate) fn hash_serial_on(input: &[u8], key: &CVWords, flags: u8, platform: Platform) -> Hash {
1440    Hash(tree::hash(&tree::PlatformKernels { key, flags, platform }, input))
1441}
1442
1443/// [`hash_many`] in the mode of `key` and `flags`, on the calling thread.
1444#[inline]
1445pub(crate) fn hash_many_serial(input: &[u8], message_len: usize, slot: usize, key: &CVWords, flags: u8, out: &mut [[u8; OUT_LEN]]) {
1446    hash_many_serial_from(Platform::detect(), input, message_len, slot, key, flags, out);
1447}
1448
1449/// [`hash_many_serial`] from `platform` (the self-test's way in, as
1450/// [`hash_serial_from`]).
1451#[inline]
1452fn hash_many_serial_from(platform: Platform, input: &[u8], message_len: usize, slot: usize, key: &CVWords, flags: u8, out: &mut [[u8; OUT_LEN]]) {
1453    let turn = platform::Sme2Turn::take(platform, many::sme2_sized(message_len, slot, out.len()));
1454    many::hash_many_on(input, message_len, slot, key, flags, out, turn.platform());
1455}
1456
1457mod hasher;
1458pub(crate) use hasher::{ChunkState, CvStack, Output};
1459
1460mod incremental;
1461pub(crate) use incremental::*;
1462
1463/// An incremental reader for extended output, returned by
1464/// [`Hasher::finalize_xof`](convenience::Hasher::finalize_xof).
1465///
1466/// Shorter BLAKE3 outputs are prefixes of longer ones, and explicitly requesting a short output is
1467/// equivalent to truncating the default-length output. Note that this is a difference between
1468/// BLAKE2 and BLAKE3.
1469///
1470/// # Security notes
1471///
1472/// Outputs shorter than the default length of 32 bytes (256 bits) provide less security. An N-bit
1473/// BLAKE3 output is intended to provide N bits of first and second preimage resistance and N/2
1474/// bits of collision resistance, for any N up to 256. Longer outputs don't provide any additional
1475/// security.
1476///
1477/// Avoid relying on the secrecy of the output offset, that is, the number of output bytes read or
1478/// the arguments to [`seek`](struct.OutputReader.html#method.seek) or
1479/// [`set_position`](struct.OutputReader.html#method.set_position). [_Block-Cipher-Based Tree
1480/// Hashing_ by Aldo Gunsing](https://eprint.iacr.org/2022/283) shows that an attacker who knows
1481/// both the message and the key (if any) can easily determine the offset of an extended output.
1482/// For comparison, AES-CTR has a similar property: if you know the key, you can decrypt a block
1483/// from an unknown position in the output stream to recover its block index. Callers with strong
1484/// secret keys aren't affected in practice, but secret offsets are a [design
1485/// smell](https://en.wikipedia.org/wiki/Design_smell) in any case.
1486///
1487/// # Trait implementations
1488///
1489/// - `Clone` reads the same output from the same position, with an
1490///   independent cursor.
1491/// - `Debug` reports the position without disclosing the output or key.
1492/// - `Read` advances by the bytes returned, stopping at position `u64::MAX`.
1493/// - `Seek` moves within the same output, clamping past its end and refusing
1494///   negative positions and seeks relative to the end.
1495#[derive(Clone)]
1496pub struct OutputReader {
1497    inner: Output,
1498    position_within_block: u8,
1499    cached_block: [u8; BLOCK_LEN],
1500    cache_valid: bool,
1501}
1502
1503impl OutputReader {
1504    fn new(inner: Output) -> Self {
1505        Self { inner, position_within_block: 0, cached_block: [0; BLOCK_LEN], cache_valid: false }
1506    }
1507
1508    // This helper function handles both the case where the output buffer is
1509    // shorter than one block, and the case where our position_within_block is
1510    // non-zero.
1511    fn fill_one_block(&mut self, buf: &mut &mut [u8]) {
1512        if !self.cache_valid {
1513            self.cached_block = self.inner.root_output_block();
1514            self.cache_valid = true;
1515        }
1516        let output_bytes = &self.cached_block[self.position_within_block as usize..];
1517        let take = cmp::min(buf.len(), output_bytes.len());
1518        buf[..take].copy_from_slice(&output_bytes[..take]);
1519        self.position_within_block += u8::try_from(take).expect("take <= BLOCK_LEN");
1520        if usize::from(self.position_within_block) == BLOCK_LEN {
1521            self.inner.counter += 1;
1522            self.position_within_block = 0;
1523            self.cache_valid = false;
1524        }
1525        // Advance the dest buffer. mem::take() is a borrowck workaround.
1526        *buf = &mut core::mem::take(buf)[take..];
1527    }
1528
1529    /// Fill a buffer with output bytes and advance the position of the
1530    /// `OutputReader`. It always fills the entire buffer. [`Read::read`]
1531    /// does the same up to the output's end, and differs there: it reads
1532    /// the bytes that are left and after them 0 bytes, where this call
1533    /// panics (below).
1534    ///
1535    /// A partial output block is retained for subsequent short reads, so
1536    /// sequential reads don't recompute that block. Whole blocks continue
1537    /// through the vectorized output path. For streaming throughput, prefer
1538    /// a slice length that's a multiple of [`BLOCK_LEN`] (64 bytes).
1539    ///
1540    /// The maximum output size of BLAKE3 is 2<sup>64</sup>-1 bytes.
1541    ///
1542    /// # Panics
1543    ///
1544    /// If `buf` asks for bytes past that end (after seeking near it), in
1545    /// every build: the position cannot count them. [`Read::read`] reads
1546    /// up to the end instead, and then gives 0 bytes.
1547    ///
1548    /// [`Read::read`]: #method.read
1549    pub fn fill(&mut self, mut buf: &mut [u8]) {
1550        if buf.is_empty() {
1551            return;
1552        }
1553        // Past the end the block counter would overflow: the position
1554        // wrapped to 0 in a release build, and a seek relative to it then
1555        // gave the output's first bytes again (BLAKE3 #423).
1556        assert!(buf.len() as u64 <= self.remaining(), "BLAKE3's output ends at 2^64 - 1 bytes");
1557
1558        // If we're partway through a block, try to get to a block boundary.
1559        if self.position_within_block != 0 {
1560            self.fill_one_block(&mut buf);
1561            if buf.is_empty() {
1562                return;
1563            }
1564        }
1565
1566        // The whole blocks at once (xof_many takes none as none), then the
1567        // tail block alone. Each guard here spares a root block computed for
1568        // nothing, which test_fill_computes_each_block_once counts.
1569        let full_blocks = buf.len() / BLOCK_LEN;
1570        let full_blocks_len = full_blocks * BLOCK_LEN;
1571        // Debug-only: structural postcondition of the partial-block branch above
1572        // (either we filled to boundary or `buf` became empty, so `full_blocks == 0`).
1573        debug_assert!(full_blocks == 0 || self.position_within_block == 0);
1574        self.inner.platform.xof_many(
1575            &self.inner.input_chaining_value,
1576            &self.inner.block,
1577            self.inner.block_len,
1578            self.inner.counter,
1579            self.inner.flags | ROOT,
1580            &mut buf[..full_blocks_len],
1581        );
1582        self.inner.counter += full_blocks as u64;
1583        buf = &mut buf[full_blocks_len..];
1584
1585        if !buf.is_empty() {
1586            // Debug-only: `buf` is the remainder after dividing by `BLOCK_LEN`.
1587            debug_assert!(buf.len() < BLOCK_LEN);
1588            self.fill_one_block(&mut buf);
1589            // Debug-only: `fill_one_block` consumes all `< BLOCK_LEN` bytes of a fresh block.
1590            debug_assert!(buf.is_empty());
1591        }
1592    }
1593
1594    /// Return the current read position in the output stream. This is
1595    /// equivalent to [`Seek::stream_position`], except that it doesn't return
1596    /// a `Result`. The position of a new `OutputReader` starts at 0, and each
1597    /// call to [`fill`] or [`Read::read`] moves the position forward by the
1598    /// number of bytes read.
1599    ///
1600    /// [`Seek::stream_position`]: #method.stream_position
1601    /// [`fill`]: #method.fill
1602    /// [`Read::read`]: #method.read
1603    pub fn position(&self) -> u64 {
1604        self.inner.counter * BLOCK_LEN as u64 + self.position_within_block as u64
1605    }
1606
1607    /// The output bytes left from the position to the output's end.
1608    #[inline]
1609    fn remaining(&self) -> u64 {
1610        u64::MAX - self.position()
1611    }
1612
1613    /// Seek to a new read position in the output stream. This is equivalent to
1614    /// calling [`Seek::seek`] with [`SeekFrom::Start`], except that it doesn't
1615    /// return a `Result`.
1616    ///
1617    /// [`Seek::seek`]: #method.seek
1618    /// [`SeekFrom::Start`]: https://doc.rust-lang.org/std/io/enum.SeekFrom.html
1619    pub fn set_position(&mut self, position: u64) {
1620        self.position_within_block = u8::try_from(position % BLOCK_LEN as u64).expect("remainder < 64");
1621        self.inner.counter = position / BLOCK_LEN as u64;
1622        self.cache_valid = false;
1623    }
1624}
1625
1626// Don't derive(Debug), because the state may be secret.
1627impl fmt::Debug for OutputReader {
1628    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1629        f.debug_struct("OutputReader").field("position", &self.position()).finish()
1630    }
1631}
1632
1633impl std::io::Read for OutputReader {
1634    #[inline]
1635    fn read(&mut self, buf: &mut [u8]) -> std::io::Result<usize> {
1636        // Up to the output's end, where a read gives 0 bytes as a file's
1637        // does.
1638        let len = usize::try_from(cmp::min(buf.len() as u64, self.remaining())).expect("bounded by buf.len()");
1639        self.fill(&mut buf[..len]);
1640        Ok(len)
1641    }
1642}
1643
1644impl std::io::Seek for OutputReader {
1645    fn seek(&mut self, pos: std::io::SeekFrom) -> std::io::Result<u64> {
1646        let max_position = u64::MAX as i128;
1647        let target_position: i128 = match pos {
1648            std::io::SeekFrom::Start(x) => x as i128,
1649            std::io::SeekFrom::Current(x) => self.position() as i128 + x as i128,
1650            std::io::SeekFrom::End(_) => {
1651                return Err(std::io::Error::new(std::io::ErrorKind::InvalidInput, "seek from end not supported"));
1652            }
1653        };
1654        if target_position < 0 {
1655            return Err(std::io::Error::new(std::io::ErrorKind::InvalidInput, "seek before start"));
1656        }
1657        self.set_position(u64::try_from(cmp::min(target_position, max_position)).expect("non-negative and <= u64::MAX"));
1658        Ok(self.position())
1659    }
1660}