Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Use Blake3's extendable output function #216

Merged
merged 4 commits into from
May 19, 2022
Merged
Show file tree
Hide file tree
Changes from 2 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
17 changes: 12 additions & 5 deletions src/hasher_impl.rs
Original file line number Diff line number Diff line change
Expand Up @@ -102,6 +102,14 @@ pub mod blake3 {
digest: [u8; S],
}

impl<const S: usize> Blake3Hasher<S> {
/// using blake3's XOF function, fills the given slice with hash output
pub fn finalize_xof_fill(&mut self, digest_out: &mut [u8]) {
let mut digest = self.hasher.finalize_xof();
digest.fill(digest_out)
}
}

impl<const S: usize> Default for Blake3Hasher<S> {
fn default() -> Self {
let hasher = ::blake3::Hasher::new();
Expand All @@ -119,11 +127,10 @@ pub mod blake3 {
}

fn finalize(&mut self) -> &[u8] {
let digest = self.hasher.finalize(); //default is 32 bytes anyway
let digest_bytes = digest.as_bytes();
let digest_out = &mut self.digest[..digest_bytes.len().max(S)];
digest_out.copy_from_slice(digest_bytes);
digest_out
let Blake3Hasher { hasher, digest } = self;
mriise marked this conversation as resolved.
Show resolved Hide resolved
let mut output = hasher.finalize_xof();
output.fill(digest);
digest
}

fn reset(&mut self) {
Expand Down
37 changes: 37 additions & 0 deletions tests/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -335,3 +335,40 @@ fn multihash_errors() {
"Should error on wrong hash length"
);
}

#[test]
fn smaller_than_default_digest() {
use multihash::Blake3Hasher;
const DIGEST_SIZE: usize = 16;
pub struct ContentHasher(Blake3Hasher<DIGEST_SIZE>);

pub struct ContentHash([u8; DIGEST_SIZE]);

impl ContentHasher {
fn new() -> ContentHasher {
ContentHasher(Blake3Hasher::default())
}

fn write(&mut self, input: &[u8]) {
self.0.update(input);
}

fn finish(&mut self) -> ContentHash {
let hash = multihash::Code::Blake3_256.wrap(self.0.finalize()).unwrap();
let resized_hash = hash.resize::<DIGEST_SIZE>().unwrap();

let mut content = ContentHash([0u8; DIGEST_SIZE]);
content.0.copy_from_slice(resized_hash.digest());
content
}

fn reset(&mut self) {
self.0.reset();
}
}

let mut hasher = ContentHasher::new();
hasher.write("foobar".as_bytes());
let _content_hash = hasher.finish();
hasher.reset();
mriise marked this conversation as resolved.
Show resolved Hide resolved
}