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 distance kernels: given a run of stored values, a query and a radius, push every position
//! within the radius with its distance.
//!
//! Each kernel has a scalar body here, written once and compiled again inside each `x86` and `arm`
//! wrapper with that path's instructions enabled, and hand-written vector bodies in those modules.
//! The dispatchers below pick the body for an [`Isa`]; a path the CPU lacks falls back to the
//! scalar body, so a kernel never runs an instruction the CPU doesn't have.

#[cfg(target_arch = "aarch64")]
mod arm;
#[cfg(target_arch = "x86_64")]
mod x86;

use crate::cpu::Isa;

/// One stored value within the radius: its position in the set searched and its distance from the
/// query.
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub struct Hit {
    /// The value's position, counting from 0, in the set searched.
    pub position: u32,
    /// How many bits differ from the query.
    pub distance: u32,
}

/// Scan one column of 64-bit values, the first at position `base`.
pub(crate) fn scan64(isa: Isa, column: &[u64], query: u64, radius: u32, base: u32, out: &mut Vec<Hit>) {
    match isa {
        #[cfg(target_arch = "x86_64")]
        Isa::Popcnt | Isa::Avx2 | Isa::Avx512Bw | Isa::Avx512 => x86::scan64(isa, column, query, radius, base, out),
        #[cfg(target_arch = "aarch64")]
        Isa::Neon => arm::scan64(column, query, radius, base, out),
        #[cfg(target_arch = "aarch64")]
        Isa::NeonWide => arm::scan64_wide(column, query, radius, base, out),
        _ => scalar::scan64(column, query, radius, base, out),
    }
}

/// Scan four columns of equal length holding the words of 256-bit values, most significant first.
pub(crate) fn scan256(isa: Isa, columns: [&[u64]; 4], query: [u64; 4], radius: u32, base: u32, out: &mut Vec<Hit>) {
    let columns = scalar::equal(columns);
    match isa {
        #[cfg(target_arch = "x86_64")]
        Isa::Popcnt | Isa::Avx2 | Isa::Avx512Bw | Isa::Avx512 => x86::scan256(isa, columns, query, radius, base, out),
        #[cfg(target_arch = "aarch64")]
        Isa::Neon | Isa::NeonWide => arm::scan256(columns, query, radius, base, out),
        _ => scalar::scan256(columns, query, radius, base, out),
    }
}

/// Scan records laid out one after another, `stride` words each, with the value's words at
/// `offset` in the order `query` gives them.
///
/// This is the layout of a snapshot file: an id word, then the value.
#[expect(
    clippy::too_many_arguments,
    reason = "the layout, query and output of one kernel call"
)]
pub(crate) fn scan_interleaved(
    isa: Isa,
    words: &[u64],
    stride: usize,
    offset: usize,
    query: &[u64],
    radius: u32,
    base: u32,
    out: &mut Vec<Hit>,
) {
    if stride == 1 && query.len() == 1 {
        return scan64(isa, words, query[0], radius, base, out);
    }
    match isa {
        #[cfg(target_arch = "x86_64")]
        Isa::Popcnt | Isa::Avx2 | Isa::Avx512Bw | Isa::Avx512 => {
            x86::scan_interleaved(isa, words, stride, offset, query, radius, base, out);
        }
        _ => scalar::scan_interleaved(words, stride, offset, query, radius, base, out),
    }
}

/// The path [`scan_interleaved`] really runs when asked for `isa` on records of `stride` words,
/// the value's `width` words starting at word `offset` of each: only some layouts have a kernel of
/// their own on a vector path, and the rest run the `popcnt` kernel, or the scalar one.
pub(crate) fn interleaved_path(isa: Isa, stride: usize, offset: usize, width: usize) -> Isa {
    if stride == 1 && width == 1 {
        return isa;
    }
    match isa {
        #[cfg(target_arch = "x86_64")]
        Isa::Avx512 if stride == 2 && offset == 1 && width == 1 => Isa::Avx512,
        #[cfg(target_arch = "x86_64")]
        Isa::Popcnt | Isa::Avx2 | Isa::Avx512Bw | Isa::Avx512 => Isa::Popcnt,
        _ => {
            let _ = offset;
            Isa::Scalar
        }
    }
}

/// The scalar bodies. Each is `#[inline(always)]` so a wrapper with `popcnt` enabled compiles it
/// with the instruction.
pub(crate) mod scalar {
    use super::Hit;

    /// Check the four columns are the same length, and say so to the compiler...
    #[inline(always)]
    pub(crate) fn equal(columns: [&[u64]; 4]) -> [&[u64]; 4] {
        let length = columns[0].len();
        assert!(
            columns.iter().all(|column| column.len() == length),
            "the four columns have the same length"
        );
        columns.map(|column| &column[..length])
    }

    #[inline(always)]
    pub(crate) fn scan64(column: &[u64], query: u64, radius: u32, base: u32, out: &mut Vec<Hit>) {
        let (fours, rest) = column.as_chunks::<4>();
        let mut position = base;
        for four in fours {
            let distances = [
                (four[0] ^ query).count_ones(),
                (four[1] ^ query).count_ones(),
                (four[2] ^ query).count_ones(),
                (four[3] ^ query).count_ones(),
            ];
            if distances[0].min(distances[1]).min(distances[2].min(distances[3])) <= radius {
                for (lane, &distance) in (0u32..).zip(&distances) {
                    if distance <= radius {
                        out.push(Hit {
                            position: position + lane,
                            distance,
                        });
                    }
                }
            }
            position += 4;
        }
        for (lane, &value) in (0u32..).zip(rest) {
            let distance = (value ^ query).count_ones();
            if distance <= radius {
                out.push(Hit {
                    position: position + lane,
                    distance,
                });
            }
        }
    }

    #[inline(always)]
    pub(crate) fn scan256(columns: [&[u64]; 4], query: [u64; 4], radius: u32, base: u32, out: &mut Vec<Hit>) {
        let [a, b, c, d] = columns;
        for (position, (((&a, &b), &c), &d)) in (base..).zip(a.iter().zip(b).zip(c).zip(d)) {
            let distance = (a ^ query[0]).count_ones()
                + (b ^ query[1]).count_ones()
                + (c ^ query[2]).count_ones()
                + (d ^ query[3]).count_ones();
            if distance <= radius {
                out.push(Hit { position, distance });
            }
        }
    }

    #[inline(always)]
    pub(crate) fn scan_interleaved(
        words: &[u64],
        stride: usize,
        offset: usize,
        query: &[u64],
        radius: u32,
        base: u32,
        out: &mut Vec<Hit>,
    ) {
        let width = query.len();
        for (position, record) in (base..).zip(words.chunks_exact(stride)) {
            let value = &record[offset..offset + width];
            let distance: u32 = value.iter().zip(query).map(|(a, b)| (a ^ b).count_ones()).sum();
            if distance <= radius {
                out.push(Hit { position, distance });
            }
        }
    }
}