legit_hashes/simhash.rs
1//! `simhash-v1`, the text hash, and its two frozen tokenisers.
2
3use std::hash::Hasher;
4use std::iter::FusedIterator;
5
6use siphasher::sip::SipHasher24;
7
8use crate::{Algorithm, Error, Hash, Result};
9
10/// Hash weighted features with `simhash-v1`, Charikar's SimHash.
11///
12/// The definition, frozen:
13///
14/// 1. Each feature is a byte string with a weight. A repeated feature counts each time, so
15/// repeating one adds its weights.
16/// 2. Hash each feature's bytes with SipHash-2-4 under the key `(0, 0)`: the bytes written once to
17/// `siphasher::sip::SipHasher24::new_with_keys(0, 0)`, then `finish()`. Features never go
18/// through `std::hash::Hash`, whose byte encoding Rust doesn't promise to keep.
19/// 3. Keep 64 signed sums, one per bit, starting at 0. For bit `i` of a feature's hash, add the
20/// feature's weight to sum `i` when the bit is set, and subtract it when it's clear. The sums
21/// are `i64` and saturate at its bounds, which takes more than 2³¹ features at the largest
22/// weight to reach.
23/// 4. The hash `V` has bit `i` set when sum `i` is above 0. No features give the all-zero hash.
24///
25/// `V` is stored big-endian, so its hex reads as `V`. Scaling every weight by one positive
26/// constant doesn't change the hash, short of saturating the sums.
27///
28/// Features come from the caller or from one of the frozen tokenisers, [`words_v1`] and
29/// [`shingles_v1`]. A short text has few features, so its hash carries little signal: for texts
30/// under about 50 words, expect unrelated ones to land closer than a longer text's would.
31///
32/// ```
33/// use legit_hashes::{simhash_v1, words_v1};
34///
35/// let hash = simhash_v1(words_v1("The quick brown fox").map(|word| (word, 1)));
36/// let same = simhash_v1([("the", 1), ("quick", 1), ("brown", 1), ("fox", 1)]);
37/// assert_eq!(hash, same);
38/// ```
39#[must_use]
40pub fn simhash_v1<F: AsRef<[u8]>>(features: impl IntoIterator<Item = (F, u32)>) -> Hash {
41 let mut hash = SimHashV1::new();
42 for (feature, weight) in features {
43 hash.add(feature, weight);
44 }
45 hash.finish()
46}
47
48/// A `simhash-v1` hash being built a feature at a time, for features that arrive in parts.
49///
50/// [`simhash_v1`] holds the definition.
51///
52/// ```
53/// use legit_hashes::{SimHashV1, simhash_v1, words_v1};
54///
55/// let mut hash = SimHashV1::new();
56/// for word in words_v1("Hello, world") {
57/// hash.add(word, 1);
58/// }
59/// assert_eq!(hash.finish(), simhash_v1([("hello", 1), ("world", 1)]));
60/// ```
61#[derive(Debug, Clone, PartialEq, Eq)]
62pub struct SimHashV1 {
63 sums: [i64; 64],
64}
65
66impl SimHashV1 {
67 /// Start a hash with no features.
68 #[must_use]
69 pub const fn new() -> Self {
70 Self { sums: [0; 64] }
71 }
72
73 /// Add one feature, the bytes of `feature`, with `weight`.
74 pub fn add(&mut self, feature: impl AsRef<[u8]>, weight: u32) {
75 let mut hasher = SipHasher24::new_with_keys(0, 0);
76 hasher.write(feature.as_ref());
77 let bits = hasher.finish();
78 let weight = i64::from(weight);
79 for (i, sum) in self.sums.iter_mut().enumerate() {
80 *sum = if bits >> i & 1 == 1 {
81 sum.saturating_add(weight)
82 } else {
83 sum.saturating_sub(weight)
84 };
85 }
86 }
87
88 /// The hash of the features added so far.
89 #[must_use]
90 pub fn finish(&self) -> Hash {
91 let bits = self
92 .sums
93 .iter()
94 .enumerate()
95 .fold(0, |bits, (i, &sum)| bits | u64::from(sum > 0) << i);
96 Hash::from_bits(Algorithm::SimHashV1, bits)
97 }
98}
99
100impl Default for SimHashV1 {
101 fn default() -> Self {
102 Self::new()
103 }
104}
105
106/// Split `text` into words with the frozen `words-v1` tokeniser.
107///
108/// A word is a maximal run of characters that are neither ASCII whitespace (space, tab, line
109/// feed, form feed and carriage return) nor ASCII punctuation
110/// (`` !"#$%&'()*+,-./:;<=>?@[\]^_`{|}~ ``). ASCII letters are lower-cased and every other
111/// character is kept as it is, so the result depends on no Unicode table, which can change between
112/// Rust versions. Each occurrence is a word of its own.
113///
114/// The tokeniser's name is frozen like an algorithm version: a change would ship as `words_v2`.
115/// To normalise Unicode or fold case beyond ASCII, do it to the text before hashing.
116///
117/// Text written without spaces, such as Chinese or Japanese, isn't split into words, and
118/// typographic punctuation such as `’` doesn't split either: use [`shingles_v1`] for such text,
119/// or normalise it first. With every occurrence counted, long unrelated texts in one language
120/// land close together, because common words dominate; for long texts prefer [`shingles_v1`] with
121/// a size of about 5, or weight and deduplicate the words before hashing.
122///
123/// ```
124/// use legit_hashes::words_v1;
125///
126/// let words: Vec<String> = words_v1("Don't PANIC: Größe 42!").collect();
127/// assert_eq!(words, ["don", "t", "panic", "größe", "42"]);
128/// ```
129#[must_use]
130pub fn words_v1(text: &str) -> WordsV1<'_> {
131 WordsV1 { rest: text }
132}
133
134/// The words of a text, from [`words_v1`].
135#[derive(Debug, Clone)]
136pub struct WordsV1<'a> {
137 rest: &'a str,
138}
139
140impl Iterator for WordsV1<'_> {
141 type Item = String;
142
143 fn next(&mut self) -> Option<String> {
144 let is_separator = |c: char| c.is_ascii_whitespace() || c.is_ascii_punctuation();
145 let start = self.rest.find(|c: char| !is_separator(c))?;
146 let rest = &self.rest[start..];
147 let end = rest.find(is_separator).unwrap_or(rest.len());
148 self.rest = &rest[end..];
149 Some(rest[..end].to_ascii_lowercase())
150 }
151}
152
153impl FusedIterator for WordsV1<'_> {}
154
155/// Split `text` into shingles of `size` characters with the frozen `shingles-v1` tokeniser.
156///
157/// A shingle is every window of `size` consecutive Unicode scalar values (Rust `char`s), taken as
158/// the UTF-8 bytes of the text; `"abcd"` in shingles of 2 is `"ab"`, `"bc"` and `"cd"`. A text
159/// shorter than `size` gives one shingle, the whole text, unless it's empty, which gives none. No
160/// character is changed or skipped.
161///
162/// The tokeniser's name is frozen like an algorithm version: a change would ship as
163/// `shingles_v2`. To normalise Unicode or fold case, do it to the text before hashing.
164///
165/// ```
166/// use legit_hashes::shingles_v1;
167///
168/// let shingles: Vec<&str> = shingles_v1("crème", 3)?.collect();
169/// assert_eq!(shingles, ["crè", "rèm", "ème"]);
170/// # Ok::<(), legit_hashes::Error>(())
171/// ```
172///
173/// # Errors
174///
175/// Returns [`Error::ShingleSize`] when `size` is 0.
176pub fn shingles_v1(text: &str, size: usize) -> Result<ShinglesV1<'_>> {
177 if size == 0 {
178 return Err(Error::ShingleSize);
179 }
180 let mut boundaries: Vec<usize> = text.char_indices().map(|(index, _)| index).collect();
181 boundaries.push(text.len());
182 let chars = boundaries.len() - 1;
183 // A short text is one window of all its characters; an empty one has none...
184 let size = size.min(chars);
185 let windows = if chars == 0 { 0 } else { chars - size + 1 };
186 Ok(ShinglesV1 {
187 text,
188 boundaries,
189 size,
190 next: 0,
191 windows,
192 })
193}
194
195/// The shingles of a text, from [`shingles_v1`].
196#[derive(Debug, Clone)]
197pub struct ShinglesV1<'a> {
198 text: &'a str,
199 boundaries: Vec<usize>,
200 size: usize,
201 next: usize,
202 windows: usize,
203}
204
205impl<'a> Iterator for ShinglesV1<'a> {
206 type Item = &'a str;
207
208 fn next(&mut self) -> Option<&'a str> {
209 if self.next >= self.windows {
210 return None;
211 }
212 let start = self.boundaries[self.next];
213 let end = self.boundaries[self.next + self.size];
214 self.next += 1;
215 Some(&self.text[start..end])
216 }
217
218 fn size_hint(&self) -> (usize, Option<usize>) {
219 let left = self.windows - self.next.min(self.windows);
220 (left, Some(left))
221 }
222}
223
224impl ExactSizeIterator for ShinglesV1<'_> {}
225
226impl FusedIterator for ShinglesV1<'_> {}