Skip to main content

Hash

Struct Hash 

Source
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.

FormExampleRead back with
Displayperceptual-v1:c3f00f3c99a5a55aFromStr
to_hexc3f00f3c99a5a55afrom_hex
as_bytes[0xc3, 0xf0, ..]from_bytes
to_u640xc3f00f3c99a5a55afrom_u64
to_i64the same bits as a signed integerfrom_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

Source

pub const fn algorithm(&self) -> Algorithm

The algorithm that made the hash.

Source

pub const fn bits(&self) -> u32

The width of the hash in bits.

Source

pub fn as_bytes(&self) -> &[u8] ⓘ

The bytes of the hash, first bit in the most significant bit of the first byte.

Source

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.

Source

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.

Source

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.

Source

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.

Source

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.

Source

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.

Source

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.

Source

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.

Source

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.

Source

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 Clone for Hash

Source§

fn clone(&self) -> Self

Returns a duplicate of the value. Read more
1.0.0 (const: unstable) · Source§

fn clone_from(&mut self, source: &Self)

Performs copy-assignment from source. Read more
Source§

impl Debug for Hash

Source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Write the algorithm and the hash’s own bytes, 8 or 32 of them.

Source§

impl<'de> Deserialize<'de> for Hash

Available on crate feature serde only.
Source§

fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error>

Deserialize from the <algorithm id>:<hex> string.

Source§

impl Display for Hash

Source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Write the hash as <algorithm id>:<hex>, such as perceptual-v1:c3f00f3c99a5a55a.

Source§

impl Eq for Hash

Source§

impl FromStr for Hash

Source§

fn from_str(text: &str) -> Result<Self>

Read the <algorithm id>:<hex> form Display writes.

Source§

type Err = Error

The associated error which can be returned from parsing.
Source§

impl Hash for Hash

Source§

fn hash<__H: Hasher>(&self, state: &mut __H)

Feeds this value into the given Hasher. Read more
1.3.0 · Source§

fn hash_slice<H>(data: &[Self], state: &mut H)
where H: Hasher, Self: Sized,

Feeds a slice of this type into the given Hasher. Read more
Source§

impl PartialEq for Hash

Source§

fn eq(&self, other: &Self) -> bool

Equality operator ==. Read more
1.0.0 (const: unstable) · Source§

fn ne(&self, other: &Rhs) -> bool

Inequality operator !=. Read more
Source§

impl Serialize for Hash

Available on crate feature serde only.
Source§

fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error>

Serialize as the <algorithm id>:<hex> string.

Source§

impl StructuralPartialEq for Hash

Auto Trait Implementations§

§

impl Forget for Hash

§

impl Freeze for Hash

§

impl Move for Hash

§

impl RefUnwindSafe for Hash

§

impl Send for Hash

§

impl Sync for Hash

§

impl Unpin for Hash

§

impl UnsafeUnpin for Hash

§

impl UnwindSafe for Hash

Blanket Implementations§

Source§

impl<T> Any for T
where T: 'static + ?Sized,

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
Source§

impl<T> Borrow<T> for T
where T: ?Sized,

Source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
Source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

Source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
Source§

impl<T> CloneToUninit for T
where T: Clone,

Source§

unsafe fn clone_to_uninit(&self, dest: *mut u8)

🔬This is a nightly-only experimental API. (clone_to_uninit)
Performs copy-assignment from self to dest. Read more
Source§

impl<T> DeserializeOwned for T
where T: for<'de> Deserialize<'de>,

Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

Source§

impl<T, U> Into<U> for T
where U: From<T>,

Source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

Source§

impl<T> Same for T

Source§

type Output = T

Should always be Self
Source§

impl<T> ToOwned for T
where T: Clone,

Source§

type Owned = T

The resulting type after obtaining ownership.
Source§

fn to_owned(&self) -> T

Creates owned data from borrowed data, usually by cloning. Read more
Source§

fn clone_into(&self, target: &mut T)

Uses borrowed data to replace owned data, usually by cloning. Read more
Source§

impl<T> ToString for T
where T: Display + ?Sized,

Source§

fn to_string(&self) -> String

Converts the given value to a String. Read more
Source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

Source§

type Error = !

The type returned in the event of a conversion error.
Source§

fn try_from(value: U) -> Result<T, !>

Performs the conversion.
Source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

Source§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
Source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.