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
//! A set of records held in memory, column by column.

use std::marker::PhantomData;

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

/// A set of records in memory: each a fixed-width value, with an unsigned 64-bit id or without.
///
/// A set either gives every record an id or gives none. With ids, they rise strictly from record
/// to record: the set is in id order. An id is the application's own, such as a row's primary key;
/// the crate never interprets it. A set without ids, such as a list of values flagged for review,
/// is held as values alone.
///
/// The layout is structure-of-arrays: a column of ids, and a column for each 64-bit word of the
/// value, most significant word first. A 64-bit record takes 16 bytes with its id and 8 without;
/// a 256-bit record takes 40 and 32. A set holds at most 2³² − 1 records, so a position fits in
/// a `u32`.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Records<V> {
    ids: Option<Vec<u64>>,
    columns: Vec<Vec<u64>>,
    value: PhantomData<V>,
}

impl<V: Value> Records<V> {
    /// An empty set of records with ids.
    #[must_use]
    pub fn with_ids() -> Self {
        Self {
            ids: Some(Vec::new()),
            columns: vec![Vec::new(); V::WORDS],
            value: PhantomData,
        }
    }

    /// An empty set of values without ids.
    #[must_use]
    pub fn values_only() -> Self {
        Self {
            ids: None,
            columns: vec![Vec::new(); V::WORDS],
            value: PhantomData,
        }
    }

    /// A set from columns already built: the ids, if any, and one column per 64-bit word of the
    /// value, most significant word first. Takes the vectors as they are, with no copy, which
    /// matters for a set of hundreds of millions of records.
    ///
    /// # Errors
    ///
    /// [`Error::Columns`] if there isn't one column per word or the columns and ids differ in
    /// length, [`Error::IdOrder`] if an id isn't above the one before it, and
    /// [`Error::TooManyRecords`] if there are 2³² or more records.
    pub fn from_columns(ids: Option<Vec<u64>>, columns: Vec<Vec<u64>>) -> Result<Self> {
        let length = columns.first().map_or(0, Vec::len);
        if columns.len() != V::WORDS
            || columns.iter().any(|column| column.len() != length)
            || ids.as_ref().is_some_and(|ids| ids.len() != length)
        {
            return Err(Error::Columns { words: V::WORDS });
        }
        if length > u32::MAX as usize {
            return Err(Error::TooManyRecords);
        }
        if let Some(ids) = &ids
            && let Some(pair) = ids.windows(2).find(|pair| pair[1] <= pair[0])
        {
            return Err(Error::IdOrder {
                previous: pair[0],
                id: pair[1],
            });
        }
        Ok(Self {
            ids,
            columns,
            value: PhantomData,
        })
    }

    /// A set of values without ids, in the order given.
    ///
    /// # Errors
    ///
    /// [`Error::TooManyRecords`] if there are 2³² or more.
    pub fn from_values(values: impl IntoIterator<Item = V>) -> Result<Self> {
        let mut records = Self::values_only();
        for value in values {
            records.push_value(value)?;
        }
        Ok(records)
    }

    /// A set of records with ids, from `(id, value)` pairs in rising id order.
    ///
    /// # Errors
    ///
    /// [`Error::IdOrder`] if an id isn't above the one before it, and [`Error::TooManyRecords`] if
    /// there are 2³² or more.
    pub fn from_records(records: impl IntoIterator<Item = (u64, V)>) -> Result<Self> {
        let mut set = Self::with_ids();
        for (id, value) in records {
            set.push(id, value)?;
        }
        Ok(set)
    }

    /// Reserve room for `additional` more records.
    pub fn reserve(&mut self, additional: usize) {
        if let Some(ids) = &mut self.ids {
            ids.reserve(additional);
        }
        for column in &mut self.columns {
            column.reserve(additional);
        }
    }

    /// Reserve room for exactly `additional` more records, or say the memory can't be had rather
    /// than end the process.
    ///
    /// # Errors
    ///
    /// [`Error::OutOfMemory`] when the allocator won't give it.
    pub fn try_reserve(&mut self, additional: usize) -> Result<()> {
        let short = |_| Error::OutOfMemory { what: "the records" };
        if let Some(ids) = &mut self.ids {
            ids.try_reserve_exact(additional).map_err(short)?;
        }
        for column in &mut self.columns {
            column.try_reserve_exact(additional).map_err(short)?;
        }
        Ok(())
    }

    /// Add a record after the last.
    ///
    /// # Errors
    ///
    /// [`Error::IdPresence`] if the set holds values only, [`Error::IdOrder`] if `id` isn't above
    /// the last id, and [`Error::TooManyRecords`] if the set is full.
    pub fn push(&mut self, id: u64, value: V) -> Result<()> {
        self.check_room()?;
        let Some(ids) = &mut self.ids else {
            return Err(Error::IdPresence { set_has_ids: false });
        };
        if let Some(&previous) = ids.last()
            && id <= previous
        {
            return Err(Error::IdOrder { previous, id });
        }
        ids.push(id);
        self.push_words(value);
        Ok(())
    }

    /// Add a value after the last, in a set without ids.
    ///
    /// # Errors
    ///
    /// [`Error::IdPresence`] if the set holds records with ids, and [`Error::TooManyRecords`] if it
    /// is full.
    pub fn push_value(&mut self, value: V) -> Result<()> {
        self.check_room()?;
        if self.ids.is_some() {
            return Err(Error::IdPresence { set_has_ids: true });
        }
        self.push_words(value);
        Ok(())
    }

    fn check_room(&self) -> Result<()> {
        if self.len() >= u32::MAX as usize {
            Err(Error::TooManyRecords)
        } else {
            Ok(())
        }
    }

    fn push_words(&mut self, value: V) {
        for (word, column) in self.columns.iter_mut().enumerate() {
            column.push(value.word(word));
        }
    }

    /// How many records the set holds.
    #[must_use]
    pub fn len(&self) -> usize {
        self.columns[0].len()
    }

    /// Whether the set holds no records.
    #[must_use]
    pub fn is_empty(&self) -> bool {
        self.len() == 0
    }

    /// Whether the records carry ids.
    #[must_use]
    pub const fn has_ids(&self) -> bool {
        self.ids.is_some()
    }

    /// The ids in record order, if the records carry them.
    #[must_use]
    pub fn ids(&self) -> Option<&[u64]> {
        self.ids.as_deref()
    }

    /// The id of the record at `position`, if the records carry ids.
    ///
    /// # Panics
    ///
    /// Panics if `position` is past the end.
    #[must_use]
    #[track_caller]
    pub fn id(&self, position: usize) -> Option<u64> {
        assert!(
            position < self.len(),
            "position {position} is past the end of {} records",
            self.len()
        );
        self.ids.as_ref().map(|ids| ids[position])
    }

    /// The value of the record at `position`.
    ///
    /// # Panics
    ///
    /// Panics if `position` is past the end.
    #[must_use]
    #[track_caller]
    pub fn value(&self, position: usize) -> V {
        let mut words = [0u64; 4];
        for (word, column) in self.columns.iter().enumerate() {
            words[word] = column[position];
        }
        V::from_words(&words[..V::WORDS])
    }

    /// The column of word `word` of every value, most significant word first.
    ///
    /// # Panics
    ///
    /// Panics if `word` isn't below [`Value::WORDS`].
    #[must_use]
    #[track_caller]
    pub fn column(&self, word: usize) -> &[u64] {
        &self.columns[word]
    }

    /// The records in order, as `(id, value)`.
    pub fn iter(&self) -> impl ExactSizeIterator<Item = (Option<u64>, V)> + '_ {
        (0..self.len()).map(|position| (self.id(position), self.value(position)))
    }

    /// The bytes the set's columns take in memory.
    #[must_use]
    pub fn heap_bytes(&self) -> usize {
        let ids = self.ids.as_ref().map_or(0, |ids| ids.capacity() * 8);
        ids + self.columns.iter().map(|column| column.capacity() * 8).sum::<usize>()
    }
}