legit_hashes/algorithm.rs
1//! The hash algorithms, each a frozen, versioned definition.
2
3use std::fmt;
4use std::str::FromStr;
5
6use crate::{Error, Hash, Luma, LumaBuf, Result, Rgba, SignatureAlgorithm};
7
8/// A hash algorithm at one version of its definition.
9///
10/// The version is part of the algorithm's identity. A released definition never changes its
11/// output: a change ships as a new variant, such as `PerceptualV2`, beside the old one, which
12/// stays. There's no "latest" or "default" algorithm, so upgrading the crate never changes what an
13/// application computes or stores.
14///
15/// ```
16/// use legit_hashes::Algorithm;
17///
18/// let algorithm: Algorithm = "perceptual-v1".parse()?;
19/// assert_eq!(algorithm, Algorithm::PerceptualV1);
20/// assert_eq!(algorithm.id(), "perceptual-v1");
21/// assert_eq!(algorithm.bits(), 64);
22/// # Ok::<(), legit_hashes::Error>(())
23/// ```
24#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord)]
25#[non_exhaustive]
26pub enum Algorithm {
27 /// `average-v1`: one bit per pixel of an 8×8 reduction, set when the pixel is brighter than
28 /// the mean. See [`average_v1`](crate::average_v1).
29 AverageV1,
30 /// `difference-v1`: one bit per neighbour pair of a 9×8 reduction, set when the right pixel is
31 /// brighter. See [`difference_v1`](crate::difference_v1).
32 DifferenceV1,
33 /// `perceptual-v1`: the lowest 8×8 frequencies of a 32×32 reduction's DCT, each set when it's
34 /// above their median. See [`perceptual_v1`](crate::perceptual_v1).
35 PerceptualV1,
36 /// `simhash-v1`: Charikar's SimHash of weighted text features, each hashed with SipHash-2-4.
37 /// See [`SimHashV1`](crate::SimHashV1).
38 SimHashV1,
39 /// `pdq-v1`: Meta's PDQ, 256 bits, the 16×16 DCT frequencies of a 64×64 reduction of the luma,
40 /// each set when it's above their median. See [`pdq_v1`](crate::pdq_v1).
41 PdqV1,
42 /// `blockhash-v1`: the block mean value hash of Yang, Gu and Niu, 256 bits, one for each block
43 /// of a 16×16 grid, set when the block is brighter than the median of its band. See
44 /// [`blockhash_v1`](crate::blockhash_v1).
45 BlockhashV1,
46}
47
48impl Algorithm {
49 /// Every algorithm this version of the crate knows, in the order they were added.
50 pub const ALL: [Self; 6] = [
51 Self::AverageV1,
52 Self::DifferenceV1,
53 Self::PerceptualV1,
54 Self::SimHashV1,
55 Self::PdqV1,
56 Self::BlockhashV1,
57 ];
58
59 /// The stable text id, such as `perceptual-v1`, used in every stored and printed form.
60 #[must_use]
61 pub const fn id(self) -> &'static str {
62 match self {
63 Self::AverageV1 => "average-v1",
64 Self::DifferenceV1 => "difference-v1",
65 Self::PerceptualV1 => "perceptual-v1",
66 Self::SimHashV1 => "simhash-v1",
67 Self::PdqV1 => "pdq-v1",
68 Self::BlockhashV1 => "blockhash-v1",
69 }
70 }
71
72 /// The width of the algorithm's hashes in bits: 64, or 256 for `pdq-v1` and `blockhash-v1`.
73 #[must_use]
74 pub const fn bits(self) -> u32 {
75 match self {
76 Self::AverageV1 | Self::DifferenceV1 | Self::PerceptualV1 | Self::SimHashV1 => 64,
77 Self::PdqV1 | Self::BlockhashV1 => 256,
78 }
79 }
80
81 /// Whether the algorithm hashes images, rather than text.
82 #[must_use]
83 pub const fn is_image(self) -> bool {
84 match self {
85 Self::AverageV1 | Self::DifferenceV1 | Self::PerceptualV1 | Self::PdqV1 | Self::BlockhashV1 => true,
86 Self::SimHashV1 => false,
87 }
88 }
89
90 /// Find the algorithm with the text id `id`, such as `average-v1`. The match is exact.
91 ///
92 /// # Errors
93 ///
94 /// Returns [`Error::NotABitHash`] for the id of a [`SignatureAlgorithm`], such as
95 /// `minhash-v1`, and [`Error::UnknownAlgorithm`] when no algorithm has that id.
96 pub fn from_id(id: &str) -> Result<Self> {
97 if let Some(algorithm) = Self::ALL.into_iter().find(|algorithm| algorithm.id() == id) {
98 return Ok(algorithm);
99 }
100 match SignatureAlgorithm::ALL
101 .into_iter()
102 .find(|algorithm| algorithm.id() == id)
103 {
104 Some(algorithm) => Err(Error::NotABitHash(algorithm)),
105 None => Err(Error::UnknownAlgorithm(id.to_owned())),
106 }
107 }
108
109 /// Hash an 8-bit luma image with this algorithm.
110 ///
111 /// The same as calling [`average_v1`](crate::average_v1),
112 /// [`difference_v1`](crate::difference_v1) or [`perceptual_v1`](crate::perceptual_v1), for
113 /// code that reads the algorithm from configuration. `pdq-v1` hashes the levels as luma, as
114 /// [`pdq_v1_luma`](crate::pdq_v1_luma) does, and drops the quality; `blockhash-v1` hashes each
115 /// level `v` as the opaque colour `(v, v, v)`, as [`RgbaBuf::from_luma`](crate::RgbaBuf::from_luma)
116 /// makes it.
117 ///
118 /// ```
119 /// use legit_hashes::{Algorithm, Luma};
120 ///
121 /// let pixels = [0, 255, 0, 255];
122 /// let hash = Algorithm::DifferenceV1.hash_luma(Luma::new(2, 2, &pixels)?)?;
123 /// assert_eq!(hash.algorithm(), Algorithm::DifferenceV1);
124 /// # Ok::<(), legit_hashes::Error>(())
125 /// ```
126 ///
127 /// # Errors
128 ///
129 /// Returns [`Error::NotAnImageAlgorithm`] for an algorithm that hashes text.
130 pub fn hash_luma(self, image: Luma<'_>) -> Result<Hash> {
131 match self {
132 Self::AverageV1 => Ok(crate::average_v1(image)),
133 Self::DifferenceV1 => Ok(crate::difference_v1(image)),
134 Self::PerceptualV1 => Ok(crate::perceptual_v1(image)),
135 Self::PdqV1 => Ok(crate::pdq_v1_luma(image).hash),
136 Self::BlockhashV1 => Ok(crate::blockhash_v1(crate::RgbaBuf::from_luma(image).view())),
137 Self::SimHashV1 => Err(Error::NotAnImageAlgorithm(self)),
138 }
139 }
140
141 /// Hash an 8-bit RGBA image with this algorithm.
142 ///
143 /// `pdq-v1` and `blockhash-v1` hash it as [`pdq_v1`](crate::pdq_v1) and
144 /// [`blockhash_v1`](crate::blockhash_v1) do, dropping PDQ's quality. The v1 image hashes
145 /// convert it to luma with [`LumaBuf::from_rgba8_v1`], which ignores alpha, and hash that.
146 ///
147 /// ```
148 /// use legit_hashes::{Algorithm, RgbaBuf};
149 ///
150 /// let image = RgbaBuf::from_rgb8(2, 1, &[255, 0, 0, 0, 0, 255])?;
151 /// let hash = Algorithm::BlockhashV1.hash_rgba(image.view())?;
152 /// assert_eq!(hash.bits(), 256);
153 /// # Ok::<(), legit_hashes::Error>(())
154 /// ```
155 ///
156 /// # Errors
157 ///
158 /// Returns [`Error::NotAnImageAlgorithm`] for an algorithm that hashes text.
159 pub fn hash_rgba(self, image: Rgba<'_>) -> Result<Hash> {
160 match self {
161 Self::PdqV1 => Ok(crate::pdq_v1(image).hash),
162 Self::BlockhashV1 => Ok(crate::blockhash_v1(image)),
163 Self::AverageV1 | Self::DifferenceV1 | Self::PerceptualV1 => {
164 let luma = LumaBuf::from_rgba8_v1(image.width(), image.height(), image.pixels())?;
165 self.hash_luma(luma.view())
166 }
167 Self::SimHashV1 => Err(Error::NotAnImageAlgorithm(self)),
168 }
169 }
170
171 /// Decode a PNG or JPEG file and hash it with this algorithm.
172 ///
173 /// The v1 image hashes read the file with [`decode_luma_v1`](crate::decode_luma_v1) and hash
174 /// it with [`hash_luma`](Self::hash_luma). `pdq-v1` and `blockhash-v1` read it with
175 /// [`decode_rgba_v1`](crate::decode_rgba_v1) and hash it with [`hash_rgba`](Self::hash_rgba),
176 /// so `pdq-v1` hashes a greyscale file as RGB. Both decoders' limits bound what a hostile file
177 /// can allocate.
178 ///
179 /// # Errors
180 ///
181 /// Returns [`Error::NotAnImageAlgorithm`] for an algorithm that hashes text, and
182 /// [`Error::Decode`] when the bytes aren't a PNG or JPEG file that decodes within the limits.
183 #[cfg(feature = "image")]
184 pub fn hash_encoded(self, bytes: &[u8]) -> Result<Hash> {
185 match self {
186 Self::PdqV1 | Self::BlockhashV1 => self.hash_rgba(crate::decode_rgba_v1(bytes)?.view()),
187 Self::AverageV1 | Self::DifferenceV1 | Self::PerceptualV1 => {
188 self.hash_luma(crate::decode_luma_v1(bytes)?.view())
189 }
190 Self::SimHashV1 => Err(Error::NotAnImageAlgorithm(self)),
191 }
192 }
193}
194
195impl fmt::Display for Algorithm {
196 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
197 f.write_str(self.id())
198 }
199}
200
201impl FromStr for Algorithm {
202 type Err = Error;
203
204 fn from_str(id: &str) -> Result<Self> {
205 Self::from_id(id)
206 }
207}
208
209#[cfg(feature = "serde")]
210impl serde::Serialize for Algorithm {
211 fn serialize<S: serde::Serializer>(&self, serializer: S) -> std::result::Result<S::Ok, S::Error> {
212 serializer.serialize_str(self.id())
213 }
214}
215
216#[cfg(feature = "serde")]
217impl<'de> serde::Deserialize<'de> for Algorithm {
218 fn deserialize<D: serde::Deserializer<'de>>(deserializer: D) -> std::result::Result<Self, D::Error> {
219 deserializer.deserialize_str(crate::serde_support::FromStrVisitor::new("a hash algorithm id"))
220 }
221}