Skip to main content

Hasher

Struct Hasher 

Source
pub struct Hasher { /* private fields */ }
Expand description

A message’s hash, fed in pieces: update with each piece, in order, then finalize. The pieces may be of any lengths; the hash is the same as hash of them all at once. Every call runs on the calling thread and returns with its input incorporated. For other cores, the crate blake3-servil has throughput::update_multithreaded; for many messages at once, throughput::update_each.

A Hasher is 26 KiB (it holds short pieces until it has 16 KiB to hash at once, and rows of chaining values, so that parents are hashed side by side); box it where that matters. It touches what it uses: a short message touches its first block.

§After a panic

Each call says what it refuses, and a callback of the caller’s may panic too. If update_with unwinds after passing length preflight — including a panic in its halves callback or rejection of the returned chaining values’ positions — this Hasher is poisoned: later hashing operations (update, update_with, update_reader, Write::write, finalize, finalize_xof, update_each, finalize_each) panic instead of silently hashing a truncated message, and finalize_each refuses rather than resetting it. Clone and clone_from propagate the poisoned state (clone_from from a healthy source replaces it); Debug and Write::flush still succeed. Other panics (such as an out-of-range index mid-way through update_each) may leave some pieces incorporated and others not: replace such a hasher with a new one before its next message.

§Examples

// Hash an input incrementally.
let mut hasher = blake3_servil_core::convenience::Hasher::new(blake3_servil_core::Mode::Plain, None);
hasher.update(b"foo");
hasher.update(b"bar");
hasher.update(b"baz");
// finalize borrows the Hasher: more updates may follow it.
assert_eq!(hasher.finalize(), blake3_servil_core::convenience::hash(b"foobarbaz"));

// Extended output. OutputReader also implements Read and Seek.
let mut output = [0; 1000];
let mut hasher = blake3_servil_core::convenience::Hasher::new(blake3_servil_core::Mode::Plain, None);
hasher.update(b"foobarbaz");
let mut output_reader = hasher.finalize_xof();
output_reader.fill(&mut output);
assert_eq!(&output[..32], blake3_servil_core::convenience::hash(b"foobarbaz").as_bytes());

§Trait implementations

  • Clone copies the hashing state (26 KiB: the key, the tree so far and up to the last 16 KiB of the message’s bytes), so both hashers go on with the same message, each alone; nothing wipes either copy when it is dropped.
  • Debug shows the mode flags and platform, keeping the key and message private.
  • Write feeds every written byte in order; flushing leaves the message unchanged.

Implementations§

Source§

impl Hasher

Source

pub fn new(mode: Mode<'_>, length_hint: Option<u64>) -> Hasher ⓘ

Construct a new Hasher in a Mode: the plain hash, the keyed hash, or key derivation with a context string or a context key.

length_hint is the message’s likely length in bytes, where the program knows one (a file’s size, a protocol’s length field), or None: a scheduling hint, never part of the hash, so the digest is the same whatever it says and however many bytes then arrive. The Hasher does not use it today; keeping it in the constructor avoids a breaking signature change when scheduling uses it later.

Source

pub fn update(&mut self, input: &[u8]) -> &mut Hasher ⓘ

Add the message’s next piece, of any length, on the calling thread.

§Panics

Panics if the cumulative input length would exceed BLAKE3’s maximum message length of 2^64 - 1 bytes (this limit applies equally through update_with, update_reader, std::io::Write, and grouped updates).

Speed: pieces of any size hash at nearly the speed of whole buffers: short pieces are copied into the Hasher until it holds 16 KiB, which then hash at once. Pieces of 16 KiB and more, starting at a multiple of 16 KiB of the message, skip the copy (about 5% of the time on an Apple M4). For a whole message in memory, hash is a little faster; for a file or reader, see update_reader.

Source

pub fn update_with( &mut self, input: &[u8], min_len: usize, halves: &dyn Fn(&TreeHasher, u32, u64, &[u8]) -> [Cv; 2], ) -> &mut Hasher ⓘ

Add the next piece, letting the caller hash large whole subtrees.

The Hasher can pass subtrees of at least min_len bytes to halves. For each call, return the same ordered values as tree.subtree_halves(level, index, input) in the given mode. The Hasher checks both places in every build; the callback is responsible for their bytes.

The callback finishes its work before returning. It is borrowed only for this update, so it can use the caller’s workers or scratch. Input that is not passed to it hashes on the calling thread.

If this call unwinds after passing length preflight (for example, a panic in halves or rejection of returned chaining value positions), this Hasher is poisoned: later hashing operations panic rather than silently hashing truncated bytes (after a panic).

Source

pub fn finalize(&self) -> Hash

The Hash of everything updated so far. The Hasher is left as it was: more updates may follow, and a later finalize then covers them too, as with official BLAKE3’s Hasher.

Speed: when the entire message is still in the stage (under 16 KiB fed via update), it is hashed here as hash would hash it. Otherwise, an empty stage reads the core in place, a staged tail after an aligned empty chunk hashes the tail apart without copying the core, and a fallback (such as staged bytes behind a partial chunk left in the core by update_each on x86-64) copies the core (~10 KiB).

Source

pub fn finalize_xof(&self) -> OutputReader ⓘ

An OutputReader over everything updated so far, which supplies any number of output bytes; the Hasher is left as it was, as with finalize.

Source

pub fn update_reader(&mut self, reader: impl Read) -> Result<&mut Hasher, Error>

As update, but reading from a std::io::Read implementation.

Hasher implements std::io::Write, so it’s possible to use std::io::copy to update a Hasher from any reader. Unfortunately, this standard approach can limit performance, because copy currently uses an internal 8 KiB buffer that isn’t big enough to take advantage of all SIMD instruction sets. (In particular, AVX-512 needs a 16 KiB buffer.) update_reader avoids this performance problem and is slightly more convenient.

The internal buffer size this method uses may change at any time, and it may be different for different targets. The only guarantee is that it will be large enough for all of this crate’s SIMD implementations on the current platform. On the current implementation the initial read allocates and zero-initializes a 64 KiB stack buffer before promoting to 1 MiB on the heap if the stream fills it, so very small readers pay that fixed stack-zeroing cost.

The most common implementer of std::io::Read might be std::fs::File.

The buffer holds the message’s last bytes when the call returns, and is not cleared. For a secret message, read into a buffer of your own, call update, and clear the buffer.

§Example
// Hash standard input.
let mut hasher = blake3_servil_core::convenience::Hasher::new(blake3_servil_core::Mode::Plain, None);
hasher.update_reader(std::io::stdin().lock())?;
println!("{}", hasher.finalize());

Trait Implementations§

Source§

impl Clone for Hasher

Source§

fn clone(&self) -> Hasher ⓘ

Returns a duplicate of the value. Read more
Source§

fn clone_from(&mut self, source: &Hasher)

Performs copy-assignment from source. Read more
Source§

impl Debug for Hasher

Source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result<(), Error>

Formats the value using the given formatter. Read more
Source§

impl Write for Hasher

Source§

fn write(&mut self, input: &[u8]) -> Result<usize, Error>

This is equivalent to update.

Source§

fn flush(&mut self) -> Result<(), Error>

Flushes this output stream, ensuring that all intermediately buffered contents reach their destination. Read more
1.36.0 · Source§

fn write_vectored(&mut self, bufs: &[IoSlice<'_>]) -> Result<usize, Error>

Like write, except that it writes from a slice of buffers. Read more
Source§

fn is_write_vectored(&self) -> bool

🔬This is a nightly-only experimental API. (can_vector)
Determines if this Writer has an efficient write_vectored implementation. Read more
1.0.0 · Source§

fn write_all(&mut self, buf: &[u8]) -> Result<(), Error>

Attempts to write an entire buffer into this writer. Read more
Source§

fn write_all_vectored(&mut self, bufs: &mut [IoSlice<'_>]) -> Result<(), Error>

🔬This is a nightly-only experimental API. (write_all_vectored)
Attempts to write multiple buffers into this writer. Read more
1.0.0 · Source§

fn write_fmt(&mut self, args: Arguments<'_>) -> Result<(), Error>

Writes a formatted string into this writer, returning any error encountered. Read more
1.0.0 · Source§

fn by_ref(&mut self) -> &mut Self
where Self: Sized,

Creates a “by reference” adapter for this instance of Write. Read more

Auto Trait Implementations§

Blanket Implementations§

Source§

impl<T> Any for T
where T: 'static + ?Sized,

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
Source§

impl<T> Borrow<T> for T
where T: ?Sized,

Source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
Source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

Source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
Source§

impl<T> CloneToUninit for T
where T: Clone,

Source§

unsafe fn clone_to_uninit(&self, dest: *mut u8)

🔬This is a nightly-only experimental API. (clone_to_uninit)
Performs copy-assignment from self to dest. Read more
Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

Source§

impl<T, U> Into<U> for T
where U: From<T>,

Source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

Source§

impl<T> ToOwned for T
where T: Clone,

Source§

type Owned = T

The resulting type after obtaining ownership.
Source§

fn to_owned(&self) -> T

Creates owned data from borrowed data, usually by cloning. Read more
Source§

fn clone_into(&self, target: &mut T)

Uses borrowed data to replace owned data, usually by cloning. Read more
Source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

Source§

type Error = Infallible

The type returned in the event of a conversion error.
Source§

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
Source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

Source§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
Source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.