legit-hamming 0.1.1

Exact Hamming radius search over 64-bit and 256-bit hashes in memory: a scan or multi-index hashing, chosen per query, checked against one reference, and a search service over snapshots
Documentation
//! The two value widths: `u64` and `[u64; 4]`.

use std::fmt;
use std::hash::Hash;

use crate::error::{Error, Result};

mod sealed {
    pub trait Sealed {}
    impl Sealed for u64 {}
    impl Sealed for [u64; 4] {}
}

/// A fixed-width value to search: `u64` for 64 bits, or `[u64; 4]` for 256 bits.
///
/// A 256-bit value is four 64-bit words, most significant first: word 0 holds the first 16 hex
/// digits of its hex form. The trait is sealed; the crate implements it for these two types only.
pub trait Value: Copy + Eq + Ord + Hash + fmt::Debug + Send + Sync + 'static + sealed::Sealed {
    /// The width in bits: 64 or 256.
    const BITS: u32;
    /// The width in 64-bit words: 1 or 4.
    const WORDS: usize;

    /// The Hamming distance to another value: how many bits differ.
    fn distance(&self, other: &Self) -> u32;

    /// Word `index` of the value, most significant first.
    ///
    /// # Panics
    ///
    /// Panics if `index` isn't below [`WORDS`](Self::WORDS).
    fn word(&self, index: usize) -> u64;

    /// The value from its words, most significant first.
    ///
    /// # Panics
    ///
    /// Panics if `words` doesn't hold exactly [`WORDS`](Self::WORDS) words.
    fn from_words(words: &[u64]) -> Self;

    /// Whether every bit is 0.
    fn is_zero(&self) -> bool;

    /// The value as lower-case hex, most significant digit first: 16 or 64 digits.
    fn to_hex(&self) -> String {
        let mut hex = String::with_capacity(Self::WORDS * 16);
        for index in 0..Self::WORDS {
            use fmt::Write;
            let _ = write!(hex, "{:016x}", self.word(index));
        }
        hex
    }

    /// Read a value from hex, most significant digit first, in either case.
    ///
    /// # Errors
    ///
    /// [`Error::InvalidHex`] if the string isn't exactly 16 or 64 hex digits, as the width needs.
    fn from_hex(hex: &str) -> Result<Self> {
        let expected = Self::WORDS * 16;
        if hex.len() != expected || !hex.bytes().all(|byte| byte.is_ascii_hexdigit()) {
            return Err(Error::InvalidHex { expected });
        }
        let mut words = [0u64; 4];
        for (index, word) in words.iter_mut().take(Self::WORDS).enumerate() {
            *word = u64::from_str_radix(&hex[index * 16..index * 16 + 16], 16)
                .map_err(|_| Error::InvalidHex { expected })?;
        }
        Ok(Self::from_words(&words[..Self::WORDS]))
    }

    /// Append the value to `out` as an unsigned little-endian integer: 8 or 32 bytes, least
    /// significant byte first. This is how a snapshot file stores it.
    fn write_le(&self, out: &mut Vec<u8>) {
        for index in (0..Self::WORDS).rev() {
            out.extend_from_slice(&self.word(index).to_le_bytes());
        }
    }

    /// Read a value written by [`write_le`](Self::write_le).
    ///
    /// # Panics
    ///
    /// Panics if `bytes` isn't exactly 8 or 32 bytes, as the width needs.
    fn read_le(bytes: &[u8]) -> Self {
        assert_eq!(bytes.len(), Self::WORDS * 8, "a value is {} bytes", Self::WORDS * 8);
        let mut words = [0u64; 4];
        for (index, chunk) in bytes.as_chunks::<8>().0.iter().enumerate() {
            let word = u64::from_le_bytes(*chunk);
            words[Self::WORDS - 1 - index] = word;
        }
        Self::from_words(&words[..Self::WORDS])
    }
}

impl Value for u64 {
    const BITS: u32 = 64;
    const WORDS: usize = 1;

    fn distance(&self, other: &Self) -> u32 {
        (self ^ other).count_ones()
    }

    #[track_caller]
    fn word(&self, index: usize) -> u64 {
        assert_eq!(index, 0, "a 64-bit value has one word");
        *self
    }

    #[track_caller]
    fn from_words(words: &[u64]) -> Self {
        assert_eq!(words.len(), 1, "a 64-bit value has one word");
        words[0]
    }

    fn is_zero(&self) -> bool {
        *self == 0
    }
}

impl Value for [u64; 4] {
    const BITS: u32 = 256;
    const WORDS: usize = 4;

    fn distance(&self, other: &Self) -> u32 {
        self.iter().zip(other).map(|(a, b)| (a ^ b).count_ones()).sum()
    }

    #[track_caller]
    fn word(&self, index: usize) -> u64 {
        self[index]
    }

    #[track_caller]
    fn from_words(words: &[u64]) -> Self {
        words.try_into().expect("a 256-bit value has four words")
    }

    fn is_zero(&self) -> bool {
        *self == [0; 4]
    }
}