/home/runner/actions-runner/_work/fuel-vm/fuel-vm/fuel-crypto/src/hasher.rs
Line | Count | Source (jump to first uncovered line) |
1 | | use fuel_types::Bytes32; |
2 | | use sha2::{ |
3 | | digest::Update, |
4 | | Digest, |
5 | | Sha256, |
6 | | }; |
7 | | |
8 | | use core::iter; |
9 | | |
10 | | /// Standard hasher |
11 | | #[derive(Debug, Default, Clone)] |
12 | | pub struct Hasher(Sha256); |
13 | | |
14 | | impl Hasher { |
15 | | /// Length of the output |
16 | | pub const OUTPUT_LEN: usize = Bytes32::LEN; |
17 | | |
18 | | /// Append data to the hasher |
19 | 95.4k | pub fn input<B>(&mut self, data: B) |
20 | 95.4k | where |
21 | 95.4k | B: AsRef<[u8]>, |
22 | 95.4k | { |
23 | 95.4k | sha2::Digest::update(&mut self.0, data) |
24 | 95.4k | } |
25 | | |
26 | | /// Consume, append data and return the hasher |
27 | 469 | pub fn chain<B>(self, data: B) -> Self |
28 | 469 | where |
29 | 469 | B: AsRef<[u8]>, |
30 | 469 | { |
31 | 469 | Self(self.0.chain(data)) |
32 | 469 | } |
33 | | |
34 | | /// Consume, append the items of the iterator and return the hasher |
35 | 5 | pub fn extend_chain<B, I>(mut self, iter: I) -> Self |
36 | 5 | where |
37 | 5 | B: AsRef<[u8]>, |
38 | 5 | I: IntoIterator<Item = B>, |
39 | 5 | { |
40 | 5 | self.extend(iter); |
41 | 5 | |
42 | 5 | self |
43 | 5 | } |
44 | | |
45 | | /// Reset the hasher to the default state |
46 | 0 | pub fn reset(&mut self) { |
47 | 0 | self.0.reset(); |
48 | 0 | } |
49 | | |
50 | | /// Hash the provided data, returning its digest |
51 | 27.1k | pub fn hash<B>(data: B) -> Bytes32 |
52 | 27.1k | where |
53 | 27.1k | B: AsRef<[u8]>, |
54 | 27.1k | { |
55 | 27.1k | let mut hasher = Sha256::new(); |
56 | 27.1k | |
57 | 27.1k | sha2::Digest::update(&mut hasher, data); |
58 | 27.1k | |
59 | 27.1k | <[u8; Bytes32::LEN]>::from(hasher.finalize()).into() |
60 | 27.1k | } |
61 | | |
62 | | /// Consume the hasher, returning the digest |
63 | 43.2k | pub fn finalize(self) -> Bytes32 { |
64 | 43.2k | <[u8; Bytes32::LEN]>::from(self.0.finalize()).into() |
65 | 43.2k | } |
66 | | |
67 | | /// Return the digest without consuming the hasher |
68 | 3.19k | pub fn digest(&self) -> Bytes32 { |
69 | 3.19k | <[u8; Bytes32::LEN]>::from(self.0.clone().finalize()).into() |
70 | 3.19k | } |
71 | | } |
72 | | |
73 | | impl<B> iter::FromIterator<B> for Hasher |
74 | | where |
75 | | B: AsRef<[u8]>, |
76 | | { |
77 | 1 | fn from_iter<T>(iter: T) -> Self |
78 | 1 | where |
79 | 1 | T: IntoIterator<Item = B>, |
80 | 1 | { |
81 | 1 | iter.into_iter().fold(Hasher::default(), Hasher::chain) |
82 | 1 | } |
83 | | } |
84 | | |
85 | | impl<B> Extend<B> for Hasher |
86 | | where |
87 | | B: AsRef<[u8]>, |
88 | | { |
89 | 6 | fn extend<T: IntoIterator<Item = B>>(&mut self, iter: T) { |
90 | 36 | iter.into_iter().for_each(|b| self.input(b)) |
91 | 6 | } |
92 | | } |