solana_atomic_hash/
lib.rs1use std::sync::atomic::{AtomicU64, Ordering};
2
3use solana_hash::Hash;
4
5
6pub struct AtomicHash {
7 inner: [AtomicU64; 4]
8}
9
10impl AtomicHash {
11 #[inline(always)]
12 pub const fn new_const() -> Self {
13 Self {
14 inner: [
15 AtomicU64::new(0),
16 AtomicU64::new(0),
17 AtomicU64::new(0),
18 AtomicU64::new(0),
19 ],
20 }
21 }
22
23 #[inline(always)]
24 pub fn new(hash: &Hash) -> Self {
25 let atomic_hash: Self = Self::new_const();
26 atomic_hash.store(hash, Ordering::Relaxed);
27 atomic_hash
28 }
29
30 #[inline(always)]
31 pub fn store(&self, hash: &Hash, ordering: Ordering) -> () {
32 let hash_bytes: [u8; 32] = hash.to_bytes();
33 for (i, bytes_chunk) in hash_bytes.chunks_exact(8).enumerate() {
34 let val: u64 = u64::from_le_bytes(bytes_chunk.try_into().unwrap());
35 self.inner[i].store(val, ordering);
36 }
37 }
38
39 #[inline(always)]
40 pub fn load(&self, ordering: Ordering) -> Hash {
41 let mut hash_bytes: [u8; 32] = [0u8; 32];
42 for (i, bytes_chunk) in hash_bytes.chunks_exact_mut(8).enumerate() {
43 let val: u64 = self.inner[i].load(ordering);
44 bytes_chunk.copy_from_slice(&val.to_le_bytes());
45 }
46 Hash::new_from_array(hash_bytes)
47 }
48}
49
50#[cfg(test)]
51mod tests {
52 use super::*;
53
54
55 #[test]
56 fn test_store_and_load() -> () {
57 let hash = Hash::from([101; 32]);
58 let atomic_hash = AtomicHash::new(&hash);
59 let hash_after_load = atomic_hash.load(Ordering::Relaxed);
60 assert_eq!(hash, hash_after_load);
61 }
62}