rosetta_squint_hash/
multihash.rs1use std::fmt;
6
7use crate::{hex_to_hash, Hash, ImageHashError};
8
9#[derive(Debug, Clone)]
14pub struct ImageMultiHash {
15 pub segment_hashes: Vec<Hash>,
16}
17
18impl ImageMultiHash {
19 pub fn subtract(&self, other: &Self) -> f64 {
32 self.subtract_with(other, None, None)
33 }
34
35 pub fn subtract_with(
36 &self,
37 other: &Self,
38 hamming_cutoff: Option<f64>,
39 bit_error_rate: Option<f64>,
40 ) -> f64 {
41 let (matches, sum_distance) = self.hash_diff(other, hamming_cutoff, bit_error_rate);
42 let max_difference = self.segment_hashes.len() as f64;
43 if matches == 0 {
44 return max_difference;
45 }
46 let max_distance = matches as f64 * self.segment_hashes[0].bit_count() as f64;
47 let tie_breaker = -(sum_distance as f64 / max_distance);
48 let match_score = matches as f64 + tie_breaker;
49 max_difference - match_score
50 }
51
52 pub fn hash_diff(
56 &self,
57 other: &Self,
58 hamming_cutoff: Option<f64>,
59 bit_error_rate: Option<f64>,
60 ) -> (usize, usize) {
61 if self.segment_hashes.is_empty() {
62 return (0, 0);
63 }
64 let cutoff = match hamming_cutoff {
65 Some(c) => c,
66 None => {
67 let ber = bit_error_rate.unwrap_or(0.25);
68 self.segment_hashes[0].bit_count() as f64 * ber
69 }
70 };
71
72 let mut total_matches = 0usize;
73 let mut total_distance = 0usize;
74
75 for sh in &self.segment_hashes {
76 let lowest = other
77 .segment_hashes
78 .iter()
79 .filter_map(|oh| sh.subtract(oh).ok())
80 .min()
81 .unwrap_or(usize::MAX);
82 if (lowest as f64) <= cutoff {
83 total_matches += 1;
84 total_distance += lowest;
85 }
86 }
87 (total_matches, total_distance)
88 }
89
90 pub fn matches(
92 &self,
93 other: &Self,
94 region_cutoff: usize,
95 hamming_cutoff: Option<f64>,
96 bit_error_rate: Option<f64>,
97 ) -> bool {
98 let (m, _) = self.hash_diff(other, hamming_cutoff, bit_error_rate);
99 m >= region_cutoff
100 }
101
102 pub fn best_match<'a>(&self, others: &'a [Self]) -> Option<&'a Self> {
104 others.iter().min_by(|a, b| {
105 self.subtract(a)
106 .partial_cmp(&self.subtract(b))
107 .unwrap_or(std::cmp::Ordering::Equal)
108 })
109 }
110
111 pub fn to_hex(&self) -> String {
113 self.segment_hashes
114 .iter()
115 .map(|h| h.to_hex())
116 .collect::<Vec<_>>()
117 .join(",")
118 }
119}
120
121impl fmt::Display for ImageMultiHash {
122 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
123 f.write_str(&self.to_hex())
124 }
125}
126
127pub fn hex_to_multihash(s: &str) -> Result<ImageMultiHash, ImageHashError> {
131 let hashes: Result<Vec<Hash>, ImageHashError> =
132 s.split(',').map(|part| hex_to_hash(part)).collect();
133 Ok(ImageMultiHash { segment_hashes: hashes? })
134}