legit-hashes 0.2.0

Versioned similarity hashes of images and text, and MinHash set signatures, with index keys for finding near matches
Documentation
//! The hash algorithms, each a frozen, versioned definition.

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

use crate::{Error, Hash, Luma, LumaBuf, Result, Rgba, SignatureAlgorithm};

/// A hash algorithm at one version of its definition.
///
/// The version is part of the algorithm's identity. A released definition never changes its
/// output: a change ships as a new variant, such as `PerceptualV2`, beside the old one, which
/// stays. There's no "latest" or "default" algorithm, so upgrading the crate never changes what an
/// application computes or stores.
///
/// ```
/// use legit_hashes::Algorithm;
///
/// let algorithm: Algorithm = "perceptual-v1".parse()?;
/// assert_eq!(algorithm, Algorithm::PerceptualV1);
/// assert_eq!(algorithm.id(), "perceptual-v1");
/// assert_eq!(algorithm.bits(), 64);
/// # Ok::<(), legit_hashes::Error>(())
/// ```
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord)]
#[non_exhaustive]
pub enum Algorithm {
    /// `average-v1`: one bit per pixel of an 8×8 reduction, set when the pixel is brighter than
    /// the mean. See [`average_v1`](crate::average_v1).
    AverageV1,
    /// `difference-v1`: one bit per neighbour pair of a 9×8 reduction, set when the right pixel is
    /// brighter. See [`difference_v1`](crate::difference_v1).
    DifferenceV1,
    /// `perceptual-v1`: the lowest 8×8 frequencies of a 32×32 reduction's DCT, each set when it's
    /// above their median. See [`perceptual_v1`](crate::perceptual_v1).
    PerceptualV1,
    /// `simhash-v1`: Charikar's SimHash of weighted text features, each hashed with SipHash-2-4.
    /// See [`SimHashV1`](crate::SimHashV1).
    SimHashV1,
    /// `pdq-v1`: Meta's PDQ, 256 bits, the 16×16 DCT frequencies of a 64×64 reduction of the luma,
    /// each set when it's above their median. See [`pdq_v1`](crate::pdq_v1).
    PdqV1,
    /// `blockhash-v1`: the block mean value hash of Yang, Gu and Niu, 256 bits, one for each block
    /// of a 16×16 grid, set when the block is brighter than the median of its band. See
    /// [`blockhash_v1`](crate::blockhash_v1).
    BlockhashV1,
}

impl Algorithm {
    /// Every algorithm this version of the crate knows, in the order they were added.
    pub const ALL: [Self; 6] = [
        Self::AverageV1,
        Self::DifferenceV1,
        Self::PerceptualV1,
        Self::SimHashV1,
        Self::PdqV1,
        Self::BlockhashV1,
    ];

    /// The stable text id, such as `perceptual-v1`, used in every stored and printed form.
    #[must_use]
    pub const fn id(self) -> &'static str {
        match self {
            Self::AverageV1 => "average-v1",
            Self::DifferenceV1 => "difference-v1",
            Self::PerceptualV1 => "perceptual-v1",
            Self::SimHashV1 => "simhash-v1",
            Self::PdqV1 => "pdq-v1",
            Self::BlockhashV1 => "blockhash-v1",
        }
    }

    /// The width of the algorithm's hashes in bits: 64, or 256 for `pdq-v1` and `blockhash-v1`.
    #[must_use]
    pub const fn bits(self) -> u32 {
        match self {
            Self::AverageV1 | Self::DifferenceV1 | Self::PerceptualV1 | Self::SimHashV1 => 64,
            Self::PdqV1 | Self::BlockhashV1 => 256,
        }
    }

    /// Whether the algorithm hashes images, rather than text.
    #[must_use]
    pub const fn is_image(self) -> bool {
        match self {
            Self::AverageV1 | Self::DifferenceV1 | Self::PerceptualV1 | Self::PdqV1 | Self::BlockhashV1 => true,
            Self::SimHashV1 => false,
        }
    }

    /// Find the algorithm with the text id `id`, such as `average-v1`. The match is exact.
    ///
    /// # Errors
    ///
    /// Returns [`Error::NotABitHash`] for the id of a [`SignatureAlgorithm`], such as
    /// `minhash-v1`, and [`Error::UnknownAlgorithm`] when no algorithm has that id.
    pub fn from_id(id: &str) -> Result<Self> {
        if let Some(algorithm) = Self::ALL.into_iter().find(|algorithm| algorithm.id() == id) {
            return Ok(algorithm);
        }
        match SignatureAlgorithm::ALL
            .into_iter()
            .find(|algorithm| algorithm.id() == id)
        {
            Some(algorithm) => Err(Error::NotABitHash(algorithm)),
            None => Err(Error::UnknownAlgorithm(id.to_owned())),
        }
    }

    /// Hash an 8-bit luma image with this algorithm.
    ///
    /// The same as calling [`average_v1`](crate::average_v1),
    /// [`difference_v1`](crate::difference_v1) or [`perceptual_v1`](crate::perceptual_v1), for
    /// code that reads the algorithm from configuration. `pdq-v1` hashes the levels as luma, as
    /// [`pdq_v1_luma`](crate::pdq_v1_luma) does, and drops the quality; `blockhash-v1` hashes each
    /// level `v` as the opaque colour `(v, v, v)`, as [`RgbaBuf::from_luma`](crate::RgbaBuf::from_luma)
    /// makes it.
    ///
    /// ```
    /// use legit_hashes::{Algorithm, Luma};
    ///
    /// let pixels = [0, 255, 0, 255];
    /// let hash = Algorithm::DifferenceV1.hash_luma(Luma::new(2, 2, &pixels)?)?;
    /// assert_eq!(hash.algorithm(), Algorithm::DifferenceV1);
    /// # Ok::<(), legit_hashes::Error>(())
    /// ```
    ///
    /// # Errors
    ///
    /// Returns [`Error::NotAnImageAlgorithm`] for an algorithm that hashes text.
    pub fn hash_luma(self, image: Luma<'_>) -> Result<Hash> {
        match self {
            Self::AverageV1 => Ok(crate::average_v1(image)),
            Self::DifferenceV1 => Ok(crate::difference_v1(image)),
            Self::PerceptualV1 => Ok(crate::perceptual_v1(image)),
            Self::PdqV1 => Ok(crate::pdq_v1_luma(image).hash),
            Self::BlockhashV1 => Ok(crate::blockhash_v1(crate::RgbaBuf::from_luma(image).view())),
            Self::SimHashV1 => Err(Error::NotAnImageAlgorithm(self)),
        }
    }

    /// Hash an 8-bit RGBA image with this algorithm.
    ///
    /// `pdq-v1` and `blockhash-v1` hash it as [`pdq_v1`](crate::pdq_v1) and
    /// [`blockhash_v1`](crate::blockhash_v1) do, dropping PDQ's quality. The v1 image hashes
    /// convert it to luma with [`LumaBuf::from_rgba8_v1`], which ignores alpha, and hash that.
    ///
    /// ```
    /// use legit_hashes::{Algorithm, RgbaBuf};
    ///
    /// let image = RgbaBuf::from_rgb8(2, 1, &[255, 0, 0, 0, 0, 255])?;
    /// let hash = Algorithm::BlockhashV1.hash_rgba(image.view())?;
    /// assert_eq!(hash.bits(), 256);
    /// # Ok::<(), legit_hashes::Error>(())
    /// ```
    ///
    /// # Errors
    ///
    /// Returns [`Error::NotAnImageAlgorithm`] for an algorithm that hashes text.
    pub fn hash_rgba(self, image: Rgba<'_>) -> Result<Hash> {
        match self {
            Self::PdqV1 => Ok(crate::pdq_v1(image).hash),
            Self::BlockhashV1 => Ok(crate::blockhash_v1(image)),
            Self::AverageV1 | Self::DifferenceV1 | Self::PerceptualV1 => {
                let luma = LumaBuf::from_rgba8_v1(image.width(), image.height(), image.pixels())?;
                self.hash_luma(luma.view())
            }
            Self::SimHashV1 => Err(Error::NotAnImageAlgorithm(self)),
        }
    }

    /// Decode a PNG or JPEG file and hash it with this algorithm.
    ///
    /// The v1 image hashes read the file with [`decode_luma_v1`](crate::decode_luma_v1) and hash
    /// it with [`hash_luma`](Self::hash_luma). `pdq-v1` and `blockhash-v1` read it with
    /// [`decode_rgba_v1`](crate::decode_rgba_v1) and hash it with [`hash_rgba`](Self::hash_rgba),
    /// so `pdq-v1` hashes a greyscale file as RGB. Both decoders' limits bound what a hostile file
    /// can allocate.
    ///
    /// # Errors
    ///
    /// Returns [`Error::NotAnImageAlgorithm`] for an algorithm that hashes text, and
    /// [`Error::Decode`] when the bytes aren't a PNG or JPEG file that decodes within the limits.
    #[cfg(feature = "image")]
    pub fn hash_encoded(self, bytes: &[u8]) -> Result<Hash> {
        match self {
            Self::PdqV1 | Self::BlockhashV1 => self.hash_rgba(crate::decode_rgba_v1(bytes)?.view()),
            Self::AverageV1 | Self::DifferenceV1 | Self::PerceptualV1 => {
                self.hash_luma(crate::decode_luma_v1(bytes)?.view())
            }
            Self::SimHashV1 => Err(Error::NotAnImageAlgorithm(self)),
        }
    }
}

impl fmt::Display for Algorithm {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.write_str(self.id())
    }
}

impl FromStr for Algorithm {
    type Err = Error;

    fn from_str(id: &str) -> Result<Self> {
        Self::from_id(id)
    }
}

#[cfg(feature = "serde")]
impl serde::Serialize for Algorithm {
    fn serialize<S: serde::Serializer>(&self, serializer: S) -> std::result::Result<S::Ok, S::Error> {
        serializer.serialize_str(self.id())
    }
}

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