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

Add Digest::input_hashable method #333

Open
wants to merge 3 commits into
base: master
Choose a base branch
from
Open
Changes from all 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
31 changes: 31 additions & 0 deletions src/digest.rs
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,27 @@
// except according to those terms.

use std::iter::repeat;
use std::hash::{Hash, Hasher};

/*
* The purpose of this type is to implement `Hasher` so that it can extract data from any type
* which implements `Hash` and write the data to a `Digest`. This type is private to this module
* and used to implement the `input_hashable` method.
*/
struct DigestHasher<'a, T: 'a + ?Sized> {
digest: &'a mut T,
}

impl<'a, T: ?Sized + Digest> Hasher for DigestHasher<'a, T> {
fn finish(&self) -> u64 {
// This should never be called.
panic!()
}

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

/**
* The Digest trait specifies an interface common to digest functions, such as SHA-1 and the SHA-2
Expand Down Expand Up @@ -78,4 +99,14 @@ pub trait Digest {
self.result(&mut buf);
buf[..].to_hex()
}

/**
* Provide data from anything that implements `Hash`.
*/
fn input_hashable<H: Hash>(&mut self, hashable: &H) {
let mut digest_hasher = DigestHasher {
digest: self,
};
hashable.hash(&mut digest_hasher);
}
}