Skip to main content

blake3/
lib.rs

1//! The official Rust implementation of the [BLAKE3] cryptographic hash
2//! function.
3//!
4//! # Examples
5//!
6//! ```
7//! # fn main() -> Result<(), Box<dyn std::error::Error>> {
8//! // Hash an input all at once.
9//! let hash1 = blake3::hash(b"foobarbaz");
10//!
11//! // Hash an input incrementally.
12//! let mut hasher = blake3::Hasher::new();
13//! hasher.update(b"foo");
14//! hasher.update(b"bar");
15//! hasher.update(b"baz");
16//! let hash2 = hasher.finalize();
17//! assert_eq!(hash1, hash2);
18//!
19//! // Extended output. OutputReader also implements Read and Seek.
20//! # #[cfg(feature = "std")] {
21//! let mut output = [0; 1000];
22//! let mut output_reader = hasher.finalize_xof();
23//! output_reader.fill(&mut output);
24//! assert_eq!(hash1, output[..32]);
25//! # }
26//!
27//! // Print a hash as hex.
28//! println!("{}", hash1);
29//! # Ok(())
30//! # }
31//! ```
32//!
33//! # Cargo Features
34//!
35//! The `std` feature (the only feature enabled by default) enables the
36//! [`Write`] implementation and the [`update_reader`](Hasher::update_reader)
37//! method for [`Hasher`], and also the [`Read`] and [`Seek`] implementations
38//! for [`OutputReader`].
39//!
40//! The `rayon` feature (disabled by default, but enabled for [docs.rs]) adds
41//! the [`update_rayon`](Hasher::update_rayon) and (in combination with `mmap`
42//! below) [`update_mmap_rayon`](Hasher::update_mmap_rayon) methods for
43//! multithreaded hashing. However, even if this feature is enabled, all other
44//! APIs remain single-threaded.
45//!
46//! The `mmap` feature (disabled by default, but enabled for [docs.rs]) adds the
47//! [`update_mmap`](Hasher::update_mmap) and (in combination with `rayon` above)
48//! [`update_mmap_rayon`](Hasher::update_mmap_rayon) helper methods for
49//! memory-mapped IO.
50//!
51//! The `zeroize` feature (disabled by default, but enabled for [docs.rs])
52//! implements
53//! [`Zeroize`](https://docs.rs/zeroize/latest/zeroize/trait.Zeroize.html) for
54//! this crate's types.
55//!
56//! The `serde` feature (disabled by default, but enabled for [docs.rs]) implements
57//! [`serde::Serialize`](https://docs.rs/serde/latest/serde/trait.Serialize.html) and
58//! [`serde::Deserialize`](https://docs.rs/serde/latest/serde/trait.Deserialize.html)
59//! for [`Hash`](struct@Hash).
60//!
61//! The NEON implementation is enabled by default for AArch64 but requires the
62//! `neon` feature for other ARM targets. Not all ARMv7 CPUs support NEON, and
63//! enabling this feature will produce a binary that's not portable to CPUs
64//! without NEON support.
65//!
66//! The `wasm32_simd` feature enables the WASM SIMD implementation for all `wasm32-`
67//! targets. Similar to the `neon` feature, if `wasm32_simd` is enabled, WASM SIMD
68//! support is assumed. This may become the default in the future.
69//!
70//! The `traits-preview` feature enables implementations of traits from the
71//! RustCrypto [`digest`] crate, and re-exports that crate as `traits::digest`.
72//! However, the traits aren't stable, and they're expected to change in
73//! incompatible ways before that crate reaches 1.0. For that reason, this crate
74//! makes no SemVer guarantees for this feature, and callers who use it should
75//! expect breaking changes between patch versions. (The "-preview" feature name
76//! follows the conventions of the RustCrypto [`signature`] crate.)
77//!
78//! [`Hasher::update_rayon`]: struct.Hasher.html#method.update_rayon
79//! [BLAKE3]: https://blake3.io
80//! [Rayon]: https://github.com/rayon-rs/rayon
81//! [docs.rs]: https://docs.rs/
82//! [`Read`]: https://doc.rust-lang.org/std/io/trait.Read.html
83//! [`Write`]: https://doc.rust-lang.org/std/io/trait.Write.html
84//! [`Seek`]: https://doc.rust-lang.org/std/io/trait.Seek.html
85//! [`digest`]: https://crates.io/crates/digest
86//! [`signature`]: https://crates.io/crates/signature
87
88#![cfg_attr(not(feature = "std"), no_std)]
89
90#[cfg(test)]
91mod test;
92
93#[doc(hidden)]
94#[deprecated(since = "1.8.0", note = "use the hazmat module instead")]
95pub mod guts;
96
97pub mod hazmat;
98
99/// Undocumented and unstable, for benchmarks only.
100#[doc(hidden)]
101pub mod platform;
102
103// Platform-specific implementations of the compression function. These
104// BLAKE3-specific cfg flags are set in build.rs.
105#[cfg(blake3_avx2_rust)]
106#[path = "rust_avx2.rs"]
107mod avx2;
108#[cfg(blake3_avx2_ffi)]
109#[path = "ffi_avx2.rs"]
110mod avx2;
111#[cfg(blake3_avx512_ffi)]
112#[path = "ffi_avx512.rs"]
113mod avx512;
114#[cfg(blake3_neon)]
115#[path = "ffi_neon.rs"]
116mod neon;
117mod portable;
118#[cfg(blake3_sse2_rust)]
119#[path = "rust_sse2.rs"]
120mod sse2;
121#[cfg(blake3_sse2_ffi)]
122#[path = "ffi_sse2.rs"]
123mod sse2;
124#[cfg(blake3_sse41_rust)]
125#[path = "rust_sse41.rs"]
126mod sse41;
127#[cfg(blake3_sse41_ffi)]
128#[path = "ffi_sse41.rs"]
129mod sse41;
130
131#[cfg(blake3_wasm32_simd)]
132#[path = "wasm32_simd.rs"]
133mod wasm32_simd;
134
135#[cfg(feature = "traits-preview")]
136pub mod traits;
137
138#[cfg(feature = "std")]
139mod io;
140mod join;
141
142use arrayref::{array_mut_ref, array_ref};
143use arrayvec::{ArrayString, ArrayVec};
144use core::cmp;
145use core::fmt;
146use platform::{MAX_SIMD_DEGREE, MAX_SIMD_DEGREE_OR_2, Platform};
147#[cfg(feature = "zeroize")]
148use zeroize::Zeroize;
149
150/// The number of bytes in a [`Hash`](struct.Hash.html), 32.
151pub const OUT_LEN: usize = 32;
152
153/// The number of bytes in a key, 32.
154pub const KEY_LEN: usize = 32;
155
156/// The number of bytes in a block, 64.
157///
158/// You don't usually need to think about this number. One case where it matters is calling
159/// [`OutputReader::fill`] in a loop, where using a `buf` argument that's a multiple of `BLOCK_LEN`
160/// avoids repeating work.
161pub const BLOCK_LEN: usize = 64;
162
163/// The number of bytes in a chunk, 1024.
164///
165/// You don't usually need to think about this number, but it often comes up in benchmarks, because
166/// the maximum degree of parallelism used by the implementation equals the number of chunks.
167pub const CHUNK_LEN: usize = 1024;
168
169const MAX_DEPTH: usize = 54; // 2^54 * CHUNK_LEN = 2^64
170
171// While iterating the compression function within a chunk, the CV is
172// represented as words, to avoid doing two extra endianness conversions for
173// each compression in the portable implementation. But the hash_many interface
174// needs to hash both input bytes and parent nodes, so it's better for its
175// output CVs to be represented as bytes.
176type CVWords = [u32; 8];
177type CVBytes = [u8; 32]; // little-endian
178
179const IV: &CVWords = &[
180    0x6A09E667, 0xBB67AE85, 0x3C6EF372, 0xA54FF53A, 0x510E527F, 0x9B05688C, 0x1F83D9AB, 0x5BE0CD19,
181];
182
183const MSG_SCHEDULE: [[usize; 16]; 7] = [
184    [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15],
185    [2, 6, 3, 10, 7, 0, 4, 13, 1, 11, 12, 5, 9, 14, 15, 8],
186    [3, 4, 10, 12, 13, 2, 7, 14, 6, 5, 9, 0, 11, 15, 8, 1],
187    [10, 7, 12, 9, 14, 3, 13, 15, 4, 0, 11, 2, 5, 8, 1, 6],
188    [12, 13, 9, 11, 15, 10, 14, 8, 7, 2, 5, 3, 0, 1, 6, 4],
189    [9, 14, 11, 5, 8, 12, 15, 1, 13, 3, 0, 10, 2, 6, 4, 7],
190    [11, 15, 5, 0, 1, 9, 8, 6, 14, 10, 2, 12, 3, 4, 7, 13],
191];
192
193// These are the internal flags that we use to domain separate root/non-root,
194// chunk/parent, and chunk beginning/middle/end. These get set at the high end
195// of the block flags word in the compression function, so their values start
196// high and go down.
197const CHUNK_START: u8 = 1 << 0;
198const CHUNK_END: u8 = 1 << 1;
199const PARENT: u8 = 1 << 2;
200const ROOT: u8 = 1 << 3;
201const KEYED_HASH: u8 = 1 << 4;
202const DERIVE_KEY_CONTEXT: u8 = 1 << 5;
203const DERIVE_KEY_MATERIAL: u8 = 1 << 6;
204
205#[inline]
206fn counter_low(counter: u64) -> u32 {
207    counter as u32
208}
209
210#[inline]
211fn counter_high(counter: u64) -> u32 {
212    (counter >> 32) as u32
213}
214
215/// An output of the default size, 32 bytes, which provides constant-time
216/// equality checking.
217///
218/// `Hash` implements [`From`] and [`Into`] for `[u8; 32]`, and it provides
219/// [`from_bytes`] and [`as_bytes`] for explicit conversions between itself and
220/// `[u8; 32]`. However, byte arrays and slices don't provide constant-time
221/// equality checking, which is often a security requirement in software that
222/// handles private data. `Hash` doesn't implement [`Deref`] or [`AsRef`], to
223/// avoid situations where a type conversion happens implicitly and the
224/// constant-time property is accidentally lost.
225///
226/// `Hash` provides the [`to_hex`] and [`from_hex`] methods for converting to
227/// and from hexadecimal. It also implements [`Display`] and [`FromStr`].
228///
229/// [`From`]: https://doc.rust-lang.org/std/convert/trait.From.html
230/// [`Into`]: https://doc.rust-lang.org/std/convert/trait.Into.html
231/// [`as_bytes`]: #method.as_bytes
232/// [`from_bytes`]: #method.from_bytes
233/// [`Deref`]: https://doc.rust-lang.org/stable/std/ops/trait.Deref.html
234/// [`AsRef`]: https://doc.rust-lang.org/std/convert/trait.AsRef.html
235/// [`to_hex`]: #method.to_hex
236/// [`from_hex`]: #method.from_hex
237/// [`Display`]: https://doc.rust-lang.org/std/fmt/trait.Display.html
238/// [`FromStr`]: https://doc.rust-lang.org/std/str/trait.FromStr.html
239#[cfg_attr(feature = "serde", derive(serde::Deserialize, serde::Serialize))]
240#[derive(Clone, Copy, Hash, Eq)]
241pub struct Hash([u8; OUT_LEN]);
242
243impl Hash {
244    /// The raw bytes of the `Hash`. Note that byte arrays don't provide
245    /// constant-time equality checking, so if you need to compare hashes,
246    /// prefer the `Hash` type.
247    #[inline]
248    pub const fn as_bytes(&self) -> &[u8; OUT_LEN] {
249        &self.0
250    }
251
252    /// Create a `Hash` from its raw bytes representation.
253    pub const fn from_bytes(bytes: [u8; OUT_LEN]) -> Self {
254        Self(bytes)
255    }
256
257    /// The raw bytes of the `Hash`, as a slice. Useful for serialization. Note that byte arrays
258    /// don't provide constant-time equality checking, so if you need to compare hashes, prefer
259    /// the `Hash` type.
260    #[inline]
261    pub const fn as_slice(&self) -> &[u8] {
262        self.0.as_slice()
263    }
264
265    /// Create a `Hash` from its raw bytes representation as a slice.
266    ///
267    /// Returns an error if the slice is not exactly 32 bytes long.
268    pub fn from_slice(bytes: &[u8]) -> Result<Self, core::array::TryFromSliceError> {
269        Ok(Self::from_bytes(bytes.try_into()?))
270    }
271
272    /// Encode a `Hash` in lowercase hexadecimal.
273    ///
274    /// The returned [`ArrayString`] is a fixed size and doesn't allocate memory
275    /// on the heap. Note that [`ArrayString`] doesn't provide constant-time
276    /// equality checking, so if you need to compare hashes, prefer the `Hash`
277    /// type.
278    ///
279    /// [`ArrayString`]: https://docs.rs/arrayvec/0.5.1/arrayvec/struct.ArrayString.html
280    pub fn to_hex(&self) -> ArrayString<{ 2 * OUT_LEN }> {
281        let mut s = ArrayString::new();
282        let table = b"0123456789abcdef";
283        for &b in self.0.iter() {
284            s.push(table[(b >> 4) as usize] as char);
285            s.push(table[(b & 0xf) as usize] as char);
286        }
287        s
288    }
289
290    /// Decode a `Hash` from hexadecimal. Both uppercase and lowercase ASCII
291    /// bytes are supported.
292    ///
293    /// Any byte outside the ranges `'0'...'9'`, `'a'...'f'`, and `'A'...'F'`
294    /// results in an error. An input length other than 64 also results in an
295    /// error.
296    ///
297    /// Note that `Hash` also implements `FromStr`, so `Hash::from_hex("...")`
298    /// is equivalent to `"...".parse()`.
299    pub fn from_hex(hex: impl AsRef<[u8]>) -> Result<Self, HexError> {
300        fn hex_val(byte: u8) -> Result<u8, HexError> {
301            match byte {
302                b'A'..=b'F' => Ok(byte - b'A' + 10),
303                b'a'..=b'f' => Ok(byte - b'a' + 10),
304                b'0'..=b'9' => Ok(byte - b'0'),
305                _ => Err(HexError(HexErrorInner::InvalidByte(byte))),
306            }
307        }
308        let hex_bytes: &[u8] = hex.as_ref();
309        if hex_bytes.len() != OUT_LEN * 2 {
310            return Err(HexError(HexErrorInner::InvalidLen(hex_bytes.len())));
311        }
312        let mut hash_bytes: [u8; OUT_LEN] = [0; OUT_LEN];
313        for i in 0..OUT_LEN {
314            hash_bytes[i] = 16 * hex_val(hex_bytes[2 * i])? + hex_val(hex_bytes[2 * i + 1])?;
315        }
316        Ok(Hash::from(hash_bytes))
317    }
318}
319
320impl From<[u8; OUT_LEN]> for Hash {
321    #[inline]
322    fn from(bytes: [u8; OUT_LEN]) -> Self {
323        Self::from_bytes(bytes)
324    }
325}
326
327impl From<Hash> for [u8; OUT_LEN] {
328    #[inline]
329    fn from(hash: Hash) -> Self {
330        hash.0
331    }
332}
333
334impl core::str::FromStr for Hash {
335    type Err = HexError;
336
337    fn from_str(s: &str) -> Result<Self, Self::Err> {
338        Hash::from_hex(s)
339    }
340}
341
342#[cfg(feature = "zeroize")]
343impl Zeroize for Hash {
344    fn zeroize(&mut self) {
345        // Destructuring to trigger compile error as a reminder to update this impl.
346        let Self(bytes) = self;
347        bytes.zeroize();
348    }
349}
350
351/// This implementation is constant-time.
352impl PartialEq for Hash {
353    #[inline]
354    fn eq(&self, other: &Hash) -> bool {
355        constant_time_eq::constant_time_eq_32(&self.0, &other.0)
356    }
357}
358
359/// This implementation is constant-time.
360impl PartialEq<[u8; OUT_LEN]> for Hash {
361    #[inline]
362    fn eq(&self, other: &[u8; OUT_LEN]) -> bool {
363        constant_time_eq::constant_time_eq_32(&self.0, other)
364    }
365}
366
367/// This implementation is constant-time if the target is 32 bytes long.
368impl PartialEq<[u8]> for Hash {
369    #[inline]
370    fn eq(&self, other: &[u8]) -> bool {
371        constant_time_eq::constant_time_eq(&self.0, other)
372    }
373}
374
375impl fmt::Display for Hash {
376    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
377        // Formatting field as `&str` to reduce code size since the `Debug`
378        // dynamic dispatch table for `&str` is likely needed elsewhere already,
379        // but that for `ArrayString<[u8; 64]>` is not.
380        let hex = self.to_hex();
381        let hex: &str = hex.as_str();
382
383        f.write_str(hex)
384    }
385}
386
387impl fmt::Debug for Hash {
388    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
389        // Formatting field as `&str` to reduce code size since the `Debug`
390        // dynamic dispatch table for `&str` is likely needed elsewhere already,
391        // but that for `ArrayString<[u8; 64]>` is not.
392        let hex = self.to_hex();
393        let hex: &str = hex.as_str();
394
395        f.debug_tuple("Hash").field(&hex).finish()
396    }
397}
398
399/// The error type for [`Hash::from_hex`].
400///
401/// The `.to_string()` representation of this error currently distinguishes between bad length
402/// errors and bad character errors. This is to help with logging and debugging, but it isn't a
403/// stable API detail, and it may change at any time.
404#[derive(Clone, Debug)]
405pub struct HexError(HexErrorInner);
406
407#[derive(Clone, Debug)]
408enum HexErrorInner {
409    InvalidByte(u8),
410    InvalidLen(usize),
411}
412
413impl fmt::Display for HexError {
414    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
415        match self.0 {
416            HexErrorInner::InvalidByte(byte) => {
417                if byte < 128 {
418                    write!(f, "invalid hex character: {:?}", byte as char)
419                } else {
420                    write!(f, "invalid hex character: 0x{:x}", byte)
421                }
422            }
423            HexErrorInner::InvalidLen(len) => {
424                write!(f, "expected 64 hex bytes, received {}", len)
425            }
426        }
427    }
428}
429
430#[cfg(feature = "std")]
431impl std::error::Error for HexError {}
432
433// Each chunk or parent node can produce either a 32-byte chaining value or, by
434// setting the ROOT flag, any number of final output bytes. The Output struct
435// captures the state just prior to choosing between those two possibilities.
436#[derive(Clone)]
437struct Output {
438    input_chaining_value: CVWords,
439    block: [u8; 64],
440    block_len: u8,
441    counter: u64,
442    flags: u8,
443    platform: Platform,
444}
445
446impl Output {
447    fn chaining_value(&self) -> CVBytes {
448        let mut cv = self.input_chaining_value;
449        self.platform.compress_in_place(
450            &mut cv,
451            &self.block,
452            self.block_len,
453            self.counter,
454            self.flags,
455        );
456        platform::le_bytes_from_words_32(&cv)
457    }
458
459    fn root_hash(&self) -> Hash {
460        debug_assert_eq!(self.counter, 0);
461        let mut cv = self.input_chaining_value;
462        self.platform
463            .compress_in_place(&mut cv, &self.block, self.block_len, 0, self.flags | ROOT);
464        Hash(platform::le_bytes_from_words_32(&cv))
465    }
466
467    fn root_output_block(&self) -> [u8; 2 * OUT_LEN] {
468        self.platform.compress_xof(
469            &self.input_chaining_value,
470            &self.block,
471            self.block_len,
472            self.counter,
473            self.flags | ROOT,
474        )
475    }
476}
477
478#[cfg(feature = "zeroize")]
479impl Zeroize for Output {
480    fn zeroize(&mut self) {
481        // Destructuring to trigger compile error as a reminder to update this impl.
482        let Self {
483            input_chaining_value,
484            block,
485            block_len,
486            counter,
487            flags,
488            platform: _,
489        } = self;
490
491        input_chaining_value.zeroize();
492        block.zeroize();
493        block_len.zeroize();
494        counter.zeroize();
495        flags.zeroize();
496    }
497}
498
499#[derive(Clone)]
500struct ChunkState {
501    cv: CVWords,
502    chunk_counter: u64,
503    buf: [u8; BLOCK_LEN],
504    buf_len: u8,
505    blocks_compressed: u8,
506    flags: u8,
507    platform: Platform,
508}
509
510impl ChunkState {
511    fn new(key: &CVWords, chunk_counter: u64, flags: u8, platform: Platform) -> Self {
512        Self {
513            cv: *key,
514            chunk_counter,
515            buf: [0; BLOCK_LEN],
516            buf_len: 0,
517            blocks_compressed: 0,
518            flags,
519            platform,
520        }
521    }
522
523    fn count(&self) -> usize {
524        BLOCK_LEN * self.blocks_compressed as usize + self.buf_len as usize
525    }
526
527    fn fill_buf(&mut self, input: &mut &[u8]) {
528        let want = BLOCK_LEN - self.buf_len as usize;
529        let take = cmp::min(want, input.len());
530        self.buf[self.buf_len as usize..][..take].copy_from_slice(&input[..take]);
531        self.buf_len += take as u8;
532        *input = &input[take..];
533    }
534
535    fn start_flag(&self) -> u8 {
536        if self.blocks_compressed == 0 {
537            CHUNK_START
538        } else {
539            0
540        }
541    }
542
543    // Try to avoid buffering as much as possible, by compressing directly from
544    // the input slice when full blocks are available.
545    fn update(&mut self, mut input: &[u8]) -> &mut Self {
546        if self.buf_len > 0 {
547            self.fill_buf(&mut input);
548            if !input.is_empty() {
549                debug_assert_eq!(self.buf_len as usize, BLOCK_LEN);
550                let block_flags = self.flags | self.start_flag(); // borrowck
551                self.platform.compress_in_place(
552                    &mut self.cv,
553                    &self.buf,
554                    BLOCK_LEN as u8,
555                    self.chunk_counter,
556                    block_flags,
557                );
558                self.buf_len = 0;
559                self.buf = [0; BLOCK_LEN];
560                self.blocks_compressed += 1;
561            }
562        }
563
564        while input.len() > BLOCK_LEN {
565            debug_assert_eq!(self.buf_len, 0);
566            let block_flags = self.flags | self.start_flag(); // borrowck
567            self.platform.compress_in_place(
568                &mut self.cv,
569                array_ref!(input, 0, BLOCK_LEN),
570                BLOCK_LEN as u8,
571                self.chunk_counter,
572                block_flags,
573            );
574            self.blocks_compressed += 1;
575            input = &input[BLOCK_LEN..];
576        }
577
578        self.fill_buf(&mut input);
579        debug_assert!(input.is_empty());
580        debug_assert!(self.count() <= CHUNK_LEN);
581        self
582    }
583
584    fn output(&self) -> Output {
585        let block_flags = self.flags | self.start_flag() | CHUNK_END;
586        Output {
587            input_chaining_value: self.cv,
588            block: self.buf,
589            block_len: self.buf_len,
590            counter: self.chunk_counter,
591            flags: block_flags,
592            platform: self.platform,
593        }
594    }
595}
596
597// Don't derive(Debug), because the state may be secret.
598impl fmt::Debug for ChunkState {
599    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
600        f.debug_struct("ChunkState")
601            .field("count", &self.count())
602            .field("chunk_counter", &self.chunk_counter)
603            .field("flags", &self.flags)
604            .field("platform", &self.platform)
605            .finish()
606    }
607}
608
609#[cfg(feature = "zeroize")]
610impl Zeroize for ChunkState {
611    fn zeroize(&mut self) {
612        // Destructuring to trigger compile error as a reminder to update this impl.
613        let Self {
614            cv,
615            chunk_counter,
616            buf,
617            buf_len,
618            blocks_compressed,
619            flags,
620            platform: _,
621        } = self;
622
623        cv.zeroize();
624        chunk_counter.zeroize();
625        buf.zeroize();
626        buf_len.zeroize();
627        blocks_compressed.zeroize();
628        flags.zeroize();
629    }
630}
631
632// IMPLEMENTATION NOTE
633// ===================
634// The recursive function compress_subtree_wide(), implemented below, is the
635// basis of high-performance BLAKE3. We use it both for all-at-once hashing,
636// and for the incremental input with Hasher (though we have to be careful with
637// subtree boundaries in the incremental case). compress_subtree_wide() applies
638// several optimizations at the same time:
639// - Multithreading with Rayon.
640// - Parallel chunk hashing with SIMD.
641// - Parallel parent hashing with SIMD. Note that while SIMD chunk hashing
642//   maxes out at MAX_SIMD_DEGREE*CHUNK_LEN, parallel parent hashing continues
643//   to benefit from larger inputs, because more levels of the tree benefit can
644//   use full-width SIMD vectors for parent hashing. Without parallel parent
645//   hashing, we lose about 10% of overall throughput on AVX2 and AVX-512.
646
647/// Undocumented and unstable, for benchmarks only.
648#[doc(hidden)]
649#[derive(Clone, Copy)]
650pub enum IncrementCounter {
651    Yes,
652    No,
653}
654
655impl IncrementCounter {
656    #[inline]
657    fn yes(&self) -> bool {
658        match self {
659            IncrementCounter::Yes => true,
660            IncrementCounter::No => false,
661        }
662    }
663}
664
665// The largest power of two less than or equal to `n`, used in Hasher::update(). This is similar to
666// left_subtree_len(n), but note that left_subtree_len(n) is strictly less than `n`.
667fn largest_power_of_two_leq(n: usize) -> usize {
668    ((n / 2) + 1).next_power_of_two()
669}
670
671// Use SIMD parallelism to hash up to MAX_SIMD_DEGREE chunks at the same time
672// on a single thread. Write out the chunk chaining values and return the
673// number of chunks hashed. These chunks are never the root and never empty;
674// those cases use a different codepath.
675fn compress_chunks_parallel(
676    input: &[u8],
677    key: &CVWords,
678    chunk_counter: u64,
679    flags: u8,
680    platform: Platform,
681    out: &mut [u8],
682) -> usize {
683    debug_assert!(!input.is_empty(), "empty chunks below the root");
684    debug_assert!(input.len() <= MAX_SIMD_DEGREE * CHUNK_LEN);
685
686    let mut chunks_exact = input.chunks_exact(CHUNK_LEN);
687    let mut chunks_array = ArrayVec::<&[u8; CHUNK_LEN], MAX_SIMD_DEGREE>::new();
688    for chunk in &mut chunks_exact {
689        chunks_array.push(array_ref!(chunk, 0, CHUNK_LEN));
690    }
691    platform.hash_many(
692        &chunks_array,
693        key,
694        chunk_counter,
695        IncrementCounter::Yes,
696        flags,
697        CHUNK_START,
698        CHUNK_END,
699        out,
700    );
701
702    // Hash the remaining partial chunk, if there is one. Note that the empty
703    // chunk (meaning the empty message) is a different codepath.
704    let chunks_so_far = chunks_array.len();
705    if !chunks_exact.remainder().is_empty() {
706        let counter = chunk_counter + chunks_so_far as u64;
707        let mut chunk_state = ChunkState::new(key, counter, flags, platform);
708        chunk_state.update(chunks_exact.remainder());
709        *array_mut_ref!(out, chunks_so_far * OUT_LEN, OUT_LEN) =
710            chunk_state.output().chaining_value();
711        chunks_so_far + 1
712    } else {
713        chunks_so_far
714    }
715}
716
717// Use SIMD parallelism to hash up to MAX_SIMD_DEGREE parents at the same time
718// on a single thread. Write out the parent chaining values and return the
719// number of parents hashed. (If there's an odd input chaining value left over,
720// return it as an additional output.) These parents are never the root and
721// never empty; those cases use a different codepath.
722fn compress_parents_parallel(
723    child_chaining_values: &[u8],
724    key: &CVWords,
725    flags: u8,
726    platform: Platform,
727    out: &mut [u8],
728) -> usize {
729    debug_assert_eq!(child_chaining_values.len() % OUT_LEN, 0, "wacky hash bytes");
730    let num_children = child_chaining_values.len() / OUT_LEN;
731    debug_assert!(num_children >= 2, "not enough children");
732    debug_assert!(num_children <= 2 * MAX_SIMD_DEGREE_OR_2, "too many");
733
734    let mut parents_exact = child_chaining_values.chunks_exact(BLOCK_LEN);
735    // Use MAX_SIMD_DEGREE_OR_2 rather than MAX_SIMD_DEGREE here, because of
736    // the requirements of compress_subtree_wide().
737    let mut parents_array = ArrayVec::<&[u8; BLOCK_LEN], MAX_SIMD_DEGREE_OR_2>::new();
738    for parent in &mut parents_exact {
739        parents_array.push(array_ref!(parent, 0, BLOCK_LEN));
740    }
741    platform.hash_many(
742        &parents_array,
743        key,
744        0, // Parents always use counter 0.
745        IncrementCounter::No,
746        flags | PARENT,
747        0, // Parents have no start flags.
748        0, // Parents have no end flags.
749        out,
750    );
751
752    // If there's an odd child left over, it becomes an output.
753    let parents_so_far = parents_array.len();
754    if !parents_exact.remainder().is_empty() {
755        out[parents_so_far * OUT_LEN..][..OUT_LEN].copy_from_slice(parents_exact.remainder());
756        parents_so_far + 1
757    } else {
758        parents_so_far
759    }
760}
761
762// The wide helper function returns (writes out) an array of chaining values
763// and returns the length of that array. The number of chaining values returned
764// is the dynamically detected SIMD degree, at most MAX_SIMD_DEGREE. Or fewer,
765// if the input is shorter than that many chunks. The reason for maintaining a
766// wide array of chaining values going back up the tree, is to allow the
767// implementation to hash as many parents in parallel as possible.
768//
769// As a special case when the SIMD degree is 1, this function will still return
770// at least 2 outputs. This guarantees that this function doesn't perform the
771// root compression. (If it did, it would use the wrong flags, and also we
772// wouldn't be able to implement extendable output.) Note that this function is
773// not used when the whole input is only 1 chunk long; that's a different
774// codepath.
775//
776// Why not just have the caller split the input on the first update(), instead
777// of implementing this special rule? Because we don't want to limit SIMD or
778// multithreading parallelism for that update().
779fn compress_subtree_wide<J: join::Join>(
780    input: &[u8],
781    key: &CVWords,
782    chunk_counter: u64,
783    flags: u8,
784    platform: Platform,
785    out: &mut [u8],
786) -> usize {
787    // Note that the single chunk case does *not* bump the SIMD degree up to 2
788    // when it is 1. This allows Rayon the option of multithreading even the
789    // 2-chunk case, which can help performance on smaller platforms.
790    if input.len() <= platform.simd_degree() * CHUNK_LEN {
791        return compress_chunks_parallel(input, key, chunk_counter, flags, platform, out);
792    }
793
794    // With more than simd_degree chunks, we need to recurse. Start by dividing
795    // the input into left and right subtrees. (Note that this is only optimal
796    // as long as the SIMD degree is a power of 2. If we ever get a SIMD degree
797    // of 3 or something, we'll need a more complicated strategy.)
798    debug_assert_eq!(platform.simd_degree().count_ones(), 1, "power of 2");
799    let (left, right) = input.split_at(hazmat::left_subtree_len(input.len() as u64) as usize);
800    let right_chunk_counter = chunk_counter + (left.len() / CHUNK_LEN) as u64;
801
802    // Make space for the child outputs. Here we use MAX_SIMD_DEGREE_OR_2 to
803    // account for the special case of returning 2 outputs when the SIMD degree
804    // is 1.
805    let mut cv_array = [0; 2 * MAX_SIMD_DEGREE_OR_2 * OUT_LEN];
806    let degree = if left.len() == CHUNK_LEN {
807        // The "simd_degree=1 and we're at the leaf nodes" case.
808        debug_assert_eq!(platform.simd_degree(), 1);
809        1
810    } else {
811        cmp::max(platform.simd_degree(), 2)
812    };
813    let (left_out, right_out) = cv_array.split_at_mut(degree * OUT_LEN);
814
815    // Recurse! For update_rayon(), this is where we take advantage of RayonJoin and use multiple
816    // threads.
817    let (left_n, right_n) = J::join(
818        || compress_subtree_wide::<J>(left, key, chunk_counter, flags, platform, left_out),
819        || compress_subtree_wide::<J>(right, key, right_chunk_counter, flags, platform, right_out),
820    );
821
822    // The special case again. If simd_degree=1, then we'll have left_n=1 and
823    // right_n=1. Rather than compressing them into a single output, return
824    // them directly, to make sure we always have at least two outputs.
825    debug_assert_eq!(left_n, degree);
826    debug_assert!(right_n >= 1 && right_n <= left_n);
827    if left_n == 1 {
828        out[..2 * OUT_LEN].copy_from_slice(&cv_array[..2 * OUT_LEN]);
829        return 2;
830    }
831
832    // Otherwise, do one layer of parent node compression.
833    let num_children = left_n + right_n;
834    compress_parents_parallel(
835        &cv_array[..num_children * OUT_LEN],
836        key,
837        flags,
838        platform,
839        out,
840    )
841}
842
843// Hash a subtree with compress_subtree_wide(), and then condense the resulting
844// list of chaining values down to a single parent node. Don't compress that
845// last parent node, however. Instead, return its message bytes (the
846// concatenated chaining values of its children). This is necessary when the
847// first call to update() supplies a complete subtree, because the topmost
848// parent node of that subtree could end up being the root. It's also necessary
849// for extended output in the general case.
850//
851// As with compress_subtree_wide(), this function is not used on inputs of 1
852// chunk or less. That's a different codepath.
853fn compress_subtree_to_parent_node<J: join::Join>(
854    input: &[u8],
855    key: &CVWords,
856    chunk_counter: u64,
857    flags: u8,
858    platform: Platform,
859) -> [u8; BLOCK_LEN] {
860    debug_assert!(input.len() > CHUNK_LEN);
861    let mut cv_array = [0; MAX_SIMD_DEGREE_OR_2 * OUT_LEN];
862    let mut num_cvs =
863        compress_subtree_wide::<J>(input, &key, chunk_counter, flags, platform, &mut cv_array);
864    debug_assert!(num_cvs >= 2);
865
866    // If MAX_SIMD_DEGREE is greater than 2 and there's enough input,
867    // compress_subtree_wide() returns more than 2 chaining values. Condense
868    // them into 2 by forming parent nodes repeatedly.
869    let mut out_array = [0; MAX_SIMD_DEGREE_OR_2 * OUT_LEN / 2];
870    while num_cvs > 2 {
871        let cv_slice = &cv_array[..num_cvs * OUT_LEN];
872        num_cvs = compress_parents_parallel(cv_slice, key, flags, platform, &mut out_array);
873        cv_array[..num_cvs * OUT_LEN].copy_from_slice(&out_array[..num_cvs * OUT_LEN]);
874    }
875    *array_ref!(cv_array, 0, 2 * OUT_LEN)
876}
877
878// Hash a complete input all at once. Unlike compress_subtree_wide() and
879// compress_subtree_to_parent_node(), this function handles the 1 chunk case.
880fn hash_all_at_once<J: join::Join>(input: &[u8], key: &CVWords, flags: u8) -> Output {
881    let platform = Platform::detect();
882
883    // If the whole subtree is one chunk, hash it directly with a ChunkState.
884    if input.len() <= CHUNK_LEN {
885        return ChunkState::new(key, 0, flags, platform)
886            .update(input)
887            .output();
888    }
889
890    // Otherwise construct an Output object from the parent node returned by
891    // compress_subtree_to_parent_node().
892    Output {
893        input_chaining_value: *key,
894        block: compress_subtree_to_parent_node::<J>(input, key, 0, flags, platform),
895        block_len: BLOCK_LEN as u8,
896        counter: 0,
897        flags: flags | PARENT,
898        platform,
899    }
900}
901
902/// The default hash function.
903///
904/// For an incremental version that accepts multiple writes, see [`Hasher::new`],
905/// [`Hasher::update`], and [`Hasher::finalize`]. These two lines are equivalent:
906///
907/// ```
908/// let hash = blake3::hash(b"foo");
909/// # let hash1 = hash;
910///
911/// let hash = blake3::Hasher::new().update(b"foo").finalize();
912/// # let hash2 = hash;
913/// # assert_eq!(hash1, hash2);
914/// ```
915///
916/// For output sizes other than 32 bytes, see [`Hasher::finalize_xof`] and
917/// [`OutputReader`].
918///
919/// This function is always single-threaded. For multithreading support, see
920/// [`Hasher::update_rayon`](struct.Hasher.html#method.update_rayon).
921pub fn hash(input: &[u8]) -> Hash {
922    hash_all_at_once::<join::SerialJoin>(input, IV, 0).root_hash()
923}
924
925/// The keyed hash function.
926///
927/// This is suitable for use as a message authentication code, for example to
928/// replace an HMAC instance. In that use case, the constant-time equality
929/// checking provided by [`Hash`](struct.Hash.html) is almost always a security
930/// requirement, and callers need to be careful not to compare MACs as raw
931/// bytes.
932///
933/// For an incremental version that accepts multiple writes, see [`Hasher::new_keyed`],
934/// [`Hasher::update`], and [`Hasher::finalize`]. These two lines are equivalent:
935///
936/// ```
937/// # const KEY: &[u8; 32] = &[0; 32];
938/// let mac = blake3::keyed_hash(KEY, b"foo");
939/// # let mac1 = mac;
940///
941/// let mac = blake3::Hasher::new_keyed(KEY).update(b"foo").finalize();
942/// # let mac2 = mac;
943/// # assert_eq!(mac1, mac2);
944/// ```
945///
946/// For output sizes other than 32 bytes, see [`Hasher::finalize_xof`], and [`OutputReader`].
947///
948/// This function is always single-threaded. For multithreading support, see
949/// [`Hasher::update_rayon`](struct.Hasher.html#method.update_rayon).
950pub fn keyed_hash(key: &[u8; KEY_LEN], input: &[u8]) -> Hash {
951    let key_words = platform::words_from_le_bytes_32(key);
952    hash_all_at_once::<join::SerialJoin>(input, &key_words, KEYED_HASH).root_hash()
953}
954
955/// The key derivation function.
956///
957/// Given cryptographic key material of any length and a context string of any
958/// length, this function outputs a 32-byte derived subkey. **The context string
959/// should be hardcoded, globally unique, and application-specific.** A good
960/// default format for such strings is `"[application] [commit timestamp]
961/// [purpose]"`, e.g., `"example.com 2019-12-25 16:18:03 session tokens v1"`.
962///
963/// Key derivation is important when you want to use the same key in multiple
964/// algorithms or use cases. Using the same key with different cryptographic
965/// algorithms is generally forbidden, and deriving a separate subkey for each
966/// use case protects you from bad interactions. Derived keys also mitigate the
967/// damage from one part of your application accidentally leaking its key.
968///
969/// As a rare exception to that general rule, however, it is possible to use
970/// `derive_key` itself with key material that you are already using with
971/// another algorithm. You might need to do this if you're adding features to
972/// an existing application, which does not yet use key derivation internally.
973/// However, you still must not share key material with algorithms that forbid
974/// key reuse entirely, like a one-time pad. For more on this, see sections 6.2
975/// and 7.8 of the [BLAKE3 paper](https://github.com/BLAKE3-team/BLAKE3-specs/blob/master/blake3.pdf).
976///
977/// Note that BLAKE3 is not a password hash, and **`derive_key` should never be
978/// used with passwords.** Instead, use a dedicated password hash like
979/// [Argon2]. Password hashes are entirely different from generic hash
980/// functions, with opposite design requirements.
981///
982/// For an incremental version that accepts multiple writes, see [`Hasher::new_derive_key`],
983/// [`Hasher::update`], and [`Hasher::finalize`]. These two statements are equivalent:
984///
985/// ```
986/// # const CONTEXT: &str = "example.com 2019-12-25 16:18:03 session tokens v1";
987/// let key = blake3::derive_key(CONTEXT, b"key material, not a password");
988/// # let key1 = key;
989///
990/// let key: [u8; 32] = blake3::Hasher::new_derive_key(CONTEXT)
991///     .update(b"key material, not a password")
992///     .finalize()
993///     .into();
994/// # let key2 = key;
995/// # assert_eq!(key1, key2);
996/// ```
997///
998/// For output sizes other than 32 bytes, see [`Hasher::finalize_xof`], and [`OutputReader`].
999///
1000/// This function is always single-threaded. For multithreading support, see
1001/// [`Hasher::update_rayon`](struct.Hasher.html#method.update_rayon).
1002///
1003/// [Argon2]: https://en.wikipedia.org/wiki/Argon2
1004pub fn derive_key(context: &str, key_material: &[u8]) -> [u8; OUT_LEN] {
1005    let context_key = hazmat::hash_derive_key_context(context);
1006    let context_key_words = platform::words_from_le_bytes_32(&context_key);
1007    hash_all_at_once::<join::SerialJoin>(key_material, &context_key_words, DERIVE_KEY_MATERIAL)
1008        .root_hash()
1009        .0
1010}
1011
1012fn parent_node_output(
1013    left_child: &CVBytes,
1014    right_child: &CVBytes,
1015    key: &CVWords,
1016    flags: u8,
1017    platform: Platform,
1018) -> Output {
1019    let mut block = [0; BLOCK_LEN];
1020    block[..32].copy_from_slice(left_child);
1021    block[32..].copy_from_slice(right_child);
1022    Output {
1023        input_chaining_value: *key,
1024        block,
1025        block_len: BLOCK_LEN as u8,
1026        counter: 0,
1027        flags: flags | PARENT,
1028        platform,
1029    }
1030}
1031
1032/// An incremental hash state that can accept any number of writes.
1033///
1034/// The `rayon` and `mmap` Cargo features enable additional methods on this
1035/// type related to multithreading and memory-mapped IO.
1036///
1037/// When the `traits-preview` Cargo feature is enabled, this type implements
1038/// several commonly used traits from the
1039/// [`digest`](https://crates.io/crates/digest) crate. However, those
1040/// traits aren't stable, and they're expected to change in incompatible ways
1041/// before that crate reaches 1.0. For that reason, this crate makes no SemVer
1042/// guarantees for this feature, and callers who use it should expect breaking
1043/// changes between patch versions.
1044///
1045/// # Examples
1046///
1047/// ```
1048/// # fn main() -> Result<(), Box<dyn std::error::Error>> {
1049/// // Hash an input incrementally.
1050/// let mut hasher = blake3::Hasher::new();
1051/// hasher.update(b"foo");
1052/// hasher.update(b"bar");
1053/// hasher.update(b"baz");
1054/// assert_eq!(hasher.finalize(), blake3::hash(b"foobarbaz"));
1055///
1056/// // Extended output. OutputReader also implements Read and Seek.
1057/// # #[cfg(feature = "std")] {
1058/// let mut output = [0; 1000];
1059/// let mut output_reader = hasher.finalize_xof();
1060/// output_reader.fill(&mut output);
1061/// assert_eq!(&output[..32], blake3::hash(b"foobarbaz").as_bytes());
1062/// # }
1063/// # Ok(())
1064/// # }
1065/// ```
1066#[derive(Clone)]
1067pub struct Hasher {
1068    key: CVWords,
1069    chunk_state: ChunkState,
1070    initial_chunk_counter: u64,
1071    // The stack size is MAX_DEPTH + 1 because we do lazy merging. For example,
1072    // with 7 chunks, we have 3 entries in the stack. Adding an 8th chunk
1073    // requires a 4th entry, rather than merging everything down to 1, because
1074    // we don't know whether more input is coming. This is different from how
1075    // the reference implementation does things.
1076    cv_stack: ArrayVec<CVBytes, { MAX_DEPTH + 1 }>,
1077}
1078
1079impl Hasher {
1080    fn new_internal(key: &CVWords, flags: u8) -> Self {
1081        Self {
1082            key: *key,
1083            chunk_state: ChunkState::new(key, 0, flags, Platform::detect()),
1084            initial_chunk_counter: 0,
1085            cv_stack: ArrayVec::new(),
1086        }
1087    }
1088
1089    /// Construct a new `Hasher` for the regular hash function.
1090    pub fn new() -> Self {
1091        Self::new_internal(IV, 0)
1092    }
1093
1094    /// Construct a new `Hasher` for the keyed hash function. See
1095    /// [`keyed_hash`].
1096    ///
1097    /// [`keyed_hash`]: fn.keyed_hash.html
1098    pub fn new_keyed(key: &[u8; KEY_LEN]) -> Self {
1099        let key_words = platform::words_from_le_bytes_32(key);
1100        Self::new_internal(&key_words, KEYED_HASH)
1101    }
1102
1103    /// Construct a new `Hasher` for the key derivation function. See
1104    /// [`derive_key`]. The context string should be hardcoded, globally
1105    /// unique, and application-specific.
1106    ///
1107    /// [`derive_key`]: fn.derive_key.html
1108    pub fn new_derive_key(context: &str) -> Self {
1109        let context_key = hazmat::hash_derive_key_context(context);
1110        let context_key_words = platform::words_from_le_bytes_32(&context_key);
1111        Self::new_internal(&context_key_words, DERIVE_KEY_MATERIAL)
1112    }
1113
1114    /// Reset the `Hasher` to its initial state.
1115    ///
1116    /// This is functionally the same as overwriting the `Hasher` with a new
1117    /// one, using the same key or context string if any.
1118    pub fn reset(&mut self) -> &mut Self {
1119        self.chunk_state = ChunkState::new(
1120            &self.key,
1121            0,
1122            self.chunk_state.flags,
1123            self.chunk_state.platform,
1124        );
1125        self.cv_stack.clear();
1126        self
1127    }
1128
1129    // As described in push_cv() below, we do "lazy merging", delaying merges
1130    // until right before the next CV is about to be added. This is different
1131    // from the reference implementation. Another difference is that we aren't
1132    // always merging 1 chunk at a time. Instead, each CV might represent any
1133    // power-of-two number of chunks, as long as the smaller-above-larger stack
1134    // order is maintained. Instead of the "count the trailing 0-bits"
1135    // algorithm described in the spec (which assumes you're adding one chunk
1136    // at a time), we use a "count the total number of 1-bits" variant (which
1137    // doesn't assume that). The principle is the same: each CV that should
1138    // remain in the stack is represented by a 1-bit in the total number of
1139    // chunks (or bytes) so far.
1140    fn merge_cv_stack(&mut self, chunk_counter: u64) {
1141        // Account for non-zero cases of Hasher::set_input_offset, where there are no prior
1142        // subtrees in the stack. Note that initial_chunk_counter is always 0 for callers who don't
1143        // use the hazmat module.
1144        let post_merge_stack_len =
1145            (chunk_counter - self.initial_chunk_counter).count_ones() as usize;
1146        while self.cv_stack.len() > post_merge_stack_len {
1147            let right_child = self.cv_stack.pop().unwrap();
1148            let left_child = self.cv_stack.pop().unwrap();
1149            let parent_output = parent_node_output(
1150                &left_child,
1151                &right_child,
1152                &self.key,
1153                self.chunk_state.flags,
1154                self.chunk_state.platform,
1155            );
1156            self.cv_stack.push(parent_output.chaining_value());
1157        }
1158    }
1159
1160    // In reference_impl.rs, we merge the new CV with existing CVs from the
1161    // stack before pushing it. We can do that because we know more input is
1162    // coming, so we know none of the merges are root.
1163    //
1164    // This setting is different. We want to feed as much input as possible to
1165    // compress_subtree_wide(), without setting aside anything for the
1166    // chunk_state. If the user gives us 64 KiB, we want to parallelize over
1167    // all 64 KiB at once as a single subtree, if at all possible.
1168    //
1169    // This leads to two problems:
1170    // 1) This 64 KiB input might be the only call that ever gets made to
1171    //    update. In this case, the root node of the 64 KiB subtree would be
1172    //    the root node of the whole tree, and it would need to be ROOT
1173    //    finalized. We can't compress it until we know.
1174    // 2) This 64 KiB input might complete a larger tree, whose root node is
1175    //    similarly going to be the root of the whole tree. For example,
1176    //    maybe we have 196 KiB (that is, 128 + 64) hashed so far. We can't
1177    //    compress the node at the root of the 256 KiB subtree until we know
1178    //    how to finalize it.
1179    //
1180    // The second problem is solved with "lazy merging". That is, when we're
1181    // about to add a CV to the stack, we don't merge it with anything first,
1182    // as the reference impl does. Instead we do merges using the *previous* CV
1183    // that was added, which is sitting on top of the stack, and we put the new
1184    // CV (unmerged) on top of the stack afterwards. This guarantees that we
1185    // never merge the root node until finalize().
1186    //
1187    // Solving the first problem requires an additional tool,
1188    // compress_subtree_to_parent_node(). That function always returns the top
1189    // *two* chaining values of the subtree it's compressing. We then do lazy
1190    // merging with each of them separately, so that the second CV will always
1191    // remain unmerged. (That also helps us support extendable output when
1192    // we're hashing an input all-at-once.)
1193    fn push_cv(&mut self, new_cv: &CVBytes, chunk_counter: u64) {
1194        self.merge_cv_stack(chunk_counter);
1195        self.cv_stack.push(*new_cv);
1196    }
1197
1198    /// Add input bytes to the hash state. You can call this any number of times.
1199    ///
1200    /// This method is always single-threaded. For multithreading support, see
1201    /// [`update_rayon`](#method.update_rayon) (enabled with the `rayon` Cargo feature).
1202    ///
1203    /// Note that the degree of SIMD parallelism that `update` can use is limited by the size of
1204    /// this input buffer. See [`update_reader`](#method.update_reader).
1205    pub fn update(&mut self, input: &[u8]) -> &mut Self {
1206        self.update_with_join::<join::SerialJoin>(input)
1207    }
1208
1209    fn update_with_join<J: join::Join>(&mut self, mut input: &[u8]) -> &mut Self {
1210        let input_offset = self.initial_chunk_counter * CHUNK_LEN as u64;
1211        if let Some(max) = hazmat::max_subtree_len(input_offset) {
1212            let remaining = max - self.count();
1213            assert!(
1214                input.len() as u64 <= remaining,
1215                "the subtree starting at {} contains at most {} bytes (found {})",
1216                CHUNK_LEN as u64 * self.initial_chunk_counter,
1217                max,
1218                input.len(),
1219            );
1220        }
1221        // If we have some partial chunk bytes in the internal chunk_state, we
1222        // need to finish that chunk first.
1223        if self.chunk_state.count() > 0 {
1224            let want = CHUNK_LEN - self.chunk_state.count();
1225            let take = cmp::min(want, input.len());
1226            self.chunk_state.update(&input[..take]);
1227            input = &input[take..];
1228            if !input.is_empty() {
1229                // We've filled the current chunk, and there's more input
1230                // coming, so we know it's not the root and we can finalize it.
1231                // Then we'll proceed to hashing whole chunks below.
1232                debug_assert_eq!(self.chunk_state.count(), CHUNK_LEN);
1233                let chunk_cv = self.chunk_state.output().chaining_value();
1234                self.push_cv(&chunk_cv, self.chunk_state.chunk_counter);
1235                self.chunk_state = ChunkState::new(
1236                    &self.key,
1237                    self.chunk_state.chunk_counter + 1,
1238                    self.chunk_state.flags,
1239                    self.chunk_state.platform,
1240                );
1241            } else {
1242                return self;
1243            }
1244        }
1245
1246        // Now the chunk_state is clear, and we have more input. If there's
1247        // more than a single chunk (so, definitely not the root chunk), hash
1248        // the largest whole subtree we can, with the full benefits of SIMD and
1249        // multithreading parallelism. Two restrictions:
1250        // - The subtree has to be a power-of-2 number of chunks. Only subtrees
1251        //   along the right edge can be incomplete, and we don't know where
1252        //   the right edge is going to be until we get to finalize().
1253        // - The subtree must evenly divide the total number of chunks up until
1254        //   this point (if total is not 0). If the current incomplete subtree
1255        //   is only waiting for 1 more chunk, we can't hash a subtree of 4
1256        //   chunks. We have to complete the current subtree first.
1257        // Because we might need to break up the input to form powers of 2, or
1258        // to evenly divide what we already have, this part runs in a loop.
1259        while input.len() > CHUNK_LEN {
1260            debug_assert_eq!(self.chunk_state.count(), 0, "no partial chunk data");
1261            debug_assert_eq!(CHUNK_LEN.count_ones(), 1, "power of 2 chunk len");
1262            let mut subtree_len = largest_power_of_two_leq(input.len());
1263            let count_so_far = self.chunk_state.chunk_counter * CHUNK_LEN as u64;
1264            // Shrink the subtree_len until it evenly divides the count so far.
1265            // We know that subtree_len itself is a power of 2, so we can use a
1266            // bitmasking trick instead of an actual remainder operation. (Note
1267            // that if the caller consistently passes power-of-2 inputs of the
1268            // same size, as is hopefully typical, this loop condition will
1269            // always fail, and subtree_len will always be the full length of
1270            // the input.)
1271            //
1272            // An aside: We don't have to shrink subtree_len quite this much.
1273            // For example, if count_so_far is 1, we could pass 2 chunks to
1274            // compress_subtree_to_parent_node. Since we'll get 2 CVs back,
1275            // we'll still get the right answer in the end, and we might get to
1276            // use 2-way SIMD parallelism. The problem with this optimization,
1277            // is that it gets us stuck always hashing 2 chunks. The total
1278            // number of chunks will remain odd, and we'll never graduate to
1279            // higher degrees of parallelism. See
1280            // https://github.com/BLAKE3-team/BLAKE3/issues/69.
1281            while (subtree_len - 1) as u64 & count_so_far != 0 {
1282                subtree_len /= 2;
1283            }
1284            // The shrunken subtree_len might now be 1 chunk long. If so, hash
1285            // that one chunk by itself. Otherwise, compress the subtree into a
1286            // pair of CVs.
1287            let subtree_chunks = (subtree_len / CHUNK_LEN) as u64;
1288            if subtree_len <= CHUNK_LEN {
1289                debug_assert_eq!(subtree_len, CHUNK_LEN);
1290                self.push_cv(
1291                    &ChunkState::new(
1292                        &self.key,
1293                        self.chunk_state.chunk_counter,
1294                        self.chunk_state.flags,
1295                        self.chunk_state.platform,
1296                    )
1297                    .update(&input[..subtree_len])
1298                    .output()
1299                    .chaining_value(),
1300                    self.chunk_state.chunk_counter,
1301                );
1302            } else {
1303                // This is the high-performance happy path, though getting here
1304                // depends on the caller giving us a long enough input.
1305                let cv_pair = compress_subtree_to_parent_node::<J>(
1306                    &input[..subtree_len],
1307                    &self.key,
1308                    self.chunk_state.chunk_counter,
1309                    self.chunk_state.flags,
1310                    self.chunk_state.platform,
1311                );
1312                let left_cv = array_ref!(cv_pair, 0, 32);
1313                let right_cv = array_ref!(cv_pair, 32, 32);
1314                // Push the two CVs we received into the CV stack in order. Because
1315                // the stack merges lazily, this guarantees we aren't merging the
1316                // root.
1317                self.push_cv(left_cv, self.chunk_state.chunk_counter);
1318                self.push_cv(
1319                    right_cv,
1320                    self.chunk_state.chunk_counter + (subtree_chunks / 2),
1321                );
1322            }
1323            self.chunk_state.chunk_counter += subtree_chunks;
1324            input = &input[subtree_len..];
1325        }
1326
1327        // What remains is 1 chunk or less. Add it to the chunk state.
1328        debug_assert!(input.len() <= CHUNK_LEN);
1329        if !input.is_empty() {
1330            self.chunk_state.update(input);
1331            // Having added some input to the chunk_state, we know what's in
1332            // the CV stack won't become the root node, and we can do an extra
1333            // merge. This simplifies finalize().
1334            self.merge_cv_stack(self.chunk_state.chunk_counter);
1335        }
1336
1337        self
1338    }
1339
1340    fn final_output(&self) -> Output {
1341        // If the current chunk is the only chunk, that makes it the root node
1342        // also. Convert it directly into an Output. Otherwise, we need to
1343        // merge subtrees below.
1344        if self.cv_stack.is_empty() {
1345            debug_assert_eq!(self.chunk_state.chunk_counter, self.initial_chunk_counter);
1346            return self.chunk_state.output();
1347        }
1348
1349        // If there are any bytes in the ChunkState, finalize that chunk and
1350        // merge its CV with everything in the CV stack. In that case, the work
1351        // we did at the end of update() above guarantees that the stack
1352        // doesn't contain any unmerged subtrees that need to be merged first.
1353        // (This is important, because if there were two chunk hashes sitting
1354        // on top of the stack, they would need to merge with each other, and
1355        // merging a new chunk hash into them would be incorrect.)
1356        //
1357        // If there are no bytes in the ChunkState, we'll merge what's already
1358        // in the stack. In this case it's fine if there are unmerged chunks on
1359        // top, because we'll merge them with each other. Note that the case of
1360        // the empty chunk is taken care of above.
1361        let mut output: Output;
1362        let mut num_cvs_remaining = self.cv_stack.len();
1363        if self.chunk_state.count() > 0 {
1364            debug_assert_eq!(
1365                self.cv_stack.len(),
1366                (self.chunk_state.chunk_counter - self.initial_chunk_counter).count_ones() as usize,
1367                "cv stack does not need a merge",
1368            );
1369            output = self.chunk_state.output();
1370        } else {
1371            debug_assert!(self.cv_stack.len() >= 2);
1372            output = parent_node_output(
1373                &self.cv_stack[num_cvs_remaining - 2],
1374                &self.cv_stack[num_cvs_remaining - 1],
1375                &self.key,
1376                self.chunk_state.flags,
1377                self.chunk_state.platform,
1378            );
1379            num_cvs_remaining -= 2;
1380        }
1381        while num_cvs_remaining > 0 {
1382            output = parent_node_output(
1383                &self.cv_stack[num_cvs_remaining - 1],
1384                &output.chaining_value(),
1385                &self.key,
1386                self.chunk_state.flags,
1387                self.chunk_state.platform,
1388            );
1389            num_cvs_remaining -= 1;
1390        }
1391        output
1392    }
1393
1394    /// Finalize the hash state and return the [`Hash`](struct.Hash.html) of
1395    /// the input.
1396    ///
1397    /// This method is idempotent. Calling it twice will give the same result.
1398    /// You can also add more input and finalize again.
1399    pub fn finalize(&self) -> Hash {
1400        assert_eq!(
1401            self.initial_chunk_counter, 0,
1402            "set_input_offset must be used with finalize_non_root",
1403        );
1404        self.final_output().root_hash()
1405    }
1406
1407    /// Finalize the hash state and return an [`OutputReader`], which can
1408    /// supply any number of output bytes.
1409    ///
1410    /// This method is idempotent. Calling it twice will give the same result.
1411    /// You can also add more input and finalize again.
1412    ///
1413    /// [`OutputReader`]: struct.OutputReader.html
1414    pub fn finalize_xof(&self) -> OutputReader {
1415        assert_eq!(
1416            self.initial_chunk_counter, 0,
1417            "set_input_offset must be used with finalize_non_root",
1418        );
1419        OutputReader::new(self.final_output())
1420    }
1421
1422    /// Return the total number of bytes hashed so far.
1423    ///
1424    /// [`hazmat::HasherExt::set_input_offset`] does not affect this value. This only counts bytes
1425    /// passed to [`update`](Hasher::update).
1426    pub fn count(&self) -> u64 {
1427        // Account for non-zero cases of Hasher::set_input_offset. Note that initial_chunk_counter
1428        // is always 0 for callers who don't use the hazmat module.
1429        (self.chunk_state.chunk_counter - self.initial_chunk_counter) * CHUNK_LEN as u64
1430            + self.chunk_state.count() as u64
1431    }
1432
1433    /// As [`update`](Hasher::update), but reading from a
1434    /// [`std::io::Read`](https://doc.rust-lang.org/std/io/trait.Read.html) implementation.
1435    ///
1436    /// [`Hasher`] implements
1437    /// [`std::io::Write`](https://doc.rust-lang.org/std/io/trait.Write.html), so it's possible to
1438    /// use [`std::io::copy`](https://doc.rust-lang.org/std/io/fn.copy.html) to update a [`Hasher`]
1439    /// from any reader. Unfortunately, this standard approach can limit performance, because
1440    /// `copy` currently uses an internal 8 KiB buffer that isn't big enough to take advantage of
1441    /// all SIMD instruction sets. (In particular, [AVX-512](https://en.wikipedia.org/wiki/AVX-512)
1442    /// needs a 16 KiB buffer.) `update_reader` avoids this performance problem and is slightly
1443    /// more convenient.
1444    ///
1445    /// The internal buffer size this method uses may change at any time, and it may be different
1446    /// for different targets. The only guarantee is that it will be large enough for all of this
1447    /// crate's SIMD implementations on the current platform.
1448    ///
1449    /// The most common implementer of
1450    /// [`std::io::Read`](https://doc.rust-lang.org/std/io/trait.Read.html) might be
1451    /// [`std::fs::File`](https://doc.rust-lang.org/std/fs/struct.File.html), but note that memory
1452    /// mapping can be faster than this method for hashing large files. See
1453    /// [`update_mmap`](Hasher::update_mmap) and [`update_mmap_rayon`](Hasher::update_mmap_rayon),
1454    /// which require the `mmap` and (for the latter) `rayon` Cargo features.
1455    ///
1456    /// This method requires the `std` Cargo feature, which is enabled by default.
1457    ///
1458    /// # Example
1459    ///
1460    /// ```no_run
1461    /// # use std::fs::File;
1462    /// # use std::io;
1463    /// # fn main() -> io::Result<()> {
1464    /// // Hash standard input.
1465    /// let mut hasher = blake3::Hasher::new();
1466    /// hasher.update_reader(std::io::stdin().lock())?;
1467    /// println!("{}", hasher.finalize());
1468    /// # Ok(())
1469    /// # }
1470    /// ```
1471    #[cfg(feature = "std")]
1472    pub fn update_reader(&mut self, reader: impl std::io::Read) -> std::io::Result<&mut Self> {
1473        io::copy_wide(reader, self)?;
1474        Ok(self)
1475    }
1476
1477    /// As [`update`](Hasher::update), but using Rayon-based multithreading
1478    /// internally.
1479    ///
1480    /// This method is gated by the `rayon` Cargo feature, which is disabled by
1481    /// default but enabled on [docs.rs](https://docs.rs).
1482    ///
1483    /// To get any performance benefit from multithreading, the input buffer
1484    /// needs to be large. As a rule of thumb on x86_64, `update_rayon` is
1485    /// _slower_ than `update` for inputs under 128 KiB. That threshold varies
1486    /// quite a lot across different processors, and it's important to benchmark
1487    /// your specific use case. See also the performance warning associated with
1488    /// [`update_mmap_rayon`](Hasher::update_mmap_rayon).
1489    ///
1490    /// If you already have a large buffer in memory, and you want to hash it
1491    /// with multiple threads, this method is a good option. However, reading a
1492    /// file into memory just to call this method can be a performance mistake,
1493    /// both because it requires lots of memory and because single-threaded
1494    /// reads can be slow. For hashing whole files, see
1495    /// [`update_mmap_rayon`](Hasher::update_mmap_rayon), which is gated by both
1496    /// the `rayon` and `mmap` Cargo features.
1497    #[cfg(feature = "rayon")]
1498    pub fn update_rayon(&mut self, input: &[u8]) -> &mut Self {
1499        self.update_with_join::<join::RayonJoin>(input)
1500    }
1501
1502    /// As [`update`](Hasher::update), but reading the contents of a file using memory mapping.
1503    ///
1504    /// Not all files can be memory mapped, and memory mapping small files can be slower than
1505    /// reading them the usual way. In those cases, this method will fall back to standard file IO.
1506    /// The heuristic for whether to use memory mapping is currently very simple (file size >=
1507    /// 16 KiB), and it might change at any time.
1508    ///
1509    /// Like [`update`](Hasher::update), this method is single-threaded. In this author's
1510    /// experience, memory mapping improves single-threaded performance by ~10% for large files
1511    /// that are already in cache. This probably varies between platforms, and as always it's a
1512    /// good idea to benchmark your own use case. In comparison, the multithreaded
1513    /// [`update_mmap_rayon`](Hasher::update_mmap_rayon) method can have a much larger impact on
1514    /// performance.
1515    ///
1516    /// There's a correctness reason that this method takes
1517    /// [`Path`](https://doc.rust-lang.org/stable/std/path/struct.Path.html) instead of
1518    /// [`File`](https://doc.rust-lang.org/std/fs/struct.File.html): reading from a memory-mapped
1519    /// file ignores the seek position of the original file handle (it neither respects the current
1520    /// position nor updates the position). This difference in behavior would've caused
1521    /// `update_mmap` and [`update_reader`](Hasher::update_reader) to give different answers and
1522    /// have different side effects in some cases. Taking a
1523    /// [`Path`](https://doc.rust-lang.org/stable/std/path/struct.Path.html) avoids this problem by
1524    /// making it clear that a new [`File`](https://doc.rust-lang.org/std/fs/struct.File.html) is
1525    /// opened internally.
1526    ///
1527    /// This method requires the `mmap` Cargo feature, which is disabled by default but enabled on
1528    /// [docs.rs](https://docs.rs).
1529    ///
1530    /// # Example
1531    ///
1532    /// ```no_run
1533    /// # use std::io;
1534    /// # use std::path::Path;
1535    /// # fn main() -> io::Result<()> {
1536    /// let path = Path::new("file.dat");
1537    /// let mut hasher = blake3::Hasher::new();
1538    /// hasher.update_mmap(path)?;
1539    /// println!("{}", hasher.finalize());
1540    /// # Ok(())
1541    /// # }
1542    /// ```
1543    #[cfg(feature = "mmap")]
1544    pub fn update_mmap(&mut self, path: impl AsRef<std::path::Path>) -> std::io::Result<&mut Self> {
1545        let mut file = std::fs::File::open(path.as_ref())?;
1546        if let Some(mmap) = io::maybe_mmap_file(&mut file)? {
1547            self.update(&mmap);
1548        } else {
1549            io::copy_wide(&file, self)?;
1550        }
1551        Ok(self)
1552    }
1553
1554    /// As [`update_rayon`](Hasher::update_rayon), but reading the contents of a file using
1555    /// memory mapping. This is the default behavior of `b3sum`.
1556    ///
1557    /// For large files that are likely to be in cache, this can be much faster than
1558    /// single-threaded hashing. When benchmarks report that BLAKE3 is 10x or 20x faster than other
1559    /// cryptographic hashes, this is usually what they're measuring. However...
1560    ///
1561    /// **Performance Warning:** There are cases where multithreading hurts performance. The worst
1562    /// case is [a large file on a spinning disk](https://github.com/BLAKE3-team/BLAKE3/issues/31),
1563    /// where simultaneous reads from multiple threads can cause "thrashing" (i.e. the disk spends
1564    /// more time seeking around than reading data). Windows tends to be somewhat worse about this,
1565    /// in part because it's less likely than Linux to keep very large files in cache. More
1566    /// generally, if your CPU cores are already busy, then multithreading will add overhead
1567    /// without improving performance. If your code runs in different environments that you don't
1568    /// control and can't measure, then unfortunately there's no one-size-fits-all answer for
1569    /// whether multithreading is a good idea.
1570    ///
1571    /// The memory mapping behavior of this function is the same as
1572    /// [`update_mmap`](Hasher::update_mmap), and the heuristic for when to fall back to standard
1573    /// file IO might change at any time.
1574    ///
1575    /// This method requires both the `mmap` and `rayon` Cargo features, which are disabled by
1576    /// default but enabled on [docs.rs](https://docs.rs).
1577    ///
1578    /// # Example
1579    ///
1580    /// ```no_run
1581    /// # use std::io;
1582    /// # use std::path::Path;
1583    /// # fn main() -> io::Result<()> {
1584    /// # #[cfg(feature = "rayon")]
1585    /// # {
1586    /// let path = Path::new("big_file.dat");
1587    /// let mut hasher = blake3::Hasher::new();
1588    /// hasher.update_mmap_rayon(path)?;
1589    /// println!("{}", hasher.finalize());
1590    /// # }
1591    /// # Ok(())
1592    /// # }
1593    /// ```
1594    #[cfg(feature = "mmap")]
1595    #[cfg(feature = "rayon")]
1596    pub fn update_mmap_rayon(
1597        &mut self,
1598        path: impl AsRef<std::path::Path>,
1599    ) -> std::io::Result<&mut Self> {
1600        let mut file = std::fs::File::open(path.as_ref())?;
1601        if let Some(mmap) = io::maybe_mmap_file(&mut file)? {
1602            self.update_rayon(&mmap);
1603        } else {
1604            io::copy_wide(&file, self)?;
1605        }
1606        Ok(self)
1607    }
1608}
1609
1610// Don't derive(Debug), because the state may be secret.
1611impl fmt::Debug for Hasher {
1612    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1613        f.debug_struct("Hasher")
1614            .field("flags", &self.chunk_state.flags)
1615            .field("platform", &self.chunk_state.platform)
1616            .finish()
1617    }
1618}
1619
1620impl Default for Hasher {
1621    #[inline]
1622    fn default() -> Self {
1623        Self::new()
1624    }
1625}
1626
1627#[cfg(feature = "std")]
1628impl std::io::Write for Hasher {
1629    /// This is equivalent to [`update`](#method.update).
1630    #[inline]
1631    fn write(&mut self, input: &[u8]) -> std::io::Result<usize> {
1632        self.update(input);
1633        Ok(input.len())
1634    }
1635
1636    #[inline]
1637    fn flush(&mut self) -> std::io::Result<()> {
1638        Ok(())
1639    }
1640}
1641
1642#[cfg(feature = "zeroize")]
1643impl Zeroize for Hasher {
1644    fn zeroize(&mut self) {
1645        // Destructuring to trigger compile error as a reminder to update this impl.
1646        let Self {
1647            key,
1648            chunk_state,
1649            initial_chunk_counter,
1650            cv_stack,
1651        } = self;
1652
1653        key.zeroize();
1654        chunk_state.zeroize();
1655        initial_chunk_counter.zeroize();
1656        cv_stack.zeroize();
1657    }
1658}
1659
1660/// An incremental reader for extended output, returned by
1661/// [`Hasher::finalize_xof`](struct.Hasher.html#method.finalize_xof).
1662///
1663/// Shorter BLAKE3 outputs are prefixes of longer ones, and explicitly requesting a short output is
1664/// equivalent to truncating the default-length output. Note that this is a difference between
1665/// BLAKE2 and BLAKE3.
1666///
1667/// # Security notes
1668///
1669/// Outputs shorter than the default length of 32 bytes (256 bits) provide less security. An N-bit
1670/// BLAKE3 output is intended to provide N bits of first and second preimage resistance and N/2
1671/// bits of collision resistance, for any N up to 256. Longer outputs don't provide any additional
1672/// security.
1673///
1674/// Avoid relying on the secrecy of the output offset, that is, the number of output bytes read or
1675/// the arguments to [`seek`](struct.OutputReader.html#method.seek) or
1676/// [`set_position`](struct.OutputReader.html#method.set_position). [_Block-Cipher-Based Tree
1677/// Hashing_ by Aldo Gunsing](https://eprint.iacr.org/2022/283) shows that an attacker who knows
1678/// both the message and the key (if any) can easily determine the offset of an extended output.
1679/// For comparison, AES-CTR has a similar property: if you know the key, you can decrypt a block
1680/// from an unknown position in the output stream to recover its block index. Callers with strong
1681/// secret keys aren't affected in practice, but secret offsets are a [design
1682/// smell](https://en.wikipedia.org/wiki/Design_smell) in any case.
1683#[derive(Clone)]
1684pub struct OutputReader {
1685    inner: Output,
1686    position_within_block: u8,
1687}
1688
1689impl OutputReader {
1690    fn new(inner: Output) -> Self {
1691        Self {
1692            inner,
1693            position_within_block: 0,
1694        }
1695    }
1696
1697    // This helper function handles both the case where the output buffer is
1698    // shorter than one block, and the case where our position_within_block is
1699    // non-zero.
1700    fn fill_one_block(&mut self, buf: &mut &mut [u8]) {
1701        let output_block: [u8; BLOCK_LEN] = self.inner.root_output_block();
1702        let output_bytes = &output_block[self.position_within_block as usize..];
1703        let take = cmp::min(buf.len(), output_bytes.len());
1704        buf[..take].copy_from_slice(&output_bytes[..take]);
1705        self.position_within_block += take as u8;
1706        if self.position_within_block == BLOCK_LEN as u8 {
1707            self.inner.counter += 1;
1708            self.position_within_block = 0;
1709        }
1710        // Advance the dest buffer. mem::take() is a borrowck workaround.
1711        *buf = &mut core::mem::take(buf)[take..];
1712    }
1713
1714    /// Fill a buffer with output bytes and advance the position of the
1715    /// `OutputReader`. This is equivalent to [`Read::read`], except that it
1716    /// doesn't return a `Result`. Both methods always fill the entire buffer.
1717    ///
1718    /// Note that `OutputReader` doesn't buffer output bytes internally, so
1719    /// calling `fill` repeatedly with a short-length or odd-length slice will
1720    /// end up performing the same compression multiple times. If you're
1721    /// reading output in a loop, prefer a slice length that's a multiple of
1722    /// [`BLOCK_LEN`] (64 bytes).
1723    ///
1724    /// The maximum output size of BLAKE3 is 2<sup>64</sup>-1 bytes. If you try
1725    /// to extract more than that, for example by seeking near the end and
1726    /// reading further, the behavior is unspecified.
1727    ///
1728    /// [`Read::read`]: #method.read
1729    pub fn fill(&mut self, mut buf: &mut [u8]) {
1730        if buf.is_empty() {
1731            return;
1732        }
1733
1734        // If we're partway through a block, try to get to a block boundary.
1735        if self.position_within_block != 0 {
1736            self.fill_one_block(&mut buf);
1737        }
1738
1739        let full_blocks = buf.len() / BLOCK_LEN;
1740        let full_blocks_len = full_blocks * BLOCK_LEN;
1741        if full_blocks > 0 {
1742            debug_assert_eq!(0, self.position_within_block);
1743            self.inner.platform.xof_many(
1744                &self.inner.input_chaining_value,
1745                &self.inner.block,
1746                self.inner.block_len,
1747                self.inner.counter,
1748                self.inner.flags | ROOT,
1749                &mut buf[..full_blocks_len],
1750            );
1751            self.inner.counter += full_blocks as u64;
1752            buf = &mut buf[full_blocks * BLOCK_LEN..];
1753        }
1754
1755        if !buf.is_empty() {
1756            debug_assert!(buf.len() < BLOCK_LEN);
1757            self.fill_one_block(&mut buf);
1758            debug_assert!(buf.is_empty());
1759        }
1760    }
1761
1762    /// Return the current read position in the output stream. This is
1763    /// equivalent to [`Seek::stream_position`], except that it doesn't return
1764    /// a `Result`. The position of a new `OutputReader` starts at 0, and each
1765    /// call to [`fill`] or [`Read::read`] moves the position forward by the
1766    /// number of bytes read.
1767    ///
1768    /// [`Seek::stream_position`]: #method.stream_position
1769    /// [`fill`]: #method.fill
1770    /// [`Read::read`]: #method.read
1771    pub fn position(&self) -> u64 {
1772        self.inner.counter * BLOCK_LEN as u64 + self.position_within_block as u64
1773    }
1774
1775    /// Seek to a new read position in the output stream. This is equivalent to
1776    /// calling [`Seek::seek`] with [`SeekFrom::Start`], except that it doesn't
1777    /// return a `Result`.
1778    ///
1779    /// [`Seek::seek`]: #method.seek
1780    /// [`SeekFrom::Start`]: https://doc.rust-lang.org/std/io/enum.SeekFrom.html
1781    pub fn set_position(&mut self, position: u64) {
1782        self.position_within_block = (position % BLOCK_LEN as u64) as u8;
1783        self.inner.counter = position / BLOCK_LEN as u64;
1784    }
1785}
1786
1787// Don't derive(Debug), because the state may be secret.
1788impl fmt::Debug for OutputReader {
1789    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1790        f.debug_struct("OutputReader")
1791            .field("position", &self.position())
1792            .finish()
1793    }
1794}
1795
1796#[cfg(feature = "std")]
1797impl std::io::Read for OutputReader {
1798    #[inline]
1799    fn read(&mut self, buf: &mut [u8]) -> std::io::Result<usize> {
1800        self.fill(buf);
1801        Ok(buf.len())
1802    }
1803}
1804
1805#[cfg(feature = "std")]
1806impl std::io::Seek for OutputReader {
1807    fn seek(&mut self, pos: std::io::SeekFrom) -> std::io::Result<u64> {
1808        let max_position = u64::max_value() as i128;
1809        let target_position: i128 = match pos {
1810            std::io::SeekFrom::Start(x) => x as i128,
1811            std::io::SeekFrom::Current(x) => self.position() as i128 + x as i128,
1812            std::io::SeekFrom::End(_) => {
1813                return Err(std::io::Error::new(
1814                    std::io::ErrorKind::InvalidInput,
1815                    "seek from end not supported",
1816                ));
1817            }
1818        };
1819        if target_position < 0 {
1820            return Err(std::io::Error::new(
1821                std::io::ErrorKind::InvalidInput,
1822                "seek before start",
1823            ));
1824        }
1825        self.set_position(cmp::min(target_position, max_position) as u64);
1826        Ok(self.position())
1827    }
1828}
1829
1830#[cfg(feature = "zeroize")]
1831impl Zeroize for OutputReader {
1832    fn zeroize(&mut self) {
1833        // Destructuring to trigger compile error as a reminder to update this impl.
1834        let Self {
1835            inner,
1836            position_within_block,
1837        } = self;
1838
1839        inner.zeroize();
1840        position_within_block.zeroize();
1841    }
1842}