pub struct Hash { /* private fields */ }Expand description
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 | perceptual-v1:c3f00f3c99a5a55a | FromStr |
to_hex | c3f00f3c99a5a55a | from_hex |
as_bytes | [0xc3, 0xf0, ..] | from_bytes |
to_u64 | 0xc3f00f3c99a5a55a | from_u64 |
to_i64 | the same bits as a signed integer | 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");Implementations§
Source§impl Hash
impl Hash
Sourcepub fn as_bytes(&self) -> &[u8] ⓘ
pub fn as_bytes(&self) -> &[u8] ⓘ
The bytes of the hash, first bit in the most significant bit of the first byte.
Sourcepub fn from_bytes(algorithm: Algorithm, bytes: &[u8]) -> Result<Self>
pub fn from_bytes(algorithm: Algorithm, bytes: &[u8]) -> Result<Self>
Read a hash of algorithm from the bytes as_bytes returned.
§Errors
Returns Error::WrongLength when bytes isn’t algorithm.bits() / 8 long.
Sourcepub fn to_hex(&self) -> String
pub fn to_hex(&self) -> String
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.
Sourcepub fn from_hex(algorithm: Algorithm, hex: &str) -> Result<Self>
pub fn from_hex(algorithm: Algorithm, hex: &str) -> Result<Self>
Read a hash of algorithm from the hex 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.
Sourcepub fn to_u64(&self) -> Result<u64>
pub fn to_u64(&self) -> Result<u64>
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.
Sourcepub fn to_i64(&self) -> Result<i64>
pub fn to_i64(&self) -> Result<i64>
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 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.
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);§Errors
Returns Error::NoIntegerForm when the algorithm’s hashes aren’t 64 bits wide.
Sourcepub fn from_u64(algorithm: Algorithm, value: u64) -> Result<Self>
pub fn from_u64(algorithm: Algorithm, value: u64) -> Result<Self>
Read a 64-bit hash of algorithm from the integer to_u64 returned.
§Errors
Returns Error::NoIntegerForm when the algorithm’s hashes aren’t 64 bits wide.
Sourcepub fn from_i64(algorithm: Algorithm, value: i64) -> Result<Self>
pub fn from_i64(algorithm: Algorithm, value: i64) -> Result<Self>
Read a 64-bit hash of algorithm from the integer to_i64 returned.
§Errors
Returns Error::NoIntegerForm when the algorithm’s hashes aren’t 64 bits wide.
Sourcepub fn distance(&self, other: &Self) -> Result<u32>
pub fn distance(&self, other: &Self) -> Result<u32>
The Hamming distance to other: how many bits differ, from 0 to 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.
Sourcepub fn similarity(&self, other: &Self) -> Result<f64>
pub fn similarity(&self, other: &Self) -> Result<f64>
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.
Sourcepub fn chunks(&self, count: u32) -> Result<Vec<u64>>
pub fn chunks(&self, count: u32) -> Result<Vec<u64>>
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 is at most d:
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]);§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.
Trait Implementations§
Source§impl<'de> Deserialize<'de> for Hash
Available on crate feature serde only.
impl<'de> Deserialize<'de> for Hash
serde only.Source§fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error>
fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error>
Deserialize from the <algorithm id>:<hex> string.