bloom-sol 0.0.3

Counting bloom filter, aimed for solana
Documentation
use crate::bloom_sol::struct_def::CountingBloomFilter;
use std::convert::TryInto;

impl CountingBloomFilter {
    /// Deserializes a `CountingBloomFilter` from a byte slice.
    ///
    /// Returns `Ok(CountingBloomFilter)` on success, or `Err` with an error message on failure
    /// (e.g., if the data is too short or malformed). Assumes the data follows the format produced
    /// by `serialize`.
    pub fn deserialize(data: &[u8]) -> Result<Self, &'static str> {
        let mut offset = 0;

        // Minimum length for headers: 1 (bool) + 8 (size) + 8 (num_hashes) + 8 (len)
        if data.len() < 1 + 8 + 8 + 8 {
            return Err("Data too short for headers");
        }

        let boolean_counting = data[offset] != 0;
        offset += 1;

        let size_bytes: [u8; 8] = data[offset..offset + 8]
            .try_into()
            .map_err(|_| "Invalid size bytes")?;
        let size = u64::from_le_bytes(size_bytes) as usize;
        offset += 8;

        let num_hashes_bytes: [u8; 8] = data[offset..offset + 8]
            .try_into()
            .map_err(|_| "Invalid num_hashes bytes")?;
        let num_hashes = u64::from_le_bytes(num_hashes_bytes) as usize;
        offset += 8;

        let len_bytes: [u8; 8] = data[offset..offset + 8]
            .try_into()
            .map_err(|_| "Invalid counters length bytes")?;
        let len = u64::from_le_bytes(len_bytes) as usize;
        offset += 8;

        if data.len() < offset + len {
            return Err("Data too short for counters");
        }

        let counters = data[offset..offset + len].to_vec();

        Ok(Self {
            boolean_counting,
            size,
            num_hashes,
            counters,
        })
    }
}