legit-hashes 0.2.1

Versioned similarity hashes of images and text, and MinHash set signatures, with index keys for finding near matches
Documentation
//! The hash value, its stored forms, Hamming distance and chunk keys.

use std::fmt;
use std::str::FromStr;

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

/// The longest hash any algorithm produces, in bytes: 256 bits.
const MAX_BYTES: usize = 32;

/// A hash: the algorithm that made it, version included, and its bits.
///
/// A hash is 64 or 256 bits wide, as [`Algorithm::bits`] says, and is held inline, with no heap
/// allocation. Its bits are kept in the order its algorithm defines: the first bit is the most
/// significant bit of the first byte. Every stored form carries the same bits in that order, and
/// the hex reads as the reference implementation of the algorithm prints it.
///
/// | Form | Example | Read back with |
/// |---|---|---|
/// | [`Display`](fmt::Display) | `perceptual-v1:c3f00f3c99a5a55a` | [`FromStr`] |
/// | [`to_hex`](Self::to_hex) | `c3f00f3c99a5a55a` | [`from_hex`](Self::from_hex) |
/// | [`as_bytes`](Self::as_bytes) | `[0xc3, 0xf0, ..]` | [`from_bytes`](Self::from_bytes) |
/// | [`to_u64`](Self::to_u64) | `0xc3f00f3c99a5a55a` | [`from_u64`](Self::from_u64) |
/// | [`to_i64`](Self::to_i64) | the same bits as a signed integer | [`from_i64`](Self::from_i64) |
///
/// A 256-bit hash has the string, hex and byte forms, 64 hex digits or 32 bytes long, and no
/// integer form. Only the string form names the algorithm. With the others, store the algorithm id
/// beside the value, or keep one algorithm per column.
///
/// ```
/// use legit_hashes::{Algorithm, Hash};
///
/// let stored: Hash = "average-v1:0f0f0f0f0f0f0f0f".parse()?;
/// let other = Hash::from_hex(Algorithm::AverageV1, "0f0f0f0f0f0f0f0e")?;
///
/// assert_eq!(stored.distance(&other)?, 1);
/// assert_eq!(stored.to_string(), "average-v1:0f0f0f0f0f0f0f0f");
/// # Ok::<(), legit_hashes::Error>(())
/// ```
#[derive(Clone, PartialEq, Eq, Hash)]
pub struct Hash {
    algorithm: Algorithm,
    bytes: [u8; MAX_BYTES],
}

impl Hash {
    /// Make a 64-bit hash from bits whose most significant is the first bit produced.
    pub(crate) const fn from_bits(algorithm: Algorithm, bits: u64) -> Self {
        let mut bytes = [0; MAX_BYTES];
        let be = bits.to_be_bytes();
        let mut index = 0;
        while index < be.len() {
            bytes[index] = be[index];
            index += 1;
        }
        Self { algorithm, bytes }
    }

    /// Make a 256-bit hash from its 32 bytes, in stored order.
    pub(crate) const fn from_wide(algorithm: Algorithm, bytes: [u8; MAX_BYTES]) -> Self {
        Self { algorithm, bytes }
    }

    /// The algorithm that made the hash.
    #[must_use]
    pub const fn algorithm(&self) -> Algorithm {
        self.algorithm
    }

    /// The width of the hash in bits.
    #[must_use]
    pub const fn bits(&self) -> u32 {
        self.algorithm.bits()
    }

    /// The bytes of the hash, first bit in the most significant bit of the first byte.
    #[must_use]
    pub fn as_bytes(&self) -> &[u8] {
        &self.bytes[..self.byte_len()]
    }

    /// Read a hash of `algorithm` from the bytes [`as_bytes`](Self::as_bytes) returned.
    ///
    /// # Errors
    ///
    /// Returns [`Error::WrongLength`] when `bytes` isn't `algorithm.bits() / 8` long.
    pub fn from_bytes(algorithm: Algorithm, bytes: &[u8]) -> Result<Self> {
        let mut hash = Self {
            algorithm,
            bytes: [0; MAX_BYTES],
        };
        let expected = hash.byte_len();
        if bytes.len() != expected {
            return Err(Error::WrongLength {
                algorithm,
                expected,
                actual: bytes.len(),
            });
        }
        hash.bytes[..expected].copy_from_slice(bytes);
        Ok(hash)
    }

    /// The bytes as lower-case hex, two digits a byte, in order: 16 digits for a 64-bit hash and
    /// 64 for a 256-bit one.
    ///
    /// For a v1 image hash, this is the hex Python ImageHash 4.3.2 prints for the same bits; for
    /// `pdq-v1`, the hex Meta's PDQ reference prints; for `blockhash-v1`, the hex blockhash
    /// prints.
    #[must_use]
    pub fn to_hex(&self) -> String {
        const DIGITS: &[u8; 16] = b"0123456789abcdef";
        let mut hex = String::with_capacity(self.byte_len() * 2);
        for &byte in self.as_bytes() {
            hex.push(char::from(DIGITS[usize::from(byte >> 4)]));
            hex.push(char::from(DIGITS[usize::from(byte & 0x0f)]));
        }
        hex
    }

    /// Read a hash of `algorithm` from the hex [`to_hex`](Self::to_hex) returned. Upper-case
    /// digits are accepted too.
    ///
    /// # Errors
    ///
    /// Returns [`Error::WrongLength`] when `hex` isn't `algorithm.bits() / 4` digits long, and
    /// [`Error::InvalidHex`] when it holds anything but hex digits.
    pub fn from_hex(algorithm: Algorithm, hex: &str) -> Result<Self> {
        let expected = algorithm.bits() as usize / 4;
        if hex.len() != expected {
            return Err(Error::WrongLength {
                algorithm,
                expected,
                actual: hex.len(),
            });
        }
        let digits = hex
            .bytes()
            .map(|digit| char::from(digit).to_digit(16).ok_or(Error::InvalidHex))
            .collect::<Result<Vec<u32>>>()?;
        // Each digit is below 16, so a pair always fits in a byte...
        let (pairs, _) = digits.as_chunks::<2>();
        let bytes: Vec<u8> = pairs.iter().map(|&[high, low]| (high << 4 | low) as u8).collect();
        Self::from_bytes(algorithm, &bytes)
    }

    /// The bits as an unsigned integer, first bit most significant, for a 64-bit hash.
    ///
    /// # Errors
    ///
    /// Returns [`Error::NoIntegerForm`] when the algorithm's hashes aren't 64 bits wide, as
    /// `pdq-v1` and `blockhash-v1` hashes aren't.
    pub fn to_u64(&self) -> Result<u64> {
        if self.bits() != 64 {
            return Err(Error::NoIntegerForm {
                algorithm: self.algorithm,
            });
        }
        let [b0, b1, b2, b3, b4, b5, b6, b7, ..] = self.bytes;
        Ok(u64::from_be_bytes([b0, b1, b2, b3, b4, b5, b6, b7]))
    }

    /// The bits as a signed integer, for a signed 64-bit column such as SQL's `BIGINT`.
    ///
    /// It's the same bit pattern as [`to_u64`](Self::to_u64) read as two's complement, so a hash
    /// whose first bit is set is negative. Hamming distance on these integers, such as
    /// `BIT_COUNT(a ^ b)` in MySQL or `bit_count((a # b)::bit(64))` in PostgreSQL 14 and later,
    /// equals [`distance`](Self::distance).
    ///
    /// ```
    /// use legit_hashes::{Algorithm, Hash};
    ///
    /// let hash = Hash::from_hex(Algorithm::AverageV1, "8000000000000001")?;
    /// assert_eq!(hash.to_i64()?, i64::MIN + 1);
    /// assert_eq!(Hash::from_i64(Algorithm::AverageV1, i64::MIN + 1)?, hash);
    /// # Ok::<(), legit_hashes::Error>(())
    /// ```
    ///
    /// # Errors
    ///
    /// Returns [`Error::NoIntegerForm`] when the algorithm's hashes aren't 64 bits wide.
    pub fn to_i64(&self) -> Result<i64> {
        Ok(i64::from_be_bytes(self.to_u64()?.to_be_bytes()))
    }

    /// Read a 64-bit hash of `algorithm` from the integer [`to_u64`](Self::to_u64) returned.
    ///
    /// # Errors
    ///
    /// Returns [`Error::NoIntegerForm`] when the algorithm's hashes aren't 64 bits wide.
    pub fn from_u64(algorithm: Algorithm, value: u64) -> Result<Self> {
        if algorithm.bits() != 64 {
            return Err(Error::NoIntegerForm { algorithm });
        }
        Ok(Self::from_bits(algorithm, value))
    }

    /// Read a 64-bit hash of `algorithm` from the integer [`to_i64`](Self::to_i64) returned.
    ///
    /// # Errors
    ///
    /// Returns [`Error::NoIntegerForm`] when the algorithm's hashes aren't 64 bits wide.
    pub fn from_i64(algorithm: Algorithm, value: i64) -> Result<Self> {
        Self::from_u64(algorithm, u64::from_be_bytes(value.to_be_bytes()))
    }

    /// The Hamming distance to `other`: how many bits differ, from 0 to [`bits`](Self::bits).
    ///
    /// # Errors
    ///
    /// Returns [`Error::AlgorithmMismatch`] when the hashes come from different algorithms or
    /// versions: their bits mean different things, so no distance between them means anything.
    pub fn distance(&self, other: &Self) -> Result<u32> {
        if self.algorithm != other.algorithm {
            return Err(Error::AlgorithmMismatch {
                left: self.algorithm,
                right: other.algorithm,
            });
        }
        Ok(self
            .as_bytes()
            .iter()
            .zip(other.as_bytes())
            .map(|(left, right)| (left ^ right).count_ones())
            .sum())
    }

    /// The share of bits that agree with `other`, from 0.0 to 1.0: `1 - distance / bits`.
    ///
    /// # Errors
    ///
    /// Returns [`Error::AlgorithmMismatch`] when the hashes come from different algorithms or
    /// versions.
    pub fn similarity(&self, other: &Self) -> Result<f64> {
        let distance = self.distance(other)?;
        Ok(1.0 - f64::from(distance) / f64::from(self.bits()))
    }

    /// Split the bits into `count` keys for multi-index hashing.
    ///
    /// The bits are taken in order and cut into `count` contiguous chunks; when `count` doesn't
    /// divide the width, the first `bits % count` chunks are one bit wider. Each key is its chunk's
    /// bits as an unsigned integer, first bit most significant. A 64-bit hash in 4 chunks gives
    /// four 16-bit keys; in 5 chunks, four 13-bit keys and one 12-bit key. A key holds at most 64
    /// bits, so a 256-bit hash splits into 4 to 256 chunks.
    ///
    /// The guarantee: two hashes of the same algorithm within Hamming distance `d` have an equal
    /// key at the same position whenever `count >= d + 1`, because `d` differing bits can touch at
    /// most `d` chunks.
    ///
    /// To find near matches in a database, store each key in an indexed integer column. To look a
    /// hash up within distance `d`, split it with `count = d + 1`, select the rows where any key
    /// column equals the query's key at the same position, then keep only the candidates whose
    /// exact [`distance`](Self::distance) is at most `d`:
    ///
    /// ```sql
    /// CREATE TABLE images (id BIGINT PRIMARY KEY, phash BIGINT,
    ///     k0 INTEGER, k1 INTEGER, k2 INTEGER, k3 INTEGER, k4 INTEGER);
    /// CREATE INDEX images_k0 ON images (k0); -- and one index for each other key column
    ///
    /// SELECT id, phash FROM images
    /// WHERE k0 = ?1 OR k1 = ?2 OR k2 = ?3 OR k3 = ?4 OR k4 = ?5;
    /// ```
    ///
    /// For a 256-bit hash, `d + 1` keys of `256 / (d + 1)` bits each: 16 keys of 16 bits find
    /// every match within 15 bits. A key narrower than about 16 bits matches a large share of any
    /// table, so the lookup reads many candidates; Meta's suggested starting threshold for PDQ, 31
    /// bits, needs 32 keys of 8 bits, which suits a small table or an index built for Hamming
    /// search better than this scheme.
    ///
    /// ```
    /// use legit_hashes::{Algorithm, Hash};
    ///
    /// let hash = Hash::from_hex(Algorithm::AverageV1, "0123456789abcdef")?;
    /// assert_eq!(hash.chunks(4)?, [0x0123, 0x4567, 0x89ab, 0xcdef]);
    ///
    /// // Within distance 2, so with 3 chunks at least one key matches...
    /// let near = Hash::from_hex(Algorithm::AverageV1, "0123456789abcdee")?;
    /// let same = hash.chunks(3)?.iter().zip(near.chunks(3)?).filter(|(a, b)| **a == *b).count();
    /// assert!(same >= 1);
    ///
    /// // A 256-bit hash in 16 keys of 16 bits...
    /// let wide = Hash::from_hex(Algorithm::PdqV1, &"0123456789abcdef".repeat(4))?;
    /// assert_eq!(wide.chunks(16)?[..4], [0x0123, 0x4567, 0x89ab, 0xcdef]);
    /// # Ok::<(), legit_hashes::Error>(())
    /// ```
    ///
    /// # Errors
    ///
    /// Returns [`Error::ChunkCount`] unless `count` is from 1 to `bits` and leaves no chunk wider
    /// than 64 bits: from 1 for a 64-bit hash, from 4 for a 256-bit one.
    pub fn chunks(&self, count: u32) -> Result<Vec<u64>> {
        let bits = self.bits();
        if count < bits.div_ceil(64) || count > bits {
            return Err(Error::ChunkCount { count, bits });
        }
        let mut keys = Vec::with_capacity(count as usize);
        let mut position = 0;
        for index in 0..count {
            let width = bits / count + u32::from(index < bits % count);
            let key = (position..position + width).fold(0_u64, |key, bit| key << 1 | u64::from(self.bit(bit)));
            keys.push(key);
            position += width;
        }
        Ok(keys)
    }

    /// The bit at `index`, counting from the first bit produced.
    fn bit(&self, index: u32) -> bool {
        let byte = self.bytes[(index / 8) as usize];
        byte >> (7 - index % 8) & 1 == 1
    }

    fn byte_len(&self) -> usize {
        self.bits() as usize / 8
    }
}

impl fmt::Debug for Hash {
    /// Write the algorithm and the hash's own bytes, 8 or 32 of them.
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("Hash")
            .field("algorithm", &self.algorithm)
            .field("bytes", &self.as_bytes())
            .finish()
    }
}

impl fmt::Display for Hash {
    /// Write the hash as `<algorithm id>:<hex>`, such as `perceptual-v1:c3f00f3c99a5a55a`.
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "{}:{}", self.algorithm, self.to_hex())
    }
}

impl FromStr for Hash {
    type Err = Error;

    /// Read the `<algorithm id>:<hex>` form [`Display`](fmt::Display) writes.
    fn from_str(text: &str) -> Result<Self> {
        let (id, hex) = text.split_once(':').ok_or(Error::MissingSeparator)?;
        Self::from_hex(Algorithm::from_id(id)?, hex)
    }
}

#[cfg(feature = "serde")]
impl serde::Serialize for Hash {
    /// Serialize as the `<algorithm id>:<hex>` string.
    fn serialize<S: serde::Serializer>(&self, serializer: S) -> std::result::Result<S::Ok, S::Error> {
        serializer.collect_str(self)
    }
}

#[cfg(feature = "serde")]
impl<'de> serde::Deserialize<'de> for Hash {
    /// Deserialize from the `<algorithm id>:<hex>` string.
    fn deserialize<D: serde::Deserializer<'de>>(deserializer: D) -> std::result::Result<Self, D::Error> {
        deserializer.deserialize_str(crate::serde_support::FromStrVisitor::new(
            "a hash written `<algorithm>:<hex>`",
        ))
    }
}