scsys_crypto/hash/traits/
hasher.rs

1/*
2    Appellation: hasher <module>
3    Contrib: @FL03
4*/
5
6/// A [`Hasher`] defines a common interface for defining specific hashing algorithm.
7pub trait Hasher {
8    /// the output type of the hasher
9    type Output;
10    /// reset the hasher to its initial state
11    fn clean(&mut self) -> &mut Self;
12    /// finalize the hash and return the result
13    fn finish(&self) -> crate::Result<Self::Output>;
14    /// update the hasher with new data
15    fn include(&mut self, data: impl AsRef<[u8]>) -> &mut Self;
16}
17
18/*
19 ************* Implementations *************
20*/
21#[cfg(feature = "blake3")]
22use crate::hash::H256;
23
24#[cfg(feature = "blake3")]
25impl Hasher for blake3::Hasher {
26    type Output = H256;
27
28    fn clean(&mut self) -> &mut Self {
29        self.reset()
30    }
31
32    fn finish(&self) -> crate::Result<Self::Output> {
33        // finalize the `blake3` hasher
34        let hash = self.finalize();
35        // convert the hash into the defined type before returning it
36        Ok(hash.into())
37    }
38
39    fn include(&mut self, data: impl AsRef<[u8]>) -> &mut Self {
40        self.update(data.as_ref())
41    }
42}