use std::hash::Hasher;
use std::iter::FusedIterator;
use siphasher::sip::SipHasher24;
use crate::{Algorithm, Error, Hash, Result};
#[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()
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct SimHashV1 {
sums: [i64; 64],
}
impl SimHashV1 {
#[must_use]
pub const fn new() -> Self {
Self { sums: [0; 64] }
}
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)
};
}
}
#[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()
}
}
#[must_use]
pub fn words_v1(text: &str) -> WordsV1<'_> {
WordsV1 { rest: text }
}
#[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<'_> {}
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;
let size = size.min(chars);
let windows = if chars == 0 { 0 } else { chars - size + 1 };
Ok(ShinglesV1 {
text,
boundaries,
size,
next: 0,
windows,
})
}
#[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<'_> {}