atlas_sha256_hasher/
lib.rs

1#![no_std]
2#[cfg(all(feature = "sha2", not(target_os = "atlas")))]
3use sha2::{Digest, Sha256};
4use atlas_hash::Hash;
5
6#[cfg(all(feature = "sha2", not(target_os = "atlas")))]
7#[derive(Clone, Default)]
8pub struct Hasher {
9    hasher: Sha256,
10}
11
12#[cfg(all(feature = "sha2", not(target_os = "atlas")))]
13impl Hasher {
14    pub fn hash(&mut self, val: &[u8]) {
15        self.hasher.update(val);
16    }
17    pub fn hashv(&mut self, vals: &[&[u8]]) {
18        for val in vals {
19            self.hash(val);
20        }
21    }
22    pub fn result(self) -> Hash {
23        let bytes: [u8; atlas_hash::HASH_BYTES] = self.hasher.finalize().into();
24        bytes.into()
25    }
26}
27
28#[cfg(target_os = "atlas")]
29pub use atlas_define_syscall::definitions::sol_sha256;
30
31/// Return a Sha256 hash for the given data.
32pub fn hashv(vals: &[&[u8]]) -> Hash {
33    // Perform the calculation inline, calling this from within a program is
34    // not supported
35    #[cfg(not(target_os = "atlas"))]
36    {
37        #[cfg(feature = "sha2")]
38        {
39            let mut hasher = Hasher::default();
40            hasher.hashv(vals);
41            hasher.result()
42        }
43        #[cfg(not(feature = "sha2"))]
44        {
45            core::hint::black_box(vals);
46            panic!("hashv is only available on target `atlas` or with the `sha2` feature enabled on this crate")
47        }
48    }
49    // Call via a system call to perform the calculation
50    #[cfg(target_os = "atlas")]
51    {
52        let mut hash_result = [0; atlas_hash::HASH_BYTES];
53        unsafe {
54            sol_sha256(
55                vals as *const _ as *const u8,
56                vals.len() as u64,
57                &mut hash_result as *mut _ as *mut u8,
58            );
59        }
60        Hash::new_from_array(hash_result)
61    }
62}
63
64/// Return a Sha256 hash for the given data.
65pub fn hash(val: &[u8]) -> Hash {
66    hashv(&[val])
67}