filehasher/
filehasher.rs

1use std::{
2    hash::{DefaultHasher, Hasher},
3    io::{Error, Read, Seek, SeekFrom, Write},
4};
5
6/// * File hasher to calculate the hash for a section of a file, the hash is `u64` size. The `Write` trait was implemented for it.
7#[derive(Debug, Clone)]
8pub struct FileHasher {
9    hasher: DefaultHasher,
10}
11
12impl FileHasher {
13    pub fn new() -> Self {
14        Self {
15            hasher: DefaultHasher::new(),
16        }
17    }
18
19    /// * Calculate the hash of the data from the `reader` with offset `from_byte` and length `length`
20    pub fn hash<R>(&mut self, reader: &mut R, from_byte: u64, length: u64) -> Result<u64, Error>
21    where
22        R: Read + Seek,
23    {
24        reader.seek(SeekFrom::Start(from_byte))?;
25        io_utils::copy(reader, self, length)?;
26        Ok(self.hasher.finish())
27    }
28}
29
30impl Write for FileHasher {
31    fn write(&mut self, buf: &[u8]) -> Result<usize, Error> {
32        self.hasher.write(buf);
33        Ok(buf.len())
34    }
35
36    fn flush(&mut self) -> Result<(), Error> {
37        Ok(())
38    }
39}
40
41impl Default for FileHasher {
42    fn default() -> Self {
43        Self::new()
44    }
45}