diff options
author | Matthias Beyer <mail@beyermatthias.de> | 2016-08-11 13:05:23 +0200 |
---|---|---|
committer | Matthias Beyer <mail@beyermatthias.de> | 2016-08-23 12:46:02 +0200 |
commit | 70c015f73d56896acebcf66eb38ba618bbf01e8e (patch) | |
tree | 75c1bfe2ee392adaa2d2f6f5d0761a6b6f19d3a2 /libimagref | |
parent | c7ef422cbe0f0d87dad4a4e6c6cd8562524f2a11 (diff) |
Add NBytesHasher custom hasher
Diffstat (limited to 'libimagref')
-rw-r--r-- | libimagref/src/hashers/mod.rs | 1 | ||||
-rw-r--r-- | libimagref/src/hashers/nbytes.rs | 52 | ||||
-rw-r--r-- | libimagref/src/lib.rs | 1 |
3 files changed, 54 insertions, 0 deletions
diff --git a/libimagref/src/hashers/mod.rs b/libimagref/src/hashers/mod.rs new file mode 100644 index 00000000..c5c49799 --- /dev/null +++ b/libimagref/src/hashers/mod.rs @@ -0,0 +1 @@ +pub mod nbytes; diff --git a/libimagref/src/hashers/nbytes.rs b/libimagref/src/hashers/nbytes.rs new file mode 100644 index 00000000..66af0297 --- /dev/null +++ b/libimagref/src/hashers/nbytes.rs @@ -0,0 +1,52 @@ +use std::io::Read; +use std::path::PathBuf; +use std::result::Result as RResult; + +use crypto::sha1::Sha1; +use crypto::digest::Digest; + +use libimagerror::into::IntoError; + +use hasher::Hasher; +use result::Result; +use error::RefErrorKind as REK; +use error::MapErrInto; + +pub struct NBytesHasher { + hasher: Sha1, + n: usize, +} + +impl NBytesHasher { + + pub fn new(n: usize) -> NBytesHasher { + NBytesHasher { + hasher: Sha1::new(), + n: n, + } + } + +} + +impl Hasher for NBytesHasher { + + fn hash_name(&self) -> &'static str { + "n-bytes-hasher" + } + + fn create_hash<R: Read>(&mut self, _: &PathBuf, contents: &mut R) -> Result<String> { + let s = contents + .bytes() + .take(self.n) + .collect::<RResult<Vec<u8>, _>>() + .map_err_into(REK::IOError) + .and_then(|v| String::from_utf8(v).map_err_into(REK::IOError)) + .map_err(Box::new) + .map_err(|e| REK::UTF8Error.into_error_with_cause(e)) + .map_err_into(REK::IOError); + self.hasher.input_str(&try!(s)[..]); + Ok(self.hasher.result_str()) + } + +} + diff --git a/libimagref/src/lib.rs b/libimagref/src/lib.rs index 79be27bd..bcdaf36d 100644 --- a/libimagref/src/lib.rs +++ b/libimagref/src/lib.rs @@ -30,6 +30,7 @@ module_entry_path_mod!("ref", "0.2.0"); pub mod error; pub mod flags; pub mod hasher; +pub mod hashers; pub mod lister; pub mod reference; pub mod result; |