ez_hash/
hash.rs

1#[allow(unused_imports)]
2use crate::Hashable;
3use digest::Digest;
4
5pub trait Hasher {
6    type Output: AsRef<[u8]> + Sized + Copy + Clone + Hashable;
7    fn hash<T: Hashable>(data: T) -> Self::Output;
8    fn zeros() -> Self::Output;
9}
10
11macro_rules! def_hasher {
12    ($crt: ident, $ty: ident, $func:ident, $sz: expr) => {
13        pub struct $ty;
14
15        impl Hasher for $ty {
16            type Output = [u8; $sz];
17            fn hash<T: Hashable>(data: T) -> Self::Output {
18                $func(data)
19            }
20            fn zeros() -> Self::Output {
21                [0; $sz]
22            }
23        }
24
25        pub fn $func<T: Hashable>(data: T) -> [u8; $sz] {
26            use $crt::$ty;
27
28            let mut hasher = $ty::new();
29            data.update_hasher(&mut |bytes| {
30                hasher.update(bytes);
31            });
32            hasher.finalize().into()
33        }
34    };
35}
36
37#[cfg(feature = "md5")]
38def_hasher!(md5, Md5, md5, 16);
39
40#[cfg(feature = "sha2")]
41def_hasher!(sha1, Sha1, sha1, 20);
42#[cfg(feature = "sha2")]
43def_hasher!(sha2, Sha224, sha224, 28);
44#[cfg(feature = "sha2")]
45def_hasher!(sha2, Sha256, sha256, 32);
46#[cfg(feature = "sha2")]
47def_hasher!(sha2, Sha384, sha384, 48);
48#[cfg(feature = "sha2")]
49def_hasher!(sha2, Sha512, sha512, 64);
50#[cfg(feature = "sha2")]
51def_hasher!(sha2, Sha512_224, sha512_224, 28);
52#[cfg(feature = "sha2")]
53def_hasher!(sha2, Sha512_256, sha512_256, 32);
54
55#[cfg(feature = "sha3")]
56def_hasher!(sha3, Sha3_224, sha3_224, 28);
57#[cfg(feature = "sha3")]
58def_hasher!(sha3, Sha3_256, sha3_256, 32);
59#[cfg(feature = "sha3")]
60def_hasher!(sha3, Sha3_384, sha3_384, 48);
61#[cfg(feature = "sha3")]
62def_hasher!(sha3, Sha3_512, sha3_512, 64);
63#[cfg(feature = "sha3")]
64def_hasher!(sha3, Keccak256, keccak256, 32);
65#[cfg(feature = "sha3")]
66def_hasher!(sha3, Keccak512, keccak512, 64);
67
68#[cfg(feature = "blake2")]
69def_hasher!(blake2_helper, Blake2b256, blake2b_256, 32);
70#[cfg(feature = "blake2")]
71def_hasher!(blake2_helper, Blake2b384, blake2b_384, 48);
72#[cfg(feature = "blake2")]
73def_hasher!(blake2_helper, Blake2b512, blake2b_512, 64);
74#[cfg(feature = "blake2")]
75def_hasher!(blake2_helper, Blake2s128, blake2s_128, 16);
76#[cfg(feature = "blake2")]
77def_hasher!(blake2_helper, Blake2s256, blake2s_256, 32);
78
79#[cfg(feature = "blake2")]
80mod blake2_helper {
81    pub type Blake2b256 = blake2::Blake2b<digest::consts::U32>;
82    pub type Blake2b384 = blake2::Blake2b<digest::consts::U48>;
83    pub type Blake2s128 = blake2::Blake2s<digest::consts::U16>;
84    pub type Blake2s256 = blake2::Blake2s256;
85    pub type Blake2b512 = blake2::Blake2b512;
86}
87
88#[cfg(feature = "blake3")]
89pub use blake3_helper::*;
90#[cfg(feature = "blake3")]
91mod blake3_helper;