Add NBytesHasher custom hasher
This commit is contained in:
parent
c7ef422cbe
commit
70c015f73d
3 changed files with 54 additions and 0 deletions
1
libimagref/src/hashers/mod.rs
Normal file
1
libimagref/src/hashers/mod.rs
Normal file
|
@ -0,0 +1 @@
|
|||
pub mod nbytes;
|
52
libimagref/src/hashers/nbytes.rs
Normal file
52
libimagref/src/hashers/nbytes.rs
Normal file
|
@ -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())
|
||||
}
|
||||
|
||||
}
|
||||
|
|
@ -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;
|
||||
|
|
Loading…
Reference in a new issue