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 scans: the reference, and the flat scan on any code path.

use std::ops::Range;
use std::sync::Arc;

use crate::cpu::Isa;
use crate::error::Result;
use crate::kernel::{self, Hit};
use crate::records::Records;
use crate::search::{Clock, HitList, Memory, Search, Share, Stop, TRIM_RUN};
use crate::value::Value;

/// How many records a scan reads for every query before moving on, and how often it looks at the
/// clock. 16,384 values are 128 KiB of one column, so a tile of 256-bit values stays in a core's
/// level-2 cache while every query of a batch reads it...
pub(crate) const TILE: usize = 16_384;

/// The reference: the plainest possible scan, which every other variant is checked against.
///
/// It compares every record with every query using [`Value::distance`], one record at a time, with
/// no tiling, no unrolling and no instruction set beyond the build target's.
#[derive(Debug, Clone)]
pub struct Reference<V> {
    records: Arc<Records<V>>,
}

impl<V: Value> Reference<V> {
    /// The reference over `records`.
    #[must_use]
    pub const fn new(records: Arc<Records<V>>) -> Self {
        Self { records }
    }
}

impl<V: Value> Search<V> for Reference<V> {
    fn variant(&self) -> String {
        "reference".to_owned()
    }

    fn len(&self) -> usize {
        self.records.len()
    }

    fn has_ids(&self) -> bool {
        self.records.has_ids()
    }

    fn id(&self, position: usize) -> Option<u64> {
        self.records.id(position)
    }

    fn value(&self, position: usize) -> V {
        self.records.value(position)
    }

    fn memory(&self) -> Memory {
        Memory {
            records: self.records.heap_bytes(),
            ..Memory::default()
        }
    }

    fn collect(&self, queries: &[V], radius: u32, share: Share, stop: &Stop, out: &mut [HitList<'_>]) -> bool {
        let range = share.range(self.records.len());
        for (query, list) in queries.iter().zip(out.iter_mut()) {
            if stop.reached() {
                return true;
            }
            for position in range.clone() {
                let distance = self.records.value(position).distance(query);
                if distance <= radius {
                    list.push(Hit {
                        position: position as u32,
                        distance,
                    });
                }
            }
            list.candidates += range.len() as u64;
        }
        false
    }
}

/// A flat scan of every record, on a chosen code path.
///
/// It reads the value columns in tiles of 16,384 records, running every query of a batch over a
/// tile before moving to the next, so a batch reads the set from memory once. It needs nothing but
/// the records: no index, no extra memory.
#[derive(Debug, Clone)]
pub struct Scan<V> {
    records: Arc<Records<V>>,
    isa: Isa,
}

impl<V: Value> Scan<V> {
    /// A scan over `records` on the fastest path this CPU has for their width,
    /// [`Isa::best_for`].
    #[must_use]
    pub fn new(records: Arc<Records<V>>) -> Self {
        Self {
            records,
            isa: Isa::best_for::<V>(),
        }
    }

    /// A scan over `records` on the path `isa`.
    ///
    /// # Errors
    ///
    /// [`Error::IsaUnavailable`](crate::Error::IsaUnavailable) if this CPU can't run it.
    pub fn with_isa(records: Arc<Records<V>>, isa: Isa) -> Result<Self> {
        Ok(Self {
            records,
            isa: isa.require()?,
        })
    }

    /// The path the scan runs on.
    #[must_use]
    pub const fn isa(&self) -> Isa {
        self.isa
    }
}

impl<V: Value> Search<V> for Scan<V> {
    fn variant(&self) -> String {
        format!("scan/{}", self.isa)
    }

    fn len(&self) -> usize {
        self.records.len()
    }

    fn has_ids(&self) -> bool {
        self.records.has_ids()
    }

    fn id(&self, position: usize) -> Option<u64> {
        self.records.id(position)
    }

    fn value(&self, position: usize) -> V {
        self.records.value(position)
    }

    fn memory(&self) -> Memory {
        Memory {
            records: self.records.heap_bytes(),
            ..Memory::default()
        }
    }

    fn collect(&self, queries: &[V], radius: u32, share: Share, stop: &Stop, out: &mut [HitList<'_>]) -> bool {
        scan_tiles(
            self.isa,
            &self.records,
            share.range(self.records.len()),
            0,
            queries,
            radius,
            stop,
            out,
        )
    }
}

/// Scan `range` of `records` tile by tile, every query on each tile, numbering positions from
/// `offset`. Returns whether `stop` cut it short.
#[expect(
    clippy::too_many_arguments,
    reason = "the set, the part of it, the queries and the output"
)]
pub(crate) fn scan_tiles<V: Value>(
    isa: Isa,
    records: &Records<V>,
    range: Range<usize>,
    offset: usize,
    queries: &[V],
    radius: u32,
    stop: &Stop,
    out: &mut [HitList<'_>],
) -> bool {
    let mut clock = Clock::new(stop);
    let mut start = range.start;
    while start < range.end {
        let end = (start + TILE).min(range.end);
        for (query, list) in queries.iter().zip(out.iter_mut()) {
            // Checked by work done, not once a tile: a tile run for a whole batch of queries is a
            // long time.
            if clock.spend(end - start) {
                return true;
            }
            // In runs, each trimmed, so a dense tile can't swell the list past its bound...
            let mut at = start;
            while at < end {
                let to = (at + TRIM_RUN).min(end);
                list.prepare(to - at);
                scan_run(isa, records, at..to, offset, query, radius, &mut list.hits);
                list.trim();
                at = to;
            }
            list.candidates += (end - start) as u64;
        }
        start = end;
    }
    false
}

/// Scan one run of records for one query.
pub(crate) fn scan_run<V: Value>(
    isa: Isa,
    records: &Records<V>,
    range: Range<usize>,
    offset: usize,
    query: &V,
    radius: u32,
    out: &mut Vec<Hit>,
) {
    let base = (offset + range.start) as u32;
    if V::WORDS == 1 {
        kernel::scan64(isa, &records.column(0)[range], query.word(0), radius, base, out);
    } else {
        let columns = [0, 1, 2, 3].map(|word| &records.column(word)[range.clone()]);
        let query = [0, 1, 2, 3].map(|word| query.word(word));
        kernel::scan256(isa, columns, query, radius, base, out);
    }
}