legit-hashes 0.2.1

Versioned similarity hashes of images and text, and MinHash set signatures, with index keys for finding near matches
Documentation
//! `simhash-v1`, the text hash, and its two frozen tokenisers.

use std::hash::Hasher;
use std::iter::FusedIterator;

use siphasher::sip::SipHasher24;

use crate::{Algorithm, Error, Hash, Result};

/// Hash weighted features with `simhash-v1`, Charikar's SimHash.
///
/// The definition, frozen:
///
/// 1. Each feature is a byte string with a weight. A repeated feature counts each time, so
///    repeating one adds its weights.
/// 2. Hash each feature's bytes with SipHash-2-4 under the key `(0, 0)`: the bytes written once to
///    `siphasher::sip::SipHasher24::new_with_keys(0, 0)`, then `finish()`. Features never go
///    through `std::hash::Hash`, whose byte encoding Rust doesn't promise to keep.
/// 3. Keep 64 signed sums, one per bit, starting at 0. For bit `i` of a feature's hash, add the
///    feature's weight to sum `i` when the bit is set, and subtract it when it's clear. The sums
///    are `i64` and saturate at its bounds, which takes more than 2³¹ features at the largest
///    weight to reach.
/// 4. The hash `V` has bit `i` set when sum `i` is above 0. No features give the all-zero hash.
///
/// `V` is stored big-endian, so its hex reads as `V`. Scaling every weight by one positive
/// constant doesn't change the hash, short of saturating the sums.
///
/// Features come from the caller or from one of the frozen tokenisers, [`words_v1`] and
/// [`shingles_v1`]. A short text has few features, so its hash carries little signal: for texts
/// under about 50 words, expect unrelated ones to land closer than a longer text's would.
///
/// ```
/// use legit_hashes::{simhash_v1, words_v1};
///
/// let hash = simhash_v1(words_v1("The quick brown fox").map(|word| (word, 1)));
/// let same = simhash_v1([("the", 1), ("quick", 1), ("brown", 1), ("fox", 1)]);
/// assert_eq!(hash, same);
/// ```
#[must_use]
pub fn simhash_v1<F: AsRef<[u8]>>(features: impl IntoIterator<Item = (F, u32)>) -> Hash {
    let mut hash = SimHashV1::new();
    for (feature, weight) in features {
        hash.add(feature, weight);
    }
    hash.finish()
}

/// A `simhash-v1` hash being built a feature at a time, for features that arrive in parts.
///
/// [`simhash_v1`] holds the definition.
///
/// ```
/// use legit_hashes::{SimHashV1, simhash_v1, words_v1};
///
/// let mut hash = SimHashV1::new();
/// for word in words_v1("Hello, world") {
///     hash.add(word, 1);
/// }
/// assert_eq!(hash.finish(), simhash_v1([("hello", 1), ("world", 1)]));
/// ```
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct SimHashV1 {
    sums: [i64; 64],
}

impl SimHashV1 {
    /// Start a hash with no features.
    #[must_use]
    pub const fn new() -> Self {
        Self { sums: [0; 64] }
    }

    /// Add one feature, the bytes of `feature`, with `weight`.
    pub fn add(&mut self, feature: impl AsRef<[u8]>, weight: u32) {
        let mut hasher = SipHasher24::new_with_keys(0, 0);
        hasher.write(feature.as_ref());
        let bits = hasher.finish();
        let weight = i64::from(weight);
        for (i, sum) in self.sums.iter_mut().enumerate() {
            *sum = if bits >> i & 1 == 1 {
                sum.saturating_add(weight)
            } else {
                sum.saturating_sub(weight)
            };
        }
    }

    /// The hash of the features added so far.
    #[must_use]
    pub fn finish(&self) -> Hash {
        let bits = self
            .sums
            .iter()
            .enumerate()
            .fold(0, |bits, (i, &sum)| bits | u64::from(sum > 0) << i);
        Hash::from_bits(Algorithm::SimHashV1, bits)
    }
}

impl Default for SimHashV1 {
    fn default() -> Self {
        Self::new()
    }
}

/// Split `text` into words with the frozen `words-v1` tokeniser.
///
/// A word is a maximal run of characters that are neither ASCII whitespace (space, tab, line
/// feed, form feed and carriage return) nor ASCII punctuation
/// (`` !"#$%&'()*+,-./:;<=>?@[\]^_`{|}~ ``). ASCII letters are lower-cased and every other
/// character is kept as it is, so the result depends on no Unicode table, which can change between
/// Rust versions. Each occurrence is a word of its own.
///
/// The tokeniser's name is frozen like an algorithm version: a change would ship as `words_v2`.
/// To normalise Unicode or fold case beyond ASCII, do it to the text before hashing.
///
/// Text written without spaces, such as Chinese or Japanese, isn't split into words, and
/// typographic punctuation such as `’` doesn't split either: use [`shingles_v1`] for such text,
/// or normalise it first. With every occurrence counted, long unrelated texts in one language
/// land close together, because common words dominate; for long texts prefer [`shingles_v1`] with
/// a size of about 5, or weight and deduplicate the words before hashing.
///
/// ```
/// use legit_hashes::words_v1;
///
/// let words: Vec<String> = words_v1("Don't PANIC: Größe 42!").collect();
/// assert_eq!(words, ["don", "t", "panic", "größe", "42"]);
/// ```
#[must_use]
pub fn words_v1(text: &str) -> WordsV1<'_> {
    WordsV1 { rest: text }
}

/// The words of a text, from [`words_v1`].
#[derive(Debug, Clone)]
pub struct WordsV1<'a> {
    rest: &'a str,
}

impl Iterator for WordsV1<'_> {
    type Item = String;

    fn next(&mut self) -> Option<String> {
        let is_separator = |c: char| c.is_ascii_whitespace() || c.is_ascii_punctuation();
        let start = self.rest.find(|c: char| !is_separator(c))?;
        let rest = &self.rest[start..];
        let end = rest.find(is_separator).unwrap_or(rest.len());
        self.rest = &rest[end..];
        Some(rest[..end].to_ascii_lowercase())
    }
}

impl FusedIterator for WordsV1<'_> {}

/// Split `text` into shingles of `size` characters with the frozen `shingles-v1` tokeniser.
///
/// A shingle is every window of `size` consecutive Unicode scalar values (Rust `char`s), taken as
/// the UTF-8 bytes of the text; `"abcd"` in shingles of 2 is `"ab"`, `"bc"` and `"cd"`. A text
/// shorter than `size` gives one shingle, the whole text, unless it's empty, which gives none. No
/// character is changed or skipped.
///
/// The tokeniser's name is frozen like an algorithm version: a change would ship as
/// `shingles_v2`. To normalise Unicode or fold case, do it to the text before hashing.
///
/// ```
/// use legit_hashes::shingles_v1;
///
/// let shingles: Vec<&str> = shingles_v1("crème", 3)?.collect();
/// assert_eq!(shingles, ["crè", "rèm", "ème"]);
/// # Ok::<(), legit_hashes::Error>(())
/// ```
///
/// # Errors
///
/// Returns [`Error::ShingleSize`] when `size` is 0.
pub fn shingles_v1(text: &str, size: usize) -> Result<ShinglesV1<'_>> {
    if size == 0 {
        return Err(Error::ShingleSize);
    }
    let mut boundaries: Vec<usize> = text.char_indices().map(|(index, _)| index).collect();
    boundaries.push(text.len());
    let chars = boundaries.len() - 1;
    // A short text is one window of all its characters; an empty one has none...
    let size = size.min(chars);
    let windows = if chars == 0 { 0 } else { chars - size + 1 };
    Ok(ShinglesV1 {
        text,
        boundaries,
        size,
        next: 0,
        windows,
    })
}

/// The shingles of a text, from [`shingles_v1`].
#[derive(Debug, Clone)]
pub struct ShinglesV1<'a> {
    text: &'a str,
    boundaries: Vec<usize>,
    size: usize,
    next: usize,
    windows: usize,
}

impl<'a> Iterator for ShinglesV1<'a> {
    type Item = &'a str;

    fn next(&mut self) -> Option<&'a str> {
        if self.next >= self.windows {
            return None;
        }
        let start = self.boundaries[self.next];
        let end = self.boundaries[self.next + self.size];
        self.next += 1;
        Some(&self.text[start..end])
    }

    fn size_hint(&self) -> (usize, Option<usize>) {
        let left = self.windows - self.next.min(self.windows);
        (left, Some(left))
    }
}

impl ExactSizeIterator for ShinglesV1<'_> {}

impl FusedIterator for ShinglesV1<'_> {}