Skip to main content

legit_hashes/
hash.rs

1//! The hash value, its stored forms, Hamming distance and chunk keys.
2
3use std::fmt;
4use std::str::FromStr;
5
6use crate::{Algorithm, Error, Result};
7
8/// The longest hash any algorithm produces, in bytes: 256 bits.
9const MAX_BYTES: usize = 32;
10
11/// A hash: the algorithm that made it, version included, and its bits.
12///
13/// A hash is 64 or 256 bits wide, as [`Algorithm::bits`] says, and is held inline, with no heap
14/// allocation. Its bits are kept in the order its algorithm defines: the first bit is the most
15/// significant bit of the first byte. Every stored form carries the same bits in that order, and
16/// the hex reads as the reference implementation of the algorithm prints it.
17///
18/// | Form | Example | Read back with |
19/// |---|---|---|
20/// | [`Display`](fmt::Display) | `perceptual-v1:c3f00f3c99a5a55a` | [`FromStr`] |
21/// | [`to_hex`](Self::to_hex) | `c3f00f3c99a5a55a` | [`from_hex`](Self::from_hex) |
22/// | [`as_bytes`](Self::as_bytes) | `[0xc3, 0xf0, ..]` | [`from_bytes`](Self::from_bytes) |
23/// | [`to_u64`](Self::to_u64) | `0xc3f00f3c99a5a55a` | [`from_u64`](Self::from_u64) |
24/// | [`to_i64`](Self::to_i64) | the same bits as a signed integer | [`from_i64`](Self::from_i64) |
25///
26/// A 256-bit hash has the string, hex and byte forms, 64 hex digits or 32 bytes long, and no
27/// integer form. Only the string form names the algorithm. With the others, store the algorithm id
28/// beside the value, or keep one algorithm per column.
29///
30/// ```
31/// use legit_hashes::{Algorithm, Hash};
32///
33/// let stored: Hash = "average-v1:0f0f0f0f0f0f0f0f".parse()?;
34/// let other = Hash::from_hex(Algorithm::AverageV1, "0f0f0f0f0f0f0f0e")?;
35///
36/// assert_eq!(stored.distance(&other)?, 1);
37/// assert_eq!(stored.to_string(), "average-v1:0f0f0f0f0f0f0f0f");
38/// # Ok::<(), legit_hashes::Error>(())
39/// ```
40#[derive(Clone, PartialEq, Eq, Hash)]
41pub struct Hash {
42    algorithm: Algorithm,
43    bytes: [u8; MAX_BYTES],
44}
45
46impl Hash {
47    /// Make a 64-bit hash from bits whose most significant is the first bit produced.
48    pub(crate) const fn from_bits(algorithm: Algorithm, bits: u64) -> Self {
49        let mut bytes = [0; MAX_BYTES];
50        let be = bits.to_be_bytes();
51        let mut index = 0;
52        while index < be.len() {
53            bytes[index] = be[index];
54            index += 1;
55        }
56        Self { algorithm, bytes }
57    }
58
59    /// Make a 256-bit hash from its 32 bytes, in stored order.
60    pub(crate) const fn from_wide(algorithm: Algorithm, bytes: [u8; MAX_BYTES]) -> Self {
61        Self { algorithm, bytes }
62    }
63
64    /// The algorithm that made the hash.
65    #[must_use]
66    pub const fn algorithm(&self) -> Algorithm {
67        self.algorithm
68    }
69
70    /// The width of the hash in bits.
71    #[must_use]
72    pub const fn bits(&self) -> u32 {
73        self.algorithm.bits()
74    }
75
76    /// The bytes of the hash, first bit in the most significant bit of the first byte.
77    #[must_use]
78    pub fn as_bytes(&self) -> &[u8] {
79        &self.bytes[..self.byte_len()]
80    }
81
82    /// Read a hash of `algorithm` from the bytes [`as_bytes`](Self::as_bytes) returned.
83    ///
84    /// # Errors
85    ///
86    /// Returns [`Error::WrongLength`] when `bytes` isn't `algorithm.bits() / 8` long.
87    pub fn from_bytes(algorithm: Algorithm, bytes: &[u8]) -> Result<Self> {
88        let mut hash = Self {
89            algorithm,
90            bytes: [0; MAX_BYTES],
91        };
92        let expected = hash.byte_len();
93        if bytes.len() != expected {
94            return Err(Error::WrongLength {
95                algorithm,
96                expected,
97                actual: bytes.len(),
98            });
99        }
100        hash.bytes[..expected].copy_from_slice(bytes);
101        Ok(hash)
102    }
103
104    /// The bytes as lower-case hex, two digits a byte, in order: 16 digits for a 64-bit hash and
105    /// 64 for a 256-bit one.
106    ///
107    /// For a v1 image hash, this is the hex Python ImageHash 4.3.2 prints for the same bits; for
108    /// `pdq-v1`, the hex Meta's PDQ reference prints; for `blockhash-v1`, the hex blockhash
109    /// prints.
110    #[must_use]
111    pub fn to_hex(&self) -> String {
112        const DIGITS: &[u8; 16] = b"0123456789abcdef";
113        let mut hex = String::with_capacity(self.byte_len() * 2);
114        for &byte in self.as_bytes() {
115            hex.push(char::from(DIGITS[usize::from(byte >> 4)]));
116            hex.push(char::from(DIGITS[usize::from(byte & 0x0f)]));
117        }
118        hex
119    }
120
121    /// Read a hash of `algorithm` from the hex [`to_hex`](Self::to_hex) returned. Upper-case
122    /// digits are accepted too.
123    ///
124    /// # Errors
125    ///
126    /// Returns [`Error::WrongLength`] when `hex` isn't `algorithm.bits() / 4` digits long, and
127    /// [`Error::InvalidHex`] when it holds anything but hex digits.
128    pub fn from_hex(algorithm: Algorithm, hex: &str) -> Result<Self> {
129        let expected = algorithm.bits() as usize / 4;
130        if hex.len() != expected {
131            return Err(Error::WrongLength {
132                algorithm,
133                expected,
134                actual: hex.len(),
135            });
136        }
137        let digits = hex
138            .bytes()
139            .map(|digit| char::from(digit).to_digit(16).ok_or(Error::InvalidHex))
140            .collect::<Result<Vec<u32>>>()?;
141        // Each digit is below 16, so a pair always fits in a byte...
142        let (pairs, _) = digits.as_chunks::<2>();
143        let bytes: Vec<u8> = pairs.iter().map(|&[high, low]| (high << 4 | low) as u8).collect();
144        Self::from_bytes(algorithm, &bytes)
145    }
146
147    /// The bits as an unsigned integer, first bit most significant, for a 64-bit hash.
148    ///
149    /// # Errors
150    ///
151    /// Returns [`Error::NoIntegerForm`] when the algorithm's hashes aren't 64 bits wide, as
152    /// `pdq-v1` and `blockhash-v1` hashes aren't.
153    pub fn to_u64(&self) -> Result<u64> {
154        if self.bits() != 64 {
155            return Err(Error::NoIntegerForm {
156                algorithm: self.algorithm,
157            });
158        }
159        let [b0, b1, b2, b3, b4, b5, b6, b7, ..] = self.bytes;
160        Ok(u64::from_be_bytes([b0, b1, b2, b3, b4, b5, b6, b7]))
161    }
162
163    /// The bits as a signed integer, for a signed 64-bit column such as SQL's `BIGINT`.
164    ///
165    /// It's the same bit pattern as [`to_u64`](Self::to_u64) read as two's complement, so a hash
166    /// whose first bit is set is negative. Hamming distance on these integers, such as
167    /// `BIT_COUNT(a ^ b)` in MySQL or `bit_count((a # b)::bit(64))` in PostgreSQL 14 and later,
168    /// equals [`distance`](Self::distance).
169    ///
170    /// ```
171    /// use legit_hashes::{Algorithm, Hash};
172    ///
173    /// let hash = Hash::from_hex(Algorithm::AverageV1, "8000000000000001")?;
174    /// assert_eq!(hash.to_i64()?, i64::MIN + 1);
175    /// assert_eq!(Hash::from_i64(Algorithm::AverageV1, i64::MIN + 1)?, hash);
176    /// # Ok::<(), legit_hashes::Error>(())
177    /// ```
178    ///
179    /// # Errors
180    ///
181    /// Returns [`Error::NoIntegerForm`] when the algorithm's hashes aren't 64 bits wide.
182    pub fn to_i64(&self) -> Result<i64> {
183        Ok(i64::from_be_bytes(self.to_u64()?.to_be_bytes()))
184    }
185
186    /// Read a 64-bit hash of `algorithm` from the integer [`to_u64`](Self::to_u64) returned.
187    ///
188    /// # Errors
189    ///
190    /// Returns [`Error::NoIntegerForm`] when the algorithm's hashes aren't 64 bits wide.
191    pub fn from_u64(algorithm: Algorithm, value: u64) -> Result<Self> {
192        if algorithm.bits() != 64 {
193            return Err(Error::NoIntegerForm { algorithm });
194        }
195        Ok(Self::from_bits(algorithm, value))
196    }
197
198    /// Read a 64-bit hash of `algorithm` from the integer [`to_i64`](Self::to_i64) returned.
199    ///
200    /// # Errors
201    ///
202    /// Returns [`Error::NoIntegerForm`] when the algorithm's hashes aren't 64 bits wide.
203    pub fn from_i64(algorithm: Algorithm, value: i64) -> Result<Self> {
204        Self::from_u64(algorithm, u64::from_be_bytes(value.to_be_bytes()))
205    }
206
207    /// The Hamming distance to `other`: how many bits differ, from 0 to [`bits`](Self::bits).
208    ///
209    /// # Errors
210    ///
211    /// Returns [`Error::AlgorithmMismatch`] when the hashes come from different algorithms or
212    /// versions: their bits mean different things, so no distance between them means anything.
213    pub fn distance(&self, other: &Self) -> Result<u32> {
214        if self.algorithm != other.algorithm {
215            return Err(Error::AlgorithmMismatch {
216                left: self.algorithm,
217                right: other.algorithm,
218            });
219        }
220        Ok(self
221            .as_bytes()
222            .iter()
223            .zip(other.as_bytes())
224            .map(|(left, right)| (left ^ right).count_ones())
225            .sum())
226    }
227
228    /// The share of bits that agree with `other`, from 0.0 to 1.0: `1 - distance / bits`.
229    ///
230    /// # Errors
231    ///
232    /// Returns [`Error::AlgorithmMismatch`] when the hashes come from different algorithms or
233    /// versions.
234    pub fn similarity(&self, other: &Self) -> Result<f64> {
235        let distance = self.distance(other)?;
236        Ok(1.0 - f64::from(distance) / f64::from(self.bits()))
237    }
238
239    /// Split the bits into `count` keys for multi-index hashing.
240    ///
241    /// The bits are taken in order and cut into `count` contiguous chunks; when `count` doesn't
242    /// divide the width, the first `bits % count` chunks are one bit wider. Each key is its chunk's
243    /// bits as an unsigned integer, first bit most significant. A 64-bit hash in 4 chunks gives
244    /// four 16-bit keys; in 5 chunks, four 13-bit keys and one 12-bit key. A key holds at most 64
245    /// bits, so a 256-bit hash splits into 4 to 256 chunks.
246    ///
247    /// The guarantee: two hashes of the same algorithm within Hamming distance `d` have an equal
248    /// key at the same position whenever `count >= d + 1`, because `d` differing bits can touch at
249    /// most `d` chunks.
250    ///
251    /// To find near matches in a database, store each key in an indexed integer column. To look a
252    /// hash up within distance `d`, split it with `count = d + 1`, select the rows where any key
253    /// column equals the query's key at the same position, then keep only the candidates whose
254    /// exact [`distance`](Self::distance) is at most `d`:
255    ///
256    /// ```sql
257    /// CREATE TABLE images (id BIGINT PRIMARY KEY, phash BIGINT,
258    ///     k0 INTEGER, k1 INTEGER, k2 INTEGER, k3 INTEGER, k4 INTEGER);
259    /// CREATE INDEX images_k0 ON images (k0); -- and one index for each other key column
260    ///
261    /// SELECT id, phash FROM images
262    /// WHERE k0 = ?1 OR k1 = ?2 OR k2 = ?3 OR k3 = ?4 OR k4 = ?5;
263    /// ```
264    ///
265    /// For a 256-bit hash, `d + 1` keys of `256 / (d + 1)` bits each: 16 keys of 16 bits find
266    /// every match within 15 bits. A key narrower than about 16 bits matches a large share of any
267    /// table, so the lookup reads many candidates; Meta's suggested starting threshold for PDQ, 31
268    /// bits, needs 32 keys of 8 bits, which suits a small table or an index built for Hamming
269    /// search better than this scheme.
270    ///
271    /// ```
272    /// use legit_hashes::{Algorithm, Hash};
273    ///
274    /// let hash = Hash::from_hex(Algorithm::AverageV1, "0123456789abcdef")?;
275    /// assert_eq!(hash.chunks(4)?, [0x0123, 0x4567, 0x89ab, 0xcdef]);
276    ///
277    /// // Within distance 2, so with 3 chunks at least one key matches...
278    /// let near = Hash::from_hex(Algorithm::AverageV1, "0123456789abcdee")?;
279    /// let same = hash.chunks(3)?.iter().zip(near.chunks(3)?).filter(|(a, b)| **a == *b).count();
280    /// assert!(same >= 1);
281    ///
282    /// // A 256-bit hash in 16 keys of 16 bits...
283    /// let wide = Hash::from_hex(Algorithm::PdqV1, &"0123456789abcdef".repeat(4))?;
284    /// assert_eq!(wide.chunks(16)?[..4], [0x0123, 0x4567, 0x89ab, 0xcdef]);
285    /// # Ok::<(), legit_hashes::Error>(())
286    /// ```
287    ///
288    /// # Errors
289    ///
290    /// Returns [`Error::ChunkCount`] unless `count` is from 1 to `bits` and leaves no chunk wider
291    /// than 64 bits: from 1 for a 64-bit hash, from 4 for a 256-bit one.
292    pub fn chunks(&self, count: u32) -> Result<Vec<u64>> {
293        let bits = self.bits();
294        if count < bits.div_ceil(64) || count > bits {
295            return Err(Error::ChunkCount { count, bits });
296        }
297        let mut keys = Vec::with_capacity(count as usize);
298        let mut position = 0;
299        for index in 0..count {
300            let width = bits / count + u32::from(index < bits % count);
301            let key = (position..position + width).fold(0_u64, |key, bit| key << 1 | u64::from(self.bit(bit)));
302            keys.push(key);
303            position += width;
304        }
305        Ok(keys)
306    }
307
308    /// The bit at `index`, counting from the first bit produced.
309    fn bit(&self, index: u32) -> bool {
310        let byte = self.bytes[(index / 8) as usize];
311        byte >> (7 - index % 8) & 1 == 1
312    }
313
314    fn byte_len(&self) -> usize {
315        self.bits() as usize / 8
316    }
317}
318
319impl fmt::Debug for Hash {
320    /// Write the algorithm and the hash's own bytes, 8 or 32 of them.
321    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
322        f.debug_struct("Hash")
323            .field("algorithm", &self.algorithm)
324            .field("bytes", &self.as_bytes())
325            .finish()
326    }
327}
328
329impl fmt::Display for Hash {
330    /// Write the hash as `<algorithm id>:<hex>`, such as `perceptual-v1:c3f00f3c99a5a55a`.
331    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
332        write!(f, "{}:{}", self.algorithm, self.to_hex())
333    }
334}
335
336impl FromStr for Hash {
337    type Err = Error;
338
339    /// Read the `<algorithm id>:<hex>` form [`Display`](fmt::Display) writes.
340    fn from_str(text: &str) -> Result<Self> {
341        let (id, hex) = text.split_once(':').ok_or(Error::MissingSeparator)?;
342        Self::from_hex(Algorithm::from_id(id)?, hex)
343    }
344}
345
346#[cfg(feature = "serde")]
347impl serde::Serialize for Hash {
348    /// Serialize as the `<algorithm id>:<hex>` string.
349    fn serialize<S: serde::Serializer>(&self, serializer: S) -> std::result::Result<S::Ok, S::Error> {
350        serializer.collect_str(self)
351    }
352}
353
354#[cfg(feature = "serde")]
355impl<'de> serde::Deserialize<'de> for Hash {
356    /// Deserialize from the `<algorithm id>:<hex>` string.
357    fn deserialize<D: serde::Deserializer<'de>>(deserializer: D) -> std::result::Result<Self, D::Error> {
358        deserializer.deserialize_str(crate::serde_support::FromStrVisitor::new(
359            "a hash written `<algorithm>:<hex>`",
360        ))
361    }
362}