legit_hashes/signature.rs
1//! Set signatures: their definitions, stored forms, similarity estimate and band keys.
2
3use std::fmt;
4use std::hash::Hasher;
5use std::str::FromStr;
6
7use siphasher::sip::SipHasher24;
8
9use crate::{Algorithm, Error, Result};
10
11/// The number of values in a signature of each algorithm.
12const VALUES: usize = 128;
13
14/// A set-signature algorithm at one version of its definition.
15///
16/// A signature estimates how much two sets overlap, value by value, where a bit hash
17/// ([`Algorithm`]) is compared bit by bit. The two never compare with each other. As with
18/// [`Algorithm`], the version is part of the identity and a released definition never changes its
19/// output.
20///
21/// `minhash-v1` and `minhash-legacy-v1` are datasketch's two 32-bit MinHash constructions, its
22/// current default and the one it used before 2.0.0. Their signatures have the same shape but
23/// different values, so they never compare, merge or parse as each other: choose one per stored
24/// column.
25///
26/// ```
27/// use legit_hashes::SignatureAlgorithm;
28///
29/// let algorithm: SignatureAlgorithm = "minhash-v1".parse()?;
30/// assert_eq!(algorithm, SignatureAlgorithm::MinHashV1);
31/// assert_eq!(algorithm.value_count(), 128);
32/// # Ok::<(), legit_hashes::Error>(())
33/// ```
34#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord)]
35#[non_exhaustive]
36pub enum SignatureAlgorithm {
37 /// `minhash-v1`: Broder's MinHash, 128 values of 32 bits, as the Python library datasketch
38 /// computes it by default since 2.0.0, its `affine32` scheme. See
39 /// [`minhash_v1`](crate::minhash_v1).
40 MinHashV1,
41 /// `minhash-legacy-v1`: Broder's MinHash, 128 values of 32 bits, as datasketch computed it by
42 /// default before 2.0.0, its `legacy` scheme. See
43 /// [`minhash_legacy_v1`](crate::minhash_legacy_v1).
44 MinHashLegacyV1,
45}
46
47impl SignatureAlgorithm {
48 /// Every signature algorithm this version of the crate knows, in the order they were added.
49 ///
50 /// ```
51 /// use legit_hashes::SignatureAlgorithm;
52 ///
53 /// assert_eq!(
54 /// SignatureAlgorithm::ALL,
55 /// [SignatureAlgorithm::MinHashV1, SignatureAlgorithm::MinHashLegacyV1]
56 /// );
57 /// ```
58 pub const ALL: [Self; 2] = [Self::MinHashV1, Self::MinHashLegacyV1];
59
60 /// The stable text id, such as `minhash-v1`, used in every stored and printed form.
61 ///
62 /// ```
63 /// use legit_hashes::SignatureAlgorithm;
64 ///
65 /// assert_eq!(SignatureAlgorithm::MinHashV1.id(), "minhash-v1");
66 /// ```
67 #[must_use]
68 pub const fn id(self) -> &'static str {
69 match self {
70 Self::MinHashV1 => "minhash-v1",
71 Self::MinHashLegacyV1 => "minhash-legacy-v1",
72 }
73 }
74
75 /// The number of 32-bit values in the algorithm's signatures: 128 for both MinHash definitions.
76 ///
77 /// ```
78 /// use legit_hashes::SignatureAlgorithm;
79 ///
80 /// assert_eq!(SignatureAlgorithm::MinHashV1.value_count(), 128);
81 /// ```
82 #[must_use]
83 pub const fn value_count(self) -> u32 {
84 match self {
85 Self::MinHashV1 | Self::MinHashLegacyV1 => 128,
86 }
87 }
88
89 /// Find the signature algorithm with the text id `id`, such as `minhash-v1`. The match is
90 /// exact.
91 ///
92 /// ```
93 /// use legit_hashes::{Algorithm, Error, SignatureAlgorithm};
94 ///
95 /// assert_eq!(SignatureAlgorithm::from_id("minhash-v1")?, SignatureAlgorithm::MinHashV1);
96 /// assert_eq!(
97 /// SignatureAlgorithm::from_id("simhash-v1"),
98 /// Err(Error::NotASignature(Algorithm::SimHashV1))
99 /// );
100 /// # Ok::<(), legit_hashes::Error>(())
101 /// ```
102 ///
103 /// # Errors
104 ///
105 /// Returns [`Error::NotASignature`] for the id of a bit-hash [`Algorithm`], and
106 /// [`Error::UnknownAlgorithm`] when no algorithm has that id.
107 pub fn from_id(id: &str) -> Result<Self> {
108 if let Some(algorithm) = Self::ALL.into_iter().find(|algorithm| algorithm.id() == id) {
109 return Ok(algorithm);
110 }
111 match Algorithm::ALL.into_iter().find(|algorithm| algorithm.id() == id) {
112 Some(algorithm) => Err(Error::NotASignature(algorithm)),
113 None => Err(Error::UnknownAlgorithm(id.to_owned())),
114 }
115 }
116}
117
118impl fmt::Display for SignatureAlgorithm {
119 /// Write the id, such as `minhash-v1`.
120 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
121 f.write_str(self.id())
122 }
123}
124
125impl FromStr for SignatureAlgorithm {
126 type Err = Error;
127
128 /// Read an id, as [`from_id`](Self::from_id) does.
129 fn from_str(id: &str) -> Result<Self> {
130 Self::from_id(id)
131 }
132}
133
134#[cfg(feature = "serde")]
135impl serde::Serialize for SignatureAlgorithm {
136 /// Serialize as the id.
137 fn serialize<S: serde::Serializer>(&self, serializer: S) -> std::result::Result<S::Ok, S::Error> {
138 serializer.serialize_str(self.id())
139 }
140}
141
142#[cfg(feature = "serde")]
143impl<'de> serde::Deserialize<'de> for SignatureAlgorithm {
144 /// Deserialize from the id.
145 fn deserialize<D: serde::Deserializer<'de>>(deserializer: D) -> std::result::Result<Self, D::Error> {
146 deserializer.deserialize_str(crate::serde_support::FromStrVisitor::new("a signature algorithm id"))
147 }
148}
149
150/// A set signature: the algorithm that made it, version included, and its values.
151///
152/// A MinHash signature is 128 values of 32 bits, held inline. Two signatures estimate the
153/// Jaccard similarity of their sets, the size of the intersection over the size of the union, by
154/// the share of positions whose values are equal: see [`similarity`](Self::similarity). The
155/// Hamming distance of a [`Hash`](struct@crate::Hash) means nothing here, so the two types never
156/// compare.
157///
158/// | Form | Example | Read back with |
159/// |---|---|---|
160/// | [`Display`](fmt::Display) | `minhash-v1:` and 1,024 hex digits | [`FromStr`] |
161/// | [`to_hex`](Self::to_hex) | 1,024 hex digits | [`from_hex`](Self::from_hex) |
162/// | [`to_bytes`](Self::to_bytes) | 512 bytes | [`from_bytes`](Self::from_bytes) |
163/// | [`values`](Self::values) | 128 `u32` values | [`from_values`](Self::from_values) |
164///
165/// The bytes are the values in order, each big-endian, four bytes a value, and the hex is the
166/// bytes, two lower-case digits a byte, so each run of eight digits reads as a value. datasketch's
167/// `digest()` lists the same values in the same order. Only the string form names the algorithm.
168/// With the others, store the algorithm id beside the value, or keep one algorithm per column: the
169/// values of `minhash-v1` and `minhash-legacy-v1` look alike, so the bytes, hex and values read
170/// back as whichever algorithm the caller names.
171///
172/// ```
173/// use legit_hashes::{Signature, minhash_v1};
174///
175/// let signature = minhash_v1(["stored", "hashes", "outlive", "code"]);
176/// let stored = signature.to_string();
177/// assert!(stored.starts_with("minhash-v1:"));
178/// assert_eq!(stored.parse::<Signature>()?, signature);
179/// # Ok::<(), legit_hashes::Error>(())
180/// ```
181#[derive(Debug, Clone, PartialEq, Eq, Hash)]
182pub struct Signature {
183 algorithm: SignatureAlgorithm,
184 values: [u32; VALUES],
185}
186
187impl Signature {
188 /// Make a signature from its values.
189 pub(crate) const fn from_array(algorithm: SignatureAlgorithm, values: [u32; VALUES]) -> Self {
190 Self { algorithm, values }
191 }
192
193 /// The algorithm that made the signature.
194 ///
195 /// ```
196 /// use legit_hashes::{SignatureAlgorithm, minhash_v1};
197 ///
198 /// assert_eq!(minhash_v1(["a"]).algorithm(), SignatureAlgorithm::MinHashV1);
199 /// ```
200 #[must_use]
201 pub const fn algorithm(&self) -> SignatureAlgorithm {
202 self.algorithm
203 }
204
205 /// The values, in the order the algorithm defines: for a MinHash signature, one for each of its
206 /// 128 permutations, in datasketch's order.
207 ///
208 /// ```
209 /// use legit_hashes::minhash_v1;
210 ///
211 /// let empty = minhash_v1::<&str>([]);
212 /// assert_eq!(empty.values(), [u32::MAX; 128]);
213 /// ```
214 #[must_use]
215 pub fn values(&self) -> &[u32] {
216 &self.values
217 }
218
219 /// Read a signature of `algorithm` from the values [`values`](Self::values) returned, or from
220 /// the values of datasketch's `digest()`: for `minhash-v1` from a `MinHash` of its default
221 /// scheme, for `minhash-legacy-v1` from one of `scheme="legacy"` or made before 2.0.0.
222 ///
223 /// ```
224 /// use legit_hashes::{Signature, SignatureAlgorithm, minhash_v1};
225 ///
226 /// let signature = minhash_v1(["a", "b"]);
227 /// let read = Signature::from_values(SignatureAlgorithm::MinHashV1, signature.values())?;
228 /// assert_eq!(read, signature);
229 /// # Ok::<(), legit_hashes::Error>(())
230 /// ```
231 ///
232 /// # Errors
233 ///
234 /// Returns [`Error::SignatureLength`] when `values` doesn't hold exactly
235 /// `algorithm.value_count()` values.
236 pub fn from_values(algorithm: SignatureAlgorithm, values: &[u32]) -> Result<Self> {
237 let values = <[u32; VALUES]>::try_from(values).map_err(|_| Error::SignatureLength {
238 algorithm,
239 expected: VALUES,
240 actual: values.len(),
241 })?;
242 Ok(Self::from_array(algorithm, values))
243 }
244
245 /// Whether the signature is that of the empty set: every value at `u32::MAX`, as no feature
246 /// was added.
247 ///
248 /// Two empty signatures are equal, so they estimate a similarity of 1.0, as datasketch's do.
249 /// Check this before treating two signatures as near duplicates: two empty texts aren't.
250 ///
251 /// ```
252 /// use legit_hashes::minhash_v1;
253 ///
254 /// let empty = minhash_v1::<&str>([]);
255 /// assert!(empty.is_empty());
256 /// assert_eq!(empty.similarity(&minhash_v1::<&str>([]))?, 1.0);
257 /// assert!(!minhash_v1([""]).is_empty());
258 /// # Ok::<(), legit_hashes::Error>(())
259 /// ```
260 #[must_use]
261 pub fn is_empty(&self) -> bool {
262 self.values.iter().all(|&value| value == u32::MAX)
263 }
264
265 /// The bytes: each value big-endian, in order, 512 bytes for a MinHash signature.
266 ///
267 /// ```
268 /// use legit_hashes::minhash_v1;
269 ///
270 /// let signature = minhash_v1(["a"]);
271 /// let bytes = signature.to_bytes();
272 /// assert_eq!(bytes.len(), 512);
273 /// assert_eq!(bytes[..4], signature.values()[0].to_be_bytes());
274 /// ```
275 #[must_use]
276 pub fn to_bytes(&self) -> Vec<u8> {
277 self.values.iter().flat_map(|value| value.to_be_bytes()).collect()
278 }
279
280 /// Read a signature of `algorithm` from the bytes [`to_bytes`](Self::to_bytes) returned.
281 ///
282 /// ```
283 /// use legit_hashes::{Signature, SignatureAlgorithm, minhash_v1};
284 ///
285 /// let signature = minhash_v1(["a"]);
286 /// assert_eq!(Signature::from_bytes(SignatureAlgorithm::MinHashV1, &signature.to_bytes())?, signature);
287 /// # Ok::<(), legit_hashes::Error>(())
288 /// ```
289 ///
290 /// # Errors
291 ///
292 /// Returns [`Error::SignatureLength`] when `bytes` isn't four bytes for each of the
293 /// algorithm's values long.
294 pub fn from_bytes(algorithm: SignatureAlgorithm, bytes: &[u8]) -> Result<Self> {
295 let (words, rest) = bytes.as_chunks::<4>();
296 if words.len() != VALUES || !rest.is_empty() {
297 return Err(Error::SignatureLength {
298 algorithm,
299 expected: VALUES * 4,
300 actual: bytes.len(),
301 });
302 }
303 let mut values = [0; VALUES];
304 for (value, word) in values.iter_mut().zip(words) {
305 *value = u32::from_be_bytes(*word);
306 }
307 Ok(Self::from_array(algorithm, values))
308 }
309
310 /// The bytes as lower-case hex, two digits a byte, in order: 1,024 digits for a MinHash
311 /// signature, eight for each value.
312 ///
313 /// ```
314 /// use legit_hashes::minhash_v1;
315 ///
316 /// let signature = minhash_v1(["a"]);
317 /// assert_eq!(signature.to_hex()[..8], format!("{:08x}", signature.values()[0]));
318 /// ```
319 #[must_use]
320 pub fn to_hex(&self) -> String {
321 const DIGITS: &[u8; 16] = b"0123456789abcdef";
322 let mut hex = String::with_capacity(VALUES * 8);
323 for byte in self.to_bytes() {
324 hex.push(char::from(DIGITS[usize::from(byte >> 4)]));
325 hex.push(char::from(DIGITS[usize::from(byte & 0x0f)]));
326 }
327 hex
328 }
329
330 /// Read a signature of `algorithm` from the hex [`to_hex`](Self::to_hex) returned. Upper-case
331 /// digits are accepted too.
332 ///
333 /// ```
334 /// use legit_hashes::{Signature, SignatureAlgorithm, minhash_v1};
335 ///
336 /// let signature = minhash_v1(["a"]);
337 /// let hex = signature.to_hex().to_uppercase();
338 /// assert_eq!(Signature::from_hex(SignatureAlgorithm::MinHashV1, &hex)?, signature);
339 /// # Ok::<(), legit_hashes::Error>(())
340 /// ```
341 ///
342 /// # Errors
343 ///
344 /// Returns [`Error::SignatureLength`] when `hex` isn't eight digits for each of the
345 /// algorithm's values long, and [`Error::InvalidHex`] when it holds anything but hex digits.
346 pub fn from_hex(algorithm: SignatureAlgorithm, hex: &str) -> Result<Self> {
347 if hex.len() != VALUES * 8 {
348 return Err(Error::SignatureLength {
349 algorithm,
350 expected: VALUES * 8,
351 actual: hex.len(),
352 });
353 }
354 let digits = hex
355 .bytes()
356 .map(|digit| char::from(digit).to_digit(16).ok_or(Error::InvalidHex))
357 .collect::<Result<Vec<u32>>>()?;
358 let (groups, _) = digits.as_chunks::<8>();
359 let mut values = [0; VALUES];
360 for (value, group) in values.iter_mut().zip(groups) {
361 *value = group.iter().fold(0, |value, &digit| value << 4 | digit);
362 }
363 Ok(Self::from_array(algorithm, values))
364 }
365
366 /// How many positions hold equal values in the two signatures, from 0 to the algorithm's
367 /// [`value_count`](SignatureAlgorithm::value_count): the exact fraction behind
368 /// [`similarity`](Self::similarity), `matching / 128` for a MinHash signature.
369 ///
370 /// ```
371 /// use legit_hashes::{minhash_legacy_v1, minhash_v1};
372 ///
373 /// let first = minhash_v1(["a", "b", "c"]);
374 /// assert_eq!(first.matching(&first)?, 128);
375 /// // The same set under the other definition doesn't compare...
376 /// assert!(first.matching(&minhash_legacy_v1(["a", "b", "c"])).is_err());
377 /// # Ok::<(), legit_hashes::Error>(())
378 /// ```
379 ///
380 /// # Errors
381 ///
382 /// Returns [`Error::SignatureMismatch`] when the signatures come from different algorithms or
383 /// versions, such as `minhash-v1` and `minhash-legacy-v1`.
384 pub fn matching(&self, other: &Self) -> Result<u32> {
385 self.check_same(other)?;
386 Ok(self
387 .values
388 .iter()
389 .zip(&other.values)
390 .map(|(left, right)| u32::from(left == right))
391 .sum())
392 }
393
394 /// The estimate of the Jaccard similarity of the two sets, from 0.0 to 1.0: the share of
395 /// positions whose values are equal, [`matching`](Self::matching) over the value count.
396 ///
397 /// Each position agrees with probability equal to the true similarity, so with 128 values the
398 /// estimate's standard error is `sqrt(s(1 - s) / 128)`: at most about 0.044, at `s = 0.5`. Two
399 /// empty signatures estimate 1.0: see [`is_empty`](Self::is_empty).
400 ///
401 /// ```
402 /// use legit_hashes::minhash_v1;
403 ///
404 /// let first = minhash_v1(["a", "b", "c"]);
405 /// let second = minhash_v1(["x", "y", "z"]);
406 /// assert!(first.similarity(&second)? < 0.2);
407 /// # Ok::<(), legit_hashes::Error>(())
408 /// ```
409 ///
410 /// # Errors
411 ///
412 /// Returns [`Error::SignatureMismatch`] when the signatures come from different algorithms or
413 /// versions, such as `minhash-v1` and `minhash-legacy-v1`.
414 pub fn similarity(&self, other: &Self) -> Result<f64> {
415 let matching = self.matching(other)?;
416 Ok(f64::from(matching) / f64::from(self.algorithm.value_count()))
417 }
418
419 /// The signature of the union of the two sets: the smaller value at each position.
420 ///
421 /// It's the signature the features of both sets would give together, so an application can
422 /// build the signature of a group of texts from theirs. The union with an empty signature
423 /// changes nothing.
424 ///
425 /// ```
426 /// use legit_hashes::minhash_v1;
427 ///
428 /// let first = minhash_v1(["a", "b"]);
429 /// let second = minhash_v1(["b", "c"]);
430 /// assert_eq!(first.union(&second)?, minhash_v1(["a", "b", "c"]));
431 /// # Ok::<(), legit_hashes::Error>(())
432 /// ```
433 ///
434 /// # Errors
435 ///
436 /// Returns [`Error::SignatureMismatch`] when the signatures come from different algorithms or
437 /// versions, such as `minhash-v1` and `minhash-legacy-v1`.
438 pub fn union(&self, other: &Self) -> Result<Self> {
439 self.check_same(other)?;
440 let mut values = self.values;
441 for (value, &theirs) in values.iter_mut().zip(&other.values) {
442 *value = (*value).min(theirs);
443 }
444 Ok(Self::from_array(self.algorithm, values))
445 }
446
447 /// Split the values into `bands` equal bands and hash each into a 64-bit key, for finding
448 /// probable near matches in a database (locality-sensitive hashing).
449 ///
450 /// The definition, the same for both MinHash definitions and frozen with them: band `i` of
451 /// `bands` holds the `r = 128 / bands` values from position `i * r`. Its key is SipHash-2-4
452 /// under the key `(0, 0)` of the bytes: `i` as four bytes big-endian, then each of the band's
453 /// values as four bytes big-endian, in order, `4 + 4r` bytes in all, written once to
454 /// `siphasher::sip::SipHasher24::new_with_keys(0, 0)`, then `finish()`. The index makes equal
455 /// values in different bands give different keys, so every key of a signature can share one
456 /// indexed column, or each can have a column of its own.
457 ///
458 /// A key compares only with keys of the same algorithm and the same `bands`: the keys of
459 /// `minhash-v1` and `minhash-legacy-v1` signatures of the same set differ, and nothing in a key
460 /// says which algorithm made it, so keep each algorithm's keys apart. Two sets with
461 /// Jaccard similarity `s` share at least one key at the same position with probability
462 /// `1 - (1 - s^r)^b` for `b` bands of `r` values:
463 ///
464 /// | Bands × values | s = 0.3 | s = 0.5 | s = 0.7 | s = 0.85 |
465 /// |---|---|---|---|---|
466 /// | 16 × 8 | 0.1% | 6.1% | 61.3% | 99.4% |
467 /// | 32 × 4 | 22.9% | 87.3% | > 99.9% | > 99.9% |
468 /// | 64 × 2 | 99.8% | > 99.9% | > 99.9% | > 99.9% |
469 ///
470 /// More bands find more pairs at a lower similarity, and read more candidates. Look the
471 /// candidates up by key, then keep those whose [`similarity`](Self::similarity) is high enough.
472 /// Unlike [`Hash::chunks`](crate::Hash::chunks), which finds every hash within a distance,
473 /// band keys find a match with the probability above, never with certainty. Every empty
474 /// signature has the same keys, so leave [empty](Self::is_empty) ones out of the index.
475 ///
476 /// ```
477 /// use legit_hashes::minhash_v1_shingles;
478 ///
479 /// let first = minhash_v1_shingles("The meeting moved to Thursday at noon.", 5)?;
480 /// let second = minhash_v1_shingles("The meeting moved to thursday at noon!", 5)?;
481 /// let shared = first.band_keys(32)?.iter().zip(second.band_keys(32)?).filter(|(a, b)| **a == *b).count();
482 /// assert!(shared > 0);
483 /// # Ok::<(), legit_hashes::Error>(())
484 /// ```
485 ///
486 /// # Errors
487 ///
488 /// Returns [`Error::BandCount`] unless `bands` divides the value count: 1, 2, 4, 8, 16, 32, 64
489 /// or 128 for a MinHash signature.
490 pub fn band_keys(&self, bands: u32) -> Result<Vec<u64>> {
491 let count = self.algorithm.value_count();
492 if !count.is_multiple_of(bands) {
493 return Err(Error::BandCount { bands, values: count });
494 }
495 let width = (count / bands) as usize;
496 let keys = self
497 .values
498 .chunks_exact(width)
499 .zip(0_u32..)
500 .map(|(band, index)| {
501 let mut bytes = Vec::with_capacity(4 + 4 * width);
502 bytes.extend_from_slice(&index.to_be_bytes());
503 for value in band {
504 bytes.extend_from_slice(&value.to_be_bytes());
505 }
506 let mut hasher = SipHasher24::new_with_keys(0, 0);
507 hasher.write(&bytes);
508 hasher.finish()
509 })
510 .collect();
511 Ok(keys)
512 }
513
514 /// The [`band_keys`](Self::band_keys) as signed integers, for a signed 64-bit column such as
515 /// SQL's `BIGINT`: the same bit patterns read as two's complement.
516 ///
517 /// ```
518 /// use legit_hashes::minhash_v1;
519 ///
520 /// let signature = minhash_v1(["a", "b"]);
521 /// let unsigned = signature.band_keys(16)?;
522 /// let signed = signature.band_keys_i64(16)?;
523 /// assert_eq!(signed[0], unsigned[0] as i64);
524 /// # Ok::<(), legit_hashes::Error>(())
525 /// ```
526 ///
527 /// # Errors
528 ///
529 /// Returns [`Error::BandCount`] unless `bands` divides the value count.
530 pub fn band_keys_i64(&self, bands: u32) -> Result<Vec<i64>> {
531 Ok(self
532 .band_keys(bands)?
533 .into_iter()
534 .map(|key| i64::from_be_bytes(key.to_be_bytes()))
535 .collect())
536 }
537
538 fn check_same(&self, other: &Self) -> Result<()> {
539 if self.algorithm == other.algorithm {
540 Ok(())
541 } else {
542 Err(Error::SignatureMismatch {
543 left: self.algorithm,
544 right: other.algorithm,
545 })
546 }
547 }
548}
549
550impl fmt::Display for Signature {
551 /// Write the signature as `<algorithm id>:<hex>`, such as `minhash-v1:` and 1,024 hex digits.
552 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
553 write!(f, "{}:{}", self.algorithm, self.to_hex())
554 }
555}
556
557impl FromStr for Signature {
558 type Err = Error;
559
560 /// Read the `<algorithm id>:<hex>` form [`Display`](fmt::Display) writes.
561 fn from_str(text: &str) -> Result<Self> {
562 let (id, hex) = text.split_once(':').ok_or(Error::MissingSeparator)?;
563 Self::from_hex(SignatureAlgorithm::from_id(id)?, hex)
564 }
565}
566
567#[cfg(feature = "serde")]
568impl serde::Serialize for Signature {
569 /// Serialize as the `<algorithm id>:<hex>` string.
570 fn serialize<S: serde::Serializer>(&self, serializer: S) -> std::result::Result<S::Ok, S::Error> {
571 serializer.collect_str(self)
572 }
573}
574
575#[cfg(feature = "serde")]
576impl<'de> serde::Deserialize<'de> for Signature {
577 /// Deserialize from the `<algorithm id>:<hex>` string.
578 fn deserialize<D: serde::Deserializer<'de>>(deserializer: D) -> std::result::Result<Self, D::Error> {
579 deserializer.deserialize_str(crate::serde_support::FromStrVisitor::new(
580 "a signature written `<algorithm>:<hex>`",
581 ))
582 }
583}