Skip to content

The API

← blake3pp

The surface is small because the choices are independent. What you compute, how you feed it, what runs it and what it may spend are four separate decisions, and picking one never constrains another. Everything lives in namespace blake3pp, and #include <blake3pp/blake3pp.hpp> brings in all of it; the granular headers are in Integration.

This page runs across those decisions. The reference runs down each header.

The choices, and how they compose

one-shot incremental file input extended output
sequential hash(data) hasher update_file(h, path) fill(r, out)
multi-core hash(data, sched) parallel_hasher update_file(h, path, sched) fill(r, out, sched)

Every cell takes the same key modes, returns the same digests, and accepts the same variant pinning. Adding cores adds a scheduler argument and changes nothing else; the one-shot column has keyed_hash and derive_key siblings in both rows, each also taking a std::string_view.

What you compute

Mode: plain, keyed, derive_key

BLAKE3 is one function with three keying modes, and every part of this library offers all three.

blake3pp::digest d   = blake3pp::hash("hello world");
blake3pp::digest mac = blake3pp::keyed_hash(key, message);
auto session_key     = blake3pp::derive_key("example.com 2026-08 tls session",
                                            master_secret);

Keyed mode is BLAKE3's built-in MAC and PRF, the modern replacement for HMAC. Keys are exactly 32 bytes. The span extent in the signatures makes a wrong-sized key a compile error, not a runtime failure.

derive_key is the domain-separated KDF. The context string is not a secret; it is what keeps unrelated uses of the same key material cryptographically independent, so hardcode it and make it unique to the application and purpose.

The mode is a property of the hasher, not of the call, which is why it composes with everything else:

blake3pp::hasher h = blake3pp::hasher::keyed(key);   // incremental MAC
blake3pp::update_file(h, path);                      // ...over a file
auto tag = blake3pp::hash_file(path, sched,
                               {.mode = blake3pp::hash_mode::keyed(key)});

Output: 32 bytes, or a stream

The 32-byte digest is the first 32 bytes of a stream of up to 2^64 - 1 bytes. Past that the output is unspecified, as in the reference implementations, but consecutive fills still continue one stream. Ask for any length, or take the reader:

auto wide = h.finalize<64>();               // std::array<std::byte, 64>

std::vector<std::byte> runtime_sized(n);
h.finalize(runtime_sized);                  // any length, caller's buffer

blake3pp::output_reader r = h.finalize_xof();
r.fill(first_chunk);                        // stream sequentially...
auto next = r.take<32>();                   // ...same, by value
r.seek(10'000'000'000);                     // ...or jump: O(1) random access
r.fill(deep_chunk);                         // byte 10 GB costs what byte 0 costs

Seeking is O(1) because each 64-byte block of the stream is one compression carrying its own counter, depending on nothing before it. That independence is also what makes the stream parallel: with a scheduler, blake3pp::fill(r, big_buffer, sched) splits one request into segments that fill on every core, each straight into its slice of the buffer, and leaves r positioned exactly where blake3pp::fill(r, big_buffer) would have. That free spelling of r.fill() is what lets the sequential and multi-core forms read alike. It is what blake3ppgen --threads runs on.

Extended output works in all three modes: a keyed hasher's finalize_xof() streams MAC'd output, and derive_key hashers emit subkeys of any width.

The digest as a value

std::cout << d.to_hex() << '\n';                      // 64 lowercase hex
std::cout << std::format("digest: {}\n", d);          // std::format-able

std::array<char, 65> hex = d.to_hex_chars();          // no allocation, NUL-terminated
std::string wide_hex = blake3pp::to_hex(h.finalize<64>());   // any byte sequence

digest is a regular value type: compare with ==, round-trip through hex, use it as a map key after hashing its bytes. Comparison is constant-time in every form, matching the Rust reference, which is the safe default for a value compared against untrusted input.

if (blake3pp::hash(payload).matches(user_input)) { /* verified */ }

// Parsing explicitly? std::optional's heterogeneous == compares the
// contained value, and is false for nullopt; no dereference needed.
if (blake3pp::digest::from_hex(user_input) == blake3pp::hash(payload)) {
  /* verified */
}

Hex that does not parse counts as no match, not as an error.

How you feed it

One shot, or incrementally

blake3pp::hasher h;
while (auto block = source.next_block()) {
  h.update(*block);                         // span<const byte>, or string_view
}
blake3pp::digest checkpoint = h.finalize(); // everything so far
h.update(trailer);
blake3pp::digest full = h.finalize();       // ...and of the whole stream
h.reset();                                  // reuse the instance

finalize() is non-destructive and const: taking a digest is a read of the hasher's state, so a long stream can be checkpointed without giving up the hasher. How the input is chunked never changes the result.

A caller that knows it is passing the last bytes says so with update_last() instead. BLAKE3 marks one node of the tree as the root, and which node that is depends on the message: the single chunk of a short message, or the top parent of anything longer. update() therefore has to keep the final chunk out of the wide batches in case the message ends there; told that it does end, that chunk goes through the batch with its neighbours, which is worth about 1.4x on messages of a few chunks. The one-shot hash(), keyed_hash() and derive_key() take this route already. Updating after update_last() is allowed and gives the same digest as if the message had been fed in one stream; all it costs is that batching.

From memory, or from a file

Files are a first-class input, not a read loop the caller writes. The pipeline streams a file through fixed windows using the fastest mechanism the platform offers, bypassing the page cache and overlapping reads with hashing:

OS async engine page-cache bypass
Linux io_uring O_DIRECT
Windows IoRing (Windows 11) or IOCP FILE_FLAG_NO_BUFFERING
macOS GCD (libdispatch) F_NOCACHE
FreeBSD POSIX AIO (lio_listio) on a kqueue O_DIRECT

Each feature degrades independently at runtime: a file the filesystem will not open for direct I/O is read buffered, and a transfer the asynchronous engine refuses is performed synchronously on a few I/O threads of the library's own, then reported from the same poll. Which engines a build has is decided at compile time and reported by compiled_io_engines() (below). That list includes the stdio fallback, which serves platforms with none of the engines above (wasm); nothing degrades to it.

The rung that was engaged is reported after the fact, with the reason appended when an asynchronous engine was asked for and refused: write_report::backend for a write, and blake3pp::read_backend(trace.driver()) for a read given a trace_buffer.

#include <blake3pp/io.hpp>   // sequential; standard library only

auto d = blake3pp::hash_file("dataset.parquet");        // throws system_error

std::error_code ec;
auto d2 = blake3pp::hash_file(config.input_path, ec);   // reports via ec
if (ec) { log_error(ec.message()); }

Which mechanism a file would get is a question of its own, probe_file_io(): it opens the file as update_file() would and reports the plan's window and queue, whether the cache bypass was asked for (a file under 512 KiB never is), and the rung the open landed on, without reading anything. The detail of what a hash then did is the trace's (Performance tracing).

auto p = blake3pp::probe_file_io("dataset.parquet");
p.backend;     // "io_uring+direct", "iocp", "pread", ...
p.io;          // what was asked of the filesystem
p.windows;     // windows the pipeline would keep in flight

probe_file_io() needs a path because the cache bypass depends on the filesystem. The engine does not -- it is fixed by the build and the kernel -- so these calls answer without opening anything:

blake3pp::compiled_io_engines();   // the engines in this binary
blake3pp::available_io_engines();  // those this kernel grants
blake3pp::best_io_engine();        // what a fresh open will use
blake3pp::is_available(e);         // in the binary and granted here
blake3pp::is_async(e);             // true for the engines --no-async gives up
blake3pp::to_string(e);            // "io_uring", "pread", ...
blake3pp::to_string(e, blake3pp::io_direction::write);  // "pwrite", ...

Both lists are best-first, and available_io_engines().front() is best_io_engine(). The enum and the names come from include/blake3pp/detail/io/io_engine.def, as arch comes from arch.def.

to_string() gives the same word a backend string starts with, so the engine token of a probe_file_io() result equals to_string(best_io_engine()) for a file that got what a fresh open gets. blake3ppsum --version prints the compiled list, which of them this machine grants and which auto picks; the tools build their --no-async help text from is_async().

hash_file() is the one-shot form. update_file() is the primitive underneath it: hasher::update() with a file as the source. It streams into a hasher you own and returns, so the hasher's mode and every finalize form apply to file input, and files hash in sequence:

// A derived key from a file's bytes, as a seekable stream:
blake3pp::hasher h = blake3pp::hasher::derive_key("fixture v3 2026-09");
blake3pp::update_file(h, "seed.bin");
auto stream = h.finalize_xof();

// The hash of several files as one message:
blake3pp::hasher all;
for (const auto& part : parts) { blake3pp::update_file(all, part); }
auto d4 = all.finalize();

Paths are std::filesystem::path. Every call that takes one file's path also takes any type with a native() observer the standard path accepts, such as boost::filesystem::path. The native string is passed through unchanged, so nothing is transcoded on Windows, and blake3pp has no Boost dependency. async_update_files is the exception: it takes a span of std::filesystem::path that must outlive the operation, so the caller converts a foreign batch first.

Inside the pipeline

The knobs are file_io_options, and hash_file_options — which adds the SIMD variant and the mode for the hasher it builds — converts to them, so one options object can drive both. The mode is one value a key or a context string names (hash_mode::keyed(key), hash_mode::derive_key("context")), so a request cannot be keyed and derived at once. It copies both, so the options may outlive whatever named them. make_hasher(opts) hands back that hasher, for the finalize forms hash_file() does not have:

#include <blake3pp/parallel_io.hpp>   // io.hpp + parallel.hpp

auto d3 = blake3pp::hash_file(path, pool.get_scheduler(),
                              {.window_bytes = 16 * 1024 * 1024,
                               .queue_depth  = 8});

blake3pp::update_file(h, path, pool.get_scheduler(),
                      {.window_bytes = 16 * 1024 * 1024});

On Linux each read is issued on io_uring's worker threads (IOSQE_ASYNC), not inline in the submitting call. Issuing a large direct read is real CPU work — pinning the pages, splitting and queueing the bios, 1.5-1.9 ms per 64 MiB on a four-drive PCIe 5 stripe under kernel 7.0 — and inline it lands on the thread that also waits for the window's hash. Kernels since 6.x take the inline path whenever they can, which halved the pipeline there, 22 against 41 GiB/s. .submit = submit_mode::immediate turns the hand-off off for callers who want the submit inline (--inline-submit in the tools), and the writer behind blake3ppgen --output takes the same option.

A stream instead of a file

update_stream() is update_file() over a source that cannot be seeked: a pipe, a socket, standard input. The sequential form reads on the calling thread and hashes as it reads, into a hasher in any state:

#include <blake3pp/io.hpp>

blake3pp::hasher h;
std::uint64_t n = blake3pp::update_stream(h, blake3pp::standard_input());
auto d = h.finalize();

Both forms retry a read a signal interrupts, wait on a handle in non-blocking mode rather than read it as ended, and leave the handle open and its blocking mode as found.

The scheduler form fans the windows out over a pool. Its geometry is not planned, because a stream has none to plan from — its length is known only when it ends, and a window is however much of it arrived.

#include <blake3pp/parallel_io.hpp>

blake3pp::hasher h;
auto r = blake3pp::update_stream(h, blake3pp::standard_input(),
                                 pool.get_scheduler());
auto d = h.finalize();

The calling thread reads one window while the pool hashes the ones before it. A producer that keeps up fills every window, and the run is bounded by the hash or by the stream itself. How a window ends behind a slower producer depends on the platform:

  • POSIX ends a window early when the stream runs dry with at least half a window in hand, and hashes what arrived as a run of subtrees, so the pool starts before the window is full.
  • Windows ends a window only when it is full or the stream ends. Its pipe holds about one producer write, so the producer paces every window either way, and an early hand-over would only split the work.

The dry signal is a read that comes back short of its ask; no clock is involved. Every read blocks until the producer writes. An empty stream means the producer is not waiting on the reader, so the reader's block holds nothing up, and the producer is never left blocked on a pipe nobody is draining. On POSIX platforms other than Darwin and Emscripten, the reader watches an empty stream for a few microseconds before it blocks, which saves a wake-up per producer write. On Linux the reader first asks the OS for a 1 MiB pipe buffer.

The stream_report the call returns says what happened: the windows and how many ended early, the pipe buffer the OS granted, what the watch caught, and on Windows the bound on a read's ask. The stream_io_options set the window size, the number of windows (blake3ppsum --qd sets it for a stream) and the pipe buffer to ask for.

The scheduler form needs the hasher on a window boundary, which every fresh one is; a hasher part-way through a window cannot be brought onto the grid from a stream, because the window that would do it is the one window a stream cannot promise to fill. --diag reads a stream run like any other, with the stream as the device, and adds lines for the stream itself.

Writing a file

The reverse direction is write_file(): a generator fills windows, the library writes them through the same per-OS mechanism the reader uses (io_uring + O_DIRECT, IoRing or IOCP + FILE_FLAG_NO_BUFFERING, GCD + F_NOCACHE, POSIX AIO + O_DIRECT, or synchronous pwrite). Three forms, one generator shape fill(std::span<std::byte> out, std::uint64_t offset):

// A known length, generated on the calling thread.
auto wrote = blake3pp::write_file("seed.bin", 1 << 30, fill);
wrote.backend;   // "io_uring+direct", "pwrite", ...

// A length the generator decides: it returns how many bytes it produced,
// and anything short of a whole window ends the file.
auto all = blake3pp::write_file("stream.bin", produce);

// The windows filled over a scheduler, written while the next fills
// (<blake3pp/parallel_io.hpp>).
blake3pp::write_file("seed.bin", 1 << 30, fill, pool.get_scheduler());

In the scheduler form the generator must depend on its offset and nothing else, because windows are filled concurrently and in no particular order. How many are filled at once is the queue depth: by default one per hardware thread, within a 256 MiB bound on the bytes in flight.

Every form takes a generator that may throw. Sequentially the exception propagates off the calling thread; over a scheduler the window's chain carries it, stops the run and rethrows it from write_file(). On failure the file is left as far as it got and is not truncated, because a length invented for bytes that were never produced would hide the failure.

For many files rather than one large one, there is a third layer: <blake3pp/async_io.hpp> turns the same pipeline into senders over a context that owns the window arena, so several files share one allocation instead of each faulting in its own. It is experimental; Many files at once has it.

The parallel form hands each complete window to the scheduler as a subtree, which needs the hasher to sit on a window-aligned boundary. A hasher that does not -- one that has already absorbed part of a message -- is brought back onto the grid by one short first window, whose head it absorbs itself and whose remainder fans out like any other window. The digest is the same wherever it started, and only how much of that first window is parallel varies.

What runs it

Sequential, or over a scheduler

For large in-memory buffers, hand hash() any sender/receiver scheduler. BLAKE3's tree makes the decomposition exact, so the digest is identical to the sequential one.

#include <blake3pp/parallel.hpp>

auto sched = blake3pp::get_parallel_scheduler();
blake3pp::digest d = blake3pp::hash(big_buffer, sched);

get_parallel_scheduler() is P2079's shape, the same call C++26 application code makes: one scheduler per process, taking no size. Anyone who needs a sized or bounded pool constructs their provider's pool and passes its scheduler instead, for instance stdexec's exec::static_thread_pool pool(8); ... hash(big_buffer, pool.get_scheduler()).

When the data arrives in pieces, parallel_hasher has the exact interface of hasher — all three modes, the whole finalize family including finalize_xof() — with the fan-out and all of BLAKE3's subtree-alignment and final-chunk discipline handled internally:

blake3pp::parallel_hasher ph{blake3pp::get_parallel_scheduler()};
while (auto block = source.next_block()) {
  ph.update(*block);
}
blake3pp::digest streamed = ph.finalize();   // == the sequential digest

// Tunable, and checkpointable mid-stream just like hasher:
blake3pp::parallel_hasher tuned{blake3pp::get_parallel_scheduler(),
                                {.window_bytes = 16 * 1024 * 1024}};

The sender/receiver provider is a build-time choice (-DBLAKE3PP_EXECUTION_PROVIDER=auto|std|beman|stdexec), and blake3pp::execution_provider() reports which one a binary carries:

provider floor role
std::execution a standard library that ships it preferred when available
beman.execution C++23 conformance-first polyfill
NVIDIA stdexec C++20 default polyfill

The examples you can run in a browser are built on beman.execution, because it is the one Compiler Explorer installs. Selecting it there is a checkbox; stdexec would be a build. That is a convenience of the venue. A real build should take std::execution where the standard library ships it.

get_parallel_scheduler() is process-wide and takes no size. To run it on fewer threads than the machine has, size it once, before its first use:

#include <blake3pp/parallel_backend.hpp>   // not in the umbrella header

blake3pp::size_parallel_scheduler(8);      // once, before first use
auto d = blake3pp::hash(buf, blake3pp::get_parallel_scheduler());

size_parallel_scheduler() is defined in blake3pp::parallel_backend, which BLAKE3PP_SIZED_PARALLEL_SCHEDULER builds. What it does depends on the provider:

  • beman.execution: beman's own backend runs on every core and takes no size, and P2079 lets a program replace it, once. The option's default, auto, builds blake3pp's replacement and links it into blake3pp::blake3pp, and builds beman.execution with its own default backend disabled. Every program then holds one definition of query_parallel_scheduler_backend(), and sizing works as it does under stdexec. Unsized, the replacement runs on every core, as beman's own does.
  • A beman program with a replacement of its own configures blake3pp with -DBLAKE3PP_SIZED_PARALLEL_SCHEDULER=OFF. beman's default backend then stays in, blake3pp ships no replacement, and the program's definition is the one that counts. size_parallel_scheduler() does not exist in that build.
  • stdexec: the process pool is blake3pp's own. The option is off by default; with ON, an executable that links blake3pp::parallel_backend can call size_parallel_scheduler(), which records the size the pool starts with.
  • std::execution: the standard library owns the scheduler, and the option must be off.

The scheduler-taking overloads accept any scheduler and need none of this.

Which kernel

The binary carries every variant your target platform supports, and dispatch picks the best one at runtime. You can look, and you can override:

for (blake3pp::arch a : blake3pp::compiled_arches())   // in this binary
  std::cout << blake3pp::to_string(a) << ' ';
for (blake3pp::arch a : blake3pp::available_arches())  // usable on this CPU
  std::cout << blake3pp::to_string(a) << ' ';          // best-first

blake3pp::hasher pinned{blake3pp::arch::sse42};        // explicit variant
auto d = blake3pp::hash(data, blake3pp::arch::sse42);  // the one-shots too
assert(blake3pp::available_arches().front() == blake3pp::best_available());

Requesting a variant the CPU cannot run is not an error: dispatch falls back to the best available one, and is_available() answers the question beforehand. To run on kernels of your own, see Kernels of your own.

The build configuration is introspectable too, which is what a diagnostics banner or a bug report needs:

std::cout << std::format("blake3pp {} (simd: {}, execution: {})\n",
                         blake3pp::version(), blake3pp::simd_provider(),
                         blake3pp::execution_provider());
// e.g. "blake3pp 0.1.0 (simd: std::simd, execution: stdexec)"

What it costs you

Allocation

hasher is a fixed-size value type and never touches the heap. Everything that fans out allocates once, when a run is planned: the window arena, the windows that carry the part tables, the reducer's nodes and the operation cells, and a part table's lane array on the first window that needs the size. parallel_hasher allocates its accumulation window at construction. Among the conveniences, to_hex() returns a std::string and to_hex_chars() returns a std::array<char, 65> without allocating; every span-filling overload writes into a buffer you own.

The part table, and stack

The input is split into parts that the scheduler's agents pull as they go, and each part's 32-byte chaining value waits in a table that belongs to the window being hashed. A stack_budget template argument sets how much that table may take, 32 KiB (1024 parts) by default; give it less and the input is split into fewer, larger parts. On the paths that have windows the table lives with the window, so the budget bounds memory per window in flight, not a stack frame. What the agents spend on their own frames is a constant of the build instead (freestanding). A budget that is not a multiple of 32 bytes, or that holds fewer than two parts, does not compile:

blake3pp::digest d = blake3pp::hash<blake3pp::stack_budget{1024}>(buffer, sched);   // 32 parts

Code that knows its calling thread's stack can check the budget against it at compile time:

constexpr blake3pp::stack_budget budget{1024};
static_assert(budget.bytes <= CONFIG_MAIN_STACK_SIZE / 4);   // e.g. on Zephyr

The budget covers that table and nothing else. Each part is reduced on the agent that took it, by a sweep that stages a group of chunk batches and then compresses their parents: two staging buffers and a small chaining-value stack, 12.5 KiB while the build contains a 16-wide kernel, since the buffers are sized for the widest variant compiled rather than the one that runs. That frame does not grow with the part, so an agent's stack does not depend on the input size.

What turning it down does

It shrinks the table, and nothing else. A smaller budget means fewer, larger parts, and the sweep that reduces a part has the same frame whatever the part's size, so the agents' stacks stay where they are. What changes is the table and how many parts there are to balance across agents.

Nothing catches an undersized thread. The checks on stack_budget are consteval and reject a malformed budget — not a multiple of 32 bytes, or fewer than two parts. They cannot know how much stack your threads have, and where this header is compiled nobody does. Overflowing an agent's stack is a crash or worse, not an error you can handle, which is why the freestanding page gives the frames in bytes rather than advice.

Throughput can go before stack does. Agents pull parts from a shared counter, so parts are also the unit of load balancing. A budget that yields fewer parts than the scheduler has agents leaves agents with nothing to take, and the slowest part sets the finish time.

If the agents' frames are the problem, two build settings cut them: BLAKE3PP_SUBTREE_GROUP=1 stages one chunk batch per burst instead of eight, and BLAKE3PP_SUBTREE_FOLD=<levels> replaces the sweep with the single-leaf fold, whose frame is a 32-byte chaining value per level plus one leaf's staging (2384 bytes for the whole-subtree form at 12 levels and degree 16, against 14480 for the sweep). Both cost throughput, and BLAKE3PP_MAX_SIMD_DEGREE scales every figure with the widest kernel the build carries. The measured frames and a worked Zephyr case are in Freestanding and RTOS builds.

keyed_hash, derive_key, update_file and hash_file take the same argument, and parallel_hasher takes it as its second template parameter.

How failures arrive

Every I/O entry point has a throwing form and a std::error_code form, mirroring the standard library, so a caller branches or catches as it prefers. The std::error_code form reports the library's own failures:

failure ec
I/O the operating system's error
allocation errc::not_enough_memory
a broken precondition, such as a hasher part-way through a chunk handed to a scheduler form errc::invalid_argument
a stop errc::operation_canceled

What the caller's own code throws is not the library's to report: a write_file() generator's exception propagates as thrown, whatever its type, also from the std::error_code forms. An execution provider's exception propagates as thrown too, except a std::system_error, std::bad_alloc or std::logic_error of its own, which the forms cannot tell from the library's and map the same way. A foreign path type's native() is the caller's code as well, and what it throws is treated as a provider's. The forms that run none of the three, the sequential update_file(), hash_file() and probe_file_io() on a std::filesystem::path, are noexcept.

Nothing else in the library reports failure on valid input: a variant the CPU cannot run falls back to one it can, and malformed hex counts as no match. What remains are broken preconditions, which throw in every build rather than return: push_subtree_cv() (below), to_hex() into a span too small for the digest, a malformed kernel table (below), and the expert reducer seams.

Expert seams

Kernels of your own

Every hash the library computes runs on four compression functions held in one table, blake3pp::kernel_ops (<blake3pp/kernel.hpp>). Each built-in variant is such a table. A table of your own runs the whole library on your functions: the chunk and tree logic, the CV stack, the parallel engine and the file pipeline call the kernels through the table and nothing else.

function computes
compress_in_place one compression, keeping the eight-word chaining value
compress_xof one compression's full 64 bytes, the extended-output primitive
xof_many consecutive output blocks of one root node
hash_many many inputs of whole blocks each to their chaining values: the SIMD workhorse

The usual case is one fast function and the library's others. Start from a built-in table and replace what you have. This wraps upstream BLAKE3's AVX2 hash_many, whose flag arguments are one byte wide:

#include <blake3pp/core.hpp>
#include <blake3pp/kernel.hpp>

extern "C" void blake3_hash_many_avx2(
    const std::uint8_t* const* inputs, std::size_t num_inputs,
    std::size_t blocks, const std::uint32_t key[8], std::uint64_t counter,
    bool increment_counter, std::uint8_t flags, std::uint8_t flags_start,
    std::uint8_t flags_end, std::uint8_t* out);

void upstream_hash_many(const std::uint8_t* const* inputs, std::size_t n,
                        std::size_t blocks, const std::uint32_t key[8],
                        std::uint64_t counter, bool increment_counter,
                        std::uint32_t flags, std::uint32_t flags_start,
                        std::uint32_t flags_end, std::uint8_t* out) noexcept {
  blake3_hash_many_avx2(inputs, n, blocks, key, counter, increment_counter,
                        static_cast<std::uint8_t>(flags),
                        static_cast<std::uint8_t>(flags_start),
                        static_cast<std::uint8_t>(flags_end), out);
}

// The AVX2 table with upstream's hash_many, where the CPU has AVX2; the
// best built-in table otherwise.
const blake3pp::kernel_ops upstream = [] {
  blake3pp::kernel_ops k = blake3pp::builtin_kernel(blake3pp::arch::avx2);
  if (blake3pp::is_available(blake3pp::arch::avx2)) {
    k.hash_many = &upstream_hash_many;
  }
  return k;
}();

blake3pp::digest hash_upstream(std::span<const std::byte> input) {
  if (const blake3pp::kernel_check c = blake3pp::check_kernel(upstream); !c) {
    throw std::runtime_error("kernel rejected: " + c.failure);
  }
  blake3pp::hasher h{upstream};
  h.update(input);
  return h.finalize();
}

builtin_kernel(a) falls back to the best usable variant, as hasher(arch) does, so install a function that needs an instruction set only where is_available() says the CPU has it. bench/throughput.cpp does this for upstream's AVX2, AVX-512 and NEON kernels, which is how its reference rows run through this pipeline.

The contract. <blake3pp/kernel.hpp> documents each function's arguments; the reference has it in full. The points a kernel most often gets wrong:

  • Counters are 64 bits. hash_many input i uses counter + i when increment_counter is set, xof_many block i uses counter + i, and both must carry into the high word: a run can cross 2^32.
  • hash_many has two shapes. Whole chunks: 16 blocks, the chunk flags as start and end, the counter stepping. Parents: one block, the parent flag, the counter fixed at 0. One call carries at most 2 * max_simd_degree() inputs.
  • No alignment. Input pointers point anywhere in the caller's buffer.
  • No shared state. The parallel engine calls the same function from several threads at once.
  • noexcept, and nothing kept. A kernel must not throw, and must not hold on to a pointer after it returns.
  • simd_degree is the width hash_many is fastest at: a power of two from 1 to max_simd_degree(), which the library was built with (BLAKE3PP_MAX_SIMD_DEGREE) and which sizes its staging buffers.
  • variant is what hasher::selected_arch() reports for a hasher on the table. Name the variant whose instructions your code needs.

Checking a kernel. check_kernel(table) runs the table against the built-in scalar kernel and returns the first difference, naming the function and its arguments:

  • every block length, counters on both sides of 2^32, and flag sets in which every flag appears;
  • xof_many and hash_many at every count up to the limits above, in both shapes and every mode;
  • inputs at every address offset from a 64-byte boundary;
  • 64 guard bytes after every output, chaining values included, so a kernel that writes past its output fails too;
  • whole messages through a hasher on the table, plain, keyed and derived (a long context included), with extended output, across the chunk and batch boundaries.

It hashes some tens of megabytes, so call it at setup or in a test. The library's test suite runs every built-in variant through it. Passing is evidence, not proof: these are the cases the built-in variants are held to. A read past an input is not detected, and a kernel that strays further out of bounds can crash the check rather than fail it; run it in a sanitizer build to catch both.

Where a table goes in. hasher{table}, hasher::keyed(key, table), hasher::derive_key(context, table) and the multi-core hash(input, sched, table). Each checks the table's shape and throws std::invalid_argument when a function pointer is null, variant is arch::auto_detect or simd_degree is not a power of two from 1 to max_simd_degree(). The table must stay alive and unchanged while any hasher made from it, a copy of one, or an output_reader from one is in use.

Stability. Fields are only ever appended. Fill a table by copying a built-in one, as above, or with designated initializers, and an added field keeps your code compiling. A change to an existing function's signature is a breaking change.

Kernels in assembly are invisible to MemorySanitizer: under it, mark their output initialized (__msan_unpoison), as bench/throughput.cpp does, or every byte downstream reads as poisoned.

External subtrees

For engines that compute subtrees externally — custom pipelines, the I/O layer itself — hasher::push_subtree_cv() absorbs an externally-computed subtree chaining value.

Its preconditions are the ones a caller cannot be trusted with, so the three that can be checked are checked in every build and throw std::invalid_argument: a subtree size that is not a power of two, a position the subtree cannot cover, and a hasher part-way through a chunk. The two that cannot be checked here are the caller's alone — the subtree must not contain the message's final chunk, and it must have been hashed under this hasher's key_words() and mode_flags().