1use std::io::{BufRead, Write};
4
5use legit_hashes::{Error as HashError, Hash, Signature};
6use serde::Serialize;
7use serde_json::{Map, Value};
8
9use crate::request::Id;
10use crate::{Error, FORMAT, Status, Summary};
11
12#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)]
14#[serde(rename_all = "snake_case")]
15#[non_exhaustive]
16pub enum DistanceError {
17 InvalidRequest,
19 InvalidHash,
21 Mismatch,
24}
25
26impl DistanceError {
27 #[must_use]
33 pub const fn as_str(self) -> &'static str {
34 match self {
35 Self::InvalidRequest => "invalid_request",
36 Self::InvalidHash => "invalid_hash",
37 Self::Mismatch => "mismatch",
38 }
39 }
40}
41
42#[derive(Debug, Clone, PartialEq, Serialize)]
44pub struct Comparison {
45 pub format: u32,
47 pub id: Option<Id>,
49 #[serde(skip_serializing_if = "Option::is_none")]
51 pub line: Option<u64>,
52 pub status: Status,
54 #[serde(skip_serializing_if = "Option::is_none")]
56 pub error_type: Option<DistanceError>,
57 #[serde(skip_serializing_if = "Option::is_none")]
59 pub error: Option<String>,
60 #[serde(skip_serializing_if = "Option::is_none")]
62 pub definition: Option<&'static str>,
63 #[serde(skip_serializing_if = "Option::is_none")]
65 pub distance: Option<u32>,
66 #[serde(skip_serializing_if = "Option::is_none")]
68 pub bits: Option<u32>,
69 #[serde(skip_serializing_if = "Option::is_none")]
71 pub matching: Option<u32>,
72 #[serde(skip_serializing_if = "Option::is_none")]
74 pub values: Option<u32>,
75 #[serde(skip_serializing_if = "Option::is_none")]
77 pub similarity: Option<f64>,
78}
79
80impl Comparison {
81 fn new(id: Option<Id>, line: Option<u64>) -> Self {
82 Self {
83 format: FORMAT,
84 id,
85 line,
86 status: Status::Success,
87 error_type: None,
88 error: None,
89 definition: None,
90 distance: None,
91 bits: None,
92 matching: None,
93 values: None,
94 similarity: None,
95 }
96 }
97
98 fn failed(mut self, code: DistanceError, message: impl Into<String>) -> Self {
99 self.status = Status::Error;
100 self.error_type = Some(code);
101 self.error = Some(message.into());
102 self
103 }
104}
105
106enum Stored {
108 Bit(Hash),
109 Signature(Box<Signature>),
110}
111
112fn parse(name: &str, text: &str) -> Result<Stored, String> {
113 match text.parse::<Hash>() {
114 Ok(hash) => Ok(Stored::Bit(hash)),
115 Err(HashError::NotABitHash(_)) => text
116 .parse::<Signature>()
117 .map(|signature| Stored::Signature(Box::new(signature)))
118 .map_err(|error| format!("`{name}`: {error}")),
119 Err(error) => Err(format!("`{name}`: {error}")),
120 }
121}
122
123#[must_use]
125pub fn compare(line: &[u8], number: u64) -> Comparison {
126 let pair: Map<String, Value> = match serde_json::from_slice(line) {
127 Ok(Value::Object(pair)) => pair,
128 _ => {
129 return Comparison::new(None, Some(number)).failed(
130 DistanceError::InvalidRequest,
131 "a pair is a JSON object with `a` and `b`",
132 );
133 }
134 };
135 let id = pair.get("id").and_then(Id::from_json);
136 let comparison = Comparison::new(id, Some(number));
137 if let Some(unknown) = pair.keys().find(|key| !matches!(key.as_str(), "id" | "a" | "b")) {
138 return comparison.failed(
139 DistanceError::InvalidRequest,
140 format!("a pair has no field `{unknown}`; it takes `id`, `a` and `b`"),
141 );
142 }
143 if pair.get("id").is_some() && comparison.id.is_none() {
144 return comparison.failed(DistanceError::InvalidRequest, "`id` must be a string or an integer");
145 }
146 let (Some(Value::String(a)), Some(Value::String(b))) = (pair.get("a"), pair.get("b")) else {
147 return comparison.failed(DistanceError::InvalidRequest, "a pair needs `a` and `b`, each a string");
148 };
149 compare_stored(comparison, a, b)
150}
151
152#[cfg(feature = "serve")]
155pub(crate) fn compare_pair(id: Id, a: &str, b: &str) -> Comparison {
156 compare_stored(Comparison::new(Some(id), None), a, b)
157}
158
159#[cfg(feature = "serve")]
161pub(crate) fn invalid_pair(id: Id, message: &str) -> Comparison {
162 Comparison::new(Some(id), None).failed(DistanceError::InvalidRequest, message)
163}
164
165fn compare_stored(comparison: Comparison, a: &str, b: &str) -> Comparison {
167 let (a, b) = match (parse("a", a), parse("b", b)) {
168 (Ok(a), Ok(b)) => (a, b),
169 (Err(message), _) | (_, Err(message)) => return comparison.failed(DistanceError::InvalidHash, message),
170 };
171 let mut comparison = comparison;
172 match (a, b) {
173 (Stored::Bit(a), Stored::Bit(b)) => match a.distance(&b) {
174 Ok(distance) => {
175 comparison.definition = Some(a.algorithm().id());
176 comparison.distance = Some(distance);
177 comparison.bits = Some(a.bits());
178 comparison
179 }
180 Err(error) => comparison.failed(DistanceError::Mismatch, error.to_string()),
181 },
182 (Stored::Signature(a), Stored::Signature(b)) => match a.matching(&b) {
183 Ok(matching) => {
184 let values = a.algorithm().value_count();
185 comparison.definition = Some(a.algorithm().id());
186 comparison.matching = Some(matching);
187 comparison.values = Some(values);
188 comparison.similarity = Some(f64::from(matching) / f64::from(values));
189 comparison
190 }
191 Err(error) => comparison.failed(DistanceError::Mismatch, error.to_string()),
192 },
193 (Stored::Bit(a), Stored::Signature(b)) => comparison.failed(
194 DistanceError::Mismatch,
195 format!(
196 "can't compare a `{}` hash with a `{}` signature",
197 a.algorithm(),
198 b.algorithm()
199 ),
200 ),
201 (Stored::Signature(a), Stored::Bit(b)) => comparison.failed(
202 DistanceError::Mismatch,
203 format!(
204 "can't compare a `{}` signature with a `{}` hash",
205 a.algorithm(),
206 b.algorithm()
207 ),
208 ),
209 }
210}
211
212pub fn distances(input: impl BufRead, mut output: impl Write) -> Result<Summary, Error> {
220 let mut summary = Summary::default();
221 for (index, line) in input.split(b'\n').enumerate() {
222 let line = line.map_err(|error| Error::io("couldn't read the input", error))?;
223 if line.iter().all(u8::is_ascii_whitespace) {
224 continue;
225 }
226 let comparison = compare(&line, index as u64 + 1);
227 summary.written += 1;
228 summary.failed += u64::from(comparison.status == Status::Error);
229 let json = serde_json::to_string(&comparison).map_err(|error| Error::Internal(error.to_string()))?;
230 writeln!(output, "{json}")
231 .and_then(|()| output.flush())
232 .map_err(|error| Error::io("couldn't write the output", error))?;
233 }
234 Ok(summary)
235}