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 Arm NEON kernels: `vcntq_u8` counts the bits of each byte, and pairwise adds sum them.
//!
//! - `neon`: pairwise widening adds (`vpaddlq_u8`, `vpaddlq_u16`, `vpaddlq_u32`) give one count
//!   per 64-bit lane, two values a vector, each tested on its own. On an Apple M2 Pro it ran 1.6
//!   times the scalar code at 256 bits and 0.68 times it at 64 bits, where the compiler already
//!   turns `count_ones` into a vector count. At 64 bits it is kept for comparison.
//! - `neon-wide`, 64 bits only: four vectors, eight values, a step; three rounds of pairwise adds
//!   (`vpaddq_u8`) narrow their byte counts into one byte a value, compared with the radius in the
//!   vector unit, so only a step with a survivor reaches the scalar code. On the same CPU it ran
//!   1.4 to 1.6 times the scalar code at 64 bits.
//!
//! The test suite checks both against the reference on any Arm machine that runs it.

#![expect(
    unsafe_code,
    reason = "vector intrinsics need `#[target_feature]` calls and raw-pointer loads"
)]

use std::arch::aarch64::{
    uint8x16_t, uint64x2_t, vaddq_u8, vcle_u8, vcleq_u64, vcntq_u8, vdup_n_u8, vdupq_n_u64, veorq_u64, vget_lane_u64,
    vget_low_u8, vgetq_lane_u64, vld1q_u64, vmaxvq_u32, vpaddlq_u8, vpaddlq_u16, vpaddlq_u32, vpaddq_u8,
    vreinterpret_u64_u8, vreinterpretq_u8_u64, vreinterpretq_u32_u64, vst1_u8,
};

use super::{Hit, scalar};
use crate::cpu::Isa;

pub(super) fn scan64(column: &[u64], query: u64, radius: u32, base: u32, out: &mut Vec<Hit>) {
    if !Isa::Neon.is_available() {
        return scalar::scan64(column, query, radius, base, out);
    }
    // SAFETY: `is_available` has just confirmed the CPU has NEON...
    unsafe { scan64_neon(column, query, radius, base, out) }
}

pub(super) fn scan256(columns: [&[u64]; 4], query: [u64; 4], radius: u32, base: u32, out: &mut Vec<Hit>) {
    if !Isa::Neon.is_available() {
        return scalar::scan256(columns, query, radius, base, out);
    }
    // SAFETY: as in `scan64`; the body reads `columns[w][i..i + 2]` only for
    // `i + 2 <= columns[0].len()`, and every column is that long...
    unsafe { scan256_neon(columns, query, radius, base, out) }
}

pub(super) fn scan64_wide(column: &[u64], query: u64, radius: u32, base: u32, out: &mut Vec<Hit>) {
    if !Isa::NeonWide.is_available() {
        return scalar::scan64(column, query, radius, base, out);
    }
    // SAFETY: `is_available` has just confirmed the CPU has NEON...
    unsafe { scan64_neon_wide(column, query, radius, base, out) }
}

/// One count per 64-bit lane of the bytes' bit counts.
#[target_feature(enable = "neon")]
fn widen(bytes: uint8x16_t) -> uint64x2_t {
    vpaddlq_u32(vpaddlq_u16(vpaddlq_u8(bytes)))
}

#[target_feature(enable = "neon")]
fn emit(distances: uint64x2_t, radius: u64, position: u32, out: &mut Vec<Hit>) {
    let within = vcleq_u64(distances, vdupq_n_u64(radius));
    if vmaxvq_u32(vreinterpretq_u32_u64(within)) == 0 {
        return;
    }
    let first = vgetq_lane_u64::<0>(distances);
    if first <= radius {
        out.push(Hit {
            position,
            distance: first as u32,
        });
    }
    let second = vgetq_lane_u64::<1>(distances);
    if second <= radius {
        out.push(Hit {
            position: position + 1,
            distance: second as u32,
        });
    }
}

#[target_feature(enable = "neon")]
fn scan64_neon(column: &[u64], query: u64, radius: u32, base: u32, out: &mut Vec<Hit>) {
    let query_lanes = vdupq_n_u64(query);
    let length = column.len();
    let mut index = 0;
    while index + 2 <= length {
        // SAFETY: `index + 2 <= length`, so the 16 bytes read lie inside `column`...
        let values = unsafe { vld1q_u64(column.as_ptr().add(index)) };
        let distances = widen(vcntq_u8(vreinterpretq_u8_u64(veorq_u64(values, query_lanes))));
        emit(distances, u64::from(radius), base + index as u32, out);
        index += 2;
    }
    scalar::scan64(&column[index..], query, radius, base + index as u32, out);
}

#[target_feature(enable = "neon")]
fn scan256_neon(columns: [&[u64]; 4], query: [u64; 4], radius: u32, base: u32, out: &mut Vec<Hit>) {
    let query_lanes = [
        vdupq_n_u64(query[0]),
        vdupq_n_u64(query[1]),
        vdupq_n_u64(query[2]),
        vdupq_n_u64(query[3]),
    ];
    let length = columns[0].len();
    let mut index = 0;
    while index + 2 <= length {
        // Each byte count is at most 8, so four summed per byte fit a byte...
        let mut bytes = vcntq_u8(vreinterpretq_u8_u64(vdupq_n_u64(0)));
        for word in 0..4 {
            // SAFETY: `index + 2 <= length` and every column is `length` words long...
            let values = unsafe { vld1q_u64(columns[word].as_ptr().add(index)) };
            bytes = vaddq_u8(
                bytes,
                vcntq_u8(vreinterpretq_u8_u64(veorq_u64(values, query_lanes[word]))),
            );
        }
        emit(widen(bytes), u64::from(radius), base + index as u32, out);
        index += 2;
    }
    scalar::scan256(
        columns.map(|column| &column[index..]),
        query,
        radius,
        base + index as u32,
        out,
    );
}

#[target_feature(enable = "neon")]
fn scan64_neon_wide(column: &[u64], query: u64, radius: u32, base: u32, out: &mut Vec<Hit>) {
    let query_lanes = vdupq_n_u64(query);
    // A count is at most 64, so a radius of 64 or more lets every value through, and fits a byte...
    let limit = vdup_n_u8(radius.min(64) as u8);
    let length = column.len();
    let pointer = column.as_ptr();
    let count = |index: usize| {
        // SAFETY: every caller passes `index + 2 <= length`, so the 16 bytes read lie inside
        // `column`...
        let values = unsafe { vld1q_u64(pointer.add(index)) };
        vcntq_u8(vreinterpretq_u8_u64(veorq_u64(values, query_lanes)))
    };
    let mut index = 0;
    while index + 8 <= length {
        // Each vector holds two values' byte counts, eight bytes a value. `vpaddq_u8` adds
        // neighbouring bytes of its two inputs, the first input's into the low half: three rounds
        // leave values `index` to `index + 7` in bytes 0 to 7, in order, each at most 64...
        let first = vpaddq_u8(count(index), count(index + 2));
        let second = vpaddq_u8(count(index + 4), count(index + 6));
        let quarters = vpaddq_u8(first, second);
        let counts = vget_low_u8(vpaddq_u8(quarters, quarters));
        if vget_lane_u64::<0>(vreinterpret_u64_u8(vcle_u8(counts, limit))) != 0 {
            let mut distances = [0u8; 8];
            // SAFETY: `distances` is 8 bytes, the width of the store...
            unsafe { vst1_u8(distances.as_mut_ptr(), counts) };
            for (lane, &distance) in (0u32..).zip(&distances) {
                if u32::from(distance) <= radius {
                    out.push(Hit {
                        position: base + index as u32 + lane,
                        distance: u32::from(distance),
                    });
                }
            }
        }
        index += 8;
    }
    scalar::scan64(&column[index..], query, radius, base + index as u32, out);
}