light_hasher/
data_hasher.rs

1use crate::HasherError;
2
3pub trait DataHasher {
4    fn hash<H: crate::Hasher>(&self) -> Result<[u8; 32], HasherError>;
5}
6
7macro_rules! impl_data_hasher_for_array {
8    ($(
9         // For each array, specify the length and then a bracketed list of indices.
10         $len:literal => [$($index:tt),* $(,)?]
11    )*) => {
12        $(
13            impl<T: DataHasher + Default> DataHasher for [T; $len] {
14                fn hash<H: crate::Hasher>(&self) -> Result<[u8; 32], HasherError> {
15                    // We call T’s hash on each element and then pass the resulting list to H::hash.
16                    H::hashv(&[$( &self[$index].hash::<H>()?.as_slice() ),*])
17                }
18            }
19        )*
20    }
21}
22
23impl_data_hasher_for_array! {
24    1 => [0]
25}
26impl_data_hasher_for_array! {
27    2 => [0, 1]
28}
29impl_data_hasher_for_array! {
30    3 => [0, 1, 2]
31}
32impl_data_hasher_for_array! {
33    4 => [0, 1, 2, 3]
34}
35impl_data_hasher_for_array! {
36    5 => [0, 1, 2, 3, 4]
37}
38impl_data_hasher_for_array! {
39    6 => [0, 1, 2, 3, 4, 5]
40}
41impl_data_hasher_for_array! {
42    7 => [0, 1, 2, 3, 4, 5, 6]
43}
44impl_data_hasher_for_array! {
45    8 => [0, 1, 2, 3, 4, 5, 6, 7]
46}
47impl_data_hasher_for_array! {
48    9 => [0, 1, 2, 3, 4, 5, 6, 7, 8]
49}
50impl_data_hasher_for_array! {
51    10 => [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
52}
53impl_data_hasher_for_array! {
54    11 => [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
55}
56impl_data_hasher_for_array! {
57    12 => [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11]
58}