solana-atomic-hash 0.1.0

A lock-free atomic wrapper for Solana Hash, enabling thread-safe concurrent load and store operations.
Documentation
use std::sync::atomic::{AtomicU64, Ordering};

use solana_hash::Hash;


pub struct AtomicHash {
    inner: [AtomicU64; 4]
}

impl AtomicHash {
    #[inline(always)]
    pub const fn new_const() -> Self {
        Self {
            inner: [
                AtomicU64::new(0),
                AtomicU64::new(0),
                AtomicU64::new(0),
                AtomicU64::new(0),
            ],
        }
    }

    #[inline(always)]
    pub fn new(hash: &Hash) -> Self {
        let atomic_hash: Self = Self::new_const();
        atomic_hash.store(hash, Ordering::Relaxed);
        atomic_hash
    }

    #[inline(always)]
    pub fn store(&self, hash: &Hash, ordering: Ordering) -> () {
        let hash_bytes: [u8; 32] = hash.to_bytes();
        for (i, bytes_chunk) in hash_bytes.chunks_exact(8).enumerate() {
            let val: u64 = u64::from_le_bytes(bytes_chunk.try_into().unwrap());
            self.inner[i].store(val, ordering);
        }
    }

    #[inline(always)]
    pub fn load(&self, ordering: Ordering) -> Hash {
        let mut hash_bytes: [u8; 32] = [0u8; 32];
        for (i, bytes_chunk) in hash_bytes.chunks_exact_mut(8).enumerate() {
            let val: u64 = self.inner[i].load(ordering);
            bytes_chunk.copy_from_slice(&val.to_le_bytes());
        }
        Hash::new_from_array(hash_bytes)
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    
    #[test]
    fn test_store_and_load() -> () {
        let hash = Hash::from([101; 32]);
        let atomic_hash = AtomicHash::new(&hash);
        let hash_after_load = atomic_hash.load(Ordering::Relaxed);
        assert_eq!(hash, hash_after_load);
    }
}