defuse_near_utils/
digest.rs

1use digest::{FixedOutput, HashMarker, OutputSizeUser, Update, consts::U32};
2use near_sdk::env;
3
4#[derive(Debug, Clone, Default)]
5pub struct Sha256 {
6    data: Vec<u8>,
7}
8
9impl Update for Sha256 {
10    #[inline]
11    fn update(&mut self, data: &[u8]) {
12        self.data.extend(data);
13    }
14}
15
16impl OutputSizeUser for Sha256 {
17    type OutputSize = U32;
18}
19
20impl FixedOutput for Sha256 {
21    #[inline]
22    fn finalize_into(self, out: &mut digest::Output<Self>) {
23        *out = self.finalize_fixed();
24    }
25
26    #[inline]
27    fn finalize_fixed(self) -> digest::Output<Self> {
28        env::sha256_array(&self.data).into()
29    }
30}
31
32impl HashMarker for Sha256 {}
33
34#[cfg(test)]
35mod tests {
36    use defuse_test_utils::random::random_bytes;
37    use digest::Digest;
38    use near_sdk::CryptoHash;
39    use rstest::rstest;
40
41    use super::*;
42
43    #[rstest]
44    fn digest(random_bytes: Vec<u8>) {
45        let got: CryptoHash = Sha256::digest(&random_bytes).into();
46        assert_eq!(got, env::sha256_array(&random_bytes));
47    }
48}