legit-hashes 0.2.0

Versioned similarity hashes of images and text, and MinHash set signatures, with index keys for finding near matches
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
//! Set signatures: their definitions, stored forms, similarity estimate and band keys.

use std::fmt;
use std::hash::Hasher;
use std::str::FromStr;

use siphasher::sip::SipHasher24;

use crate::{Algorithm, Error, Result};

/// The number of values in a signature of each algorithm.
const VALUES: usize = 128;

/// A set-signature algorithm at one version of its definition.
///
/// A signature estimates how much two sets overlap, value by value, where a bit hash
/// ([`Algorithm`]) is compared bit by bit. The two never compare with each other. As with
/// [`Algorithm`], the version is part of the identity and a released definition never changes its
/// output.
///
/// `minhash-v1` and `minhash-legacy-v1` are datasketch's two 32-bit MinHash constructions, its
/// current default and the one it used before 2.0.0. Their signatures have the same shape but
/// different values, so they never compare, merge or parse as each other: choose one per stored
/// column.
///
/// ```
/// use legit_hashes::SignatureAlgorithm;
///
/// let algorithm: SignatureAlgorithm = "minhash-v1".parse()?;
/// assert_eq!(algorithm, SignatureAlgorithm::MinHashV1);
/// assert_eq!(algorithm.value_count(), 128);
/// # Ok::<(), legit_hashes::Error>(())
/// ```
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord)]
#[non_exhaustive]
pub enum SignatureAlgorithm {
    /// `minhash-v1`: Broder's MinHash, 128 values of 32 bits, as the Python library datasketch
    /// computes it by default since 2.0.0, its `affine32` scheme. See
    /// [`minhash_v1`](crate::minhash_v1).
    MinHashV1,
    /// `minhash-legacy-v1`: Broder's MinHash, 128 values of 32 bits, as datasketch computed it by
    /// default before 2.0.0, its `legacy` scheme. See
    /// [`minhash_legacy_v1`](crate::minhash_legacy_v1).
    MinHashLegacyV1,
}

impl SignatureAlgorithm {
    /// Every signature algorithm this version of the crate knows, in the order they were added.
    ///
    /// ```
    /// use legit_hashes::SignatureAlgorithm;
    ///
    /// assert_eq!(
    ///     SignatureAlgorithm::ALL,
    ///     [SignatureAlgorithm::MinHashV1, SignatureAlgorithm::MinHashLegacyV1]
    /// );
    /// ```
    pub const ALL: [Self; 2] = [Self::MinHashV1, Self::MinHashLegacyV1];

    /// The stable text id, such as `minhash-v1`, used in every stored and printed form.
    ///
    /// ```
    /// use legit_hashes::SignatureAlgorithm;
    ///
    /// assert_eq!(SignatureAlgorithm::MinHashV1.id(), "minhash-v1");
    /// ```
    #[must_use]
    pub const fn id(self) -> &'static str {
        match self {
            Self::MinHashV1 => "minhash-v1",
            Self::MinHashLegacyV1 => "minhash-legacy-v1",
        }
    }

    /// The number of 32-bit values in the algorithm's signatures: 128 for both MinHash definitions.
    ///
    /// ```
    /// use legit_hashes::SignatureAlgorithm;
    ///
    /// assert_eq!(SignatureAlgorithm::MinHashV1.value_count(), 128);
    /// ```
    #[must_use]
    pub const fn value_count(self) -> u32 {
        match self {
            Self::MinHashV1 | Self::MinHashLegacyV1 => 128,
        }
    }

    /// Find the signature algorithm with the text id `id`, such as `minhash-v1`. The match is
    /// exact.
    ///
    /// ```
    /// use legit_hashes::{Algorithm, Error, SignatureAlgorithm};
    ///
    /// assert_eq!(SignatureAlgorithm::from_id("minhash-v1")?, SignatureAlgorithm::MinHashV1);
    /// assert_eq!(
    ///     SignatureAlgorithm::from_id("simhash-v1"),
    ///     Err(Error::NotASignature(Algorithm::SimHashV1))
    /// );
    /// # Ok::<(), legit_hashes::Error>(())
    /// ```
    ///
    /// # Errors
    ///
    /// Returns [`Error::NotASignature`] for the id of a bit-hash [`Algorithm`], and
    /// [`Error::UnknownAlgorithm`] when no algorithm has that id.
    pub fn from_id(id: &str) -> Result<Self> {
        if let Some(algorithm) = Self::ALL.into_iter().find(|algorithm| algorithm.id() == id) {
            return Ok(algorithm);
        }
        match Algorithm::ALL.into_iter().find(|algorithm| algorithm.id() == id) {
            Some(algorithm) => Err(Error::NotASignature(algorithm)),
            None => Err(Error::UnknownAlgorithm(id.to_owned())),
        }
    }
}

impl fmt::Display for SignatureAlgorithm {
    /// Write the id, such as `minhash-v1`.
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.write_str(self.id())
    }
}

impl FromStr for SignatureAlgorithm {
    type Err = Error;

    /// Read an id, as [`from_id`](Self::from_id) does.
    fn from_str(id: &str) -> Result<Self> {
        Self::from_id(id)
    }
}

#[cfg(feature = "serde")]
impl serde::Serialize for SignatureAlgorithm {
    /// Serialize as the id.
    fn serialize<S: serde::Serializer>(&self, serializer: S) -> std::result::Result<S::Ok, S::Error> {
        serializer.serialize_str(self.id())
    }
}

#[cfg(feature = "serde")]
impl<'de> serde::Deserialize<'de> for SignatureAlgorithm {
    /// Deserialize from the id.
    fn deserialize<D: serde::Deserializer<'de>>(deserializer: D) -> std::result::Result<Self, D::Error> {
        deserializer.deserialize_str(crate::serde_support::FromStrVisitor::new("a signature algorithm id"))
    }
}

/// A set signature: the algorithm that made it, version included, and its values.
///
/// A MinHash signature is 128 values of 32 bits, held inline. Two signatures estimate the
/// Jaccard similarity of their sets, the size of the intersection over the size of the union, by
/// the share of positions whose values are equal: see [`similarity`](Self::similarity). The
/// Hamming distance of a [`Hash`](struct@crate::Hash) means nothing here, so the two types never
/// compare.
///
/// | Form | Example | Read back with |
/// |---|---|---|
/// | [`Display`](fmt::Display) | `minhash-v1:` and 1,024 hex digits | [`FromStr`] |
/// | [`to_hex`](Self::to_hex) | 1,024 hex digits | [`from_hex`](Self::from_hex) |
/// | [`to_bytes`](Self::to_bytes) | 512 bytes | [`from_bytes`](Self::from_bytes) |
/// | [`values`](Self::values) | 128 `u32` values | [`from_values`](Self::from_values) |
///
/// The bytes are the values in order, each big-endian, four bytes a value, and the hex is the
/// bytes, two lower-case digits a byte, so each run of eight digits reads as a value. datasketch's
/// `digest()` lists the same values in the same order. Only the string form names the algorithm.
/// With the others, store the algorithm id beside the value, or keep one algorithm per column: the
/// values of `minhash-v1` and `minhash-legacy-v1` look alike, so the bytes, hex and values read
/// back as whichever algorithm the caller names.
///
/// ```
/// use legit_hashes::{Signature, minhash_v1};
///
/// let signature = minhash_v1(["stored", "hashes", "outlive", "code"]);
/// let stored = signature.to_string();
/// assert!(stored.starts_with("minhash-v1:"));
/// assert_eq!(stored.parse::<Signature>()?, signature);
/// # Ok::<(), legit_hashes::Error>(())
/// ```
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub struct Signature {
    algorithm: SignatureAlgorithm,
    values: [u32; VALUES],
}

impl Signature {
    /// Make a signature from its values.
    pub(crate) const fn from_array(algorithm: SignatureAlgorithm, values: [u32; VALUES]) -> Self {
        Self { algorithm, values }
    }

    /// The algorithm that made the signature.
    ///
    /// ```
    /// use legit_hashes::{SignatureAlgorithm, minhash_v1};
    ///
    /// assert_eq!(minhash_v1(["a"]).algorithm(), SignatureAlgorithm::MinHashV1);
    /// ```
    #[must_use]
    pub const fn algorithm(&self) -> SignatureAlgorithm {
        self.algorithm
    }

    /// The values, in the order the algorithm defines: for a MinHash signature, one for each of its
    /// 128 permutations, in datasketch's order.
    ///
    /// ```
    /// use legit_hashes::minhash_v1;
    ///
    /// let empty = minhash_v1::<&str>([]);
    /// assert_eq!(empty.values(), [u32::MAX; 128]);
    /// ```
    #[must_use]
    pub fn values(&self) -> &[u32] {
        &self.values
    }

    /// Read a signature of `algorithm` from the values [`values`](Self::values) returned, or from
    /// the values of datasketch's `digest()`: for `minhash-v1` from a `MinHash` of its default
    /// scheme, for `minhash-legacy-v1` from one of `scheme="legacy"` or made before 2.0.0.
    ///
    /// ```
    /// use legit_hashes::{Signature, SignatureAlgorithm, minhash_v1};
    ///
    /// let signature = minhash_v1(["a", "b"]);
    /// let read = Signature::from_values(SignatureAlgorithm::MinHashV1, signature.values())?;
    /// assert_eq!(read, signature);
    /// # Ok::<(), legit_hashes::Error>(())
    /// ```
    ///
    /// # Errors
    ///
    /// Returns [`Error::SignatureLength`] when `values` doesn't hold exactly
    /// `algorithm.value_count()` values.
    pub fn from_values(algorithm: SignatureAlgorithm, values: &[u32]) -> Result<Self> {
        let values = <[u32; VALUES]>::try_from(values).map_err(|_| Error::SignatureLength {
            algorithm,
            expected: VALUES,
            actual: values.len(),
        })?;
        Ok(Self::from_array(algorithm, values))
    }

    /// Whether the signature is that of the empty set: every value at `u32::MAX`, as no feature
    /// was added.
    ///
    /// Two empty signatures are equal, so they estimate a similarity of 1.0, as datasketch's do.
    /// Check this before treating two signatures as near duplicates: two empty texts aren't.
    ///
    /// ```
    /// use legit_hashes::minhash_v1;
    ///
    /// let empty = minhash_v1::<&str>([]);
    /// assert!(empty.is_empty());
    /// assert_eq!(empty.similarity(&minhash_v1::<&str>([]))?, 1.0);
    /// assert!(!minhash_v1([""]).is_empty());
    /// # Ok::<(), legit_hashes::Error>(())
    /// ```
    #[must_use]
    pub fn is_empty(&self) -> bool {
        self.values.iter().all(|&value| value == u32::MAX)
    }

    /// The bytes: each value big-endian, in order, 512 bytes for a MinHash signature.
    ///
    /// ```
    /// use legit_hashes::minhash_v1;
    ///
    /// let signature = minhash_v1(["a"]);
    /// let bytes = signature.to_bytes();
    /// assert_eq!(bytes.len(), 512);
    /// assert_eq!(bytes[..4], signature.values()[0].to_be_bytes());
    /// ```
    #[must_use]
    pub fn to_bytes(&self) -> Vec<u8> {
        self.values.iter().flat_map(|value| value.to_be_bytes()).collect()
    }

    /// Read a signature of `algorithm` from the bytes [`to_bytes`](Self::to_bytes) returned.
    ///
    /// ```
    /// use legit_hashes::{Signature, SignatureAlgorithm, minhash_v1};
    ///
    /// let signature = minhash_v1(["a"]);
    /// assert_eq!(Signature::from_bytes(SignatureAlgorithm::MinHashV1, &signature.to_bytes())?, signature);
    /// # Ok::<(), legit_hashes::Error>(())
    /// ```
    ///
    /// # Errors
    ///
    /// Returns [`Error::SignatureLength`] when `bytes` isn't four bytes for each of the
    /// algorithm's values long.
    pub fn from_bytes(algorithm: SignatureAlgorithm, bytes: &[u8]) -> Result<Self> {
        let (words, rest) = bytes.as_chunks::<4>();
        if words.len() != VALUES || !rest.is_empty() {
            return Err(Error::SignatureLength {
                algorithm,
                expected: VALUES * 4,
                actual: bytes.len(),
            });
        }
        let mut values = [0; VALUES];
        for (value, word) in values.iter_mut().zip(words) {
            *value = u32::from_be_bytes(*word);
        }
        Ok(Self::from_array(algorithm, values))
    }

    /// The bytes as lower-case hex, two digits a byte, in order: 1,024 digits for a MinHash
    /// signature, eight for each value.
    ///
    /// ```
    /// use legit_hashes::minhash_v1;
    ///
    /// let signature = minhash_v1(["a"]);
    /// assert_eq!(signature.to_hex()[..8], format!("{:08x}", signature.values()[0]));
    /// ```
    #[must_use]
    pub fn to_hex(&self) -> String {
        const DIGITS: &[u8; 16] = b"0123456789abcdef";
        let mut hex = String::with_capacity(VALUES * 8);
        for byte in self.to_bytes() {
            hex.push(char::from(DIGITS[usize::from(byte >> 4)]));
            hex.push(char::from(DIGITS[usize::from(byte & 0x0f)]));
        }
        hex
    }

    /// Read a signature of `algorithm` from the hex [`to_hex`](Self::to_hex) returned. Upper-case
    /// digits are accepted too.
    ///
    /// ```
    /// use legit_hashes::{Signature, SignatureAlgorithm, minhash_v1};
    ///
    /// let signature = minhash_v1(["a"]);
    /// let hex = signature.to_hex().to_uppercase();
    /// assert_eq!(Signature::from_hex(SignatureAlgorithm::MinHashV1, &hex)?, signature);
    /// # Ok::<(), legit_hashes::Error>(())
    /// ```
    ///
    /// # Errors
    ///
    /// Returns [`Error::SignatureLength`] when `hex` isn't eight digits for each of the
    /// algorithm's values long, and [`Error::InvalidHex`] when it holds anything but hex digits.
    pub fn from_hex(algorithm: SignatureAlgorithm, hex: &str) -> Result<Self> {
        if hex.len() != VALUES * 8 {
            return Err(Error::SignatureLength {
                algorithm,
                expected: VALUES * 8,
                actual: hex.len(),
            });
        }
        let digits = hex
            .bytes()
            .map(|digit| char::from(digit).to_digit(16).ok_or(Error::InvalidHex))
            .collect::<Result<Vec<u32>>>()?;
        let (groups, _) = digits.as_chunks::<8>();
        let mut values = [0; VALUES];
        for (value, group) in values.iter_mut().zip(groups) {
            *value = group.iter().fold(0, |value, &digit| value << 4 | digit);
        }
        Ok(Self::from_array(algorithm, values))
    }

    /// How many positions hold equal values in the two signatures, from 0 to the algorithm's
    /// [`value_count`](SignatureAlgorithm::value_count): the exact fraction behind
    /// [`similarity`](Self::similarity), `matching / 128` for a MinHash signature.
    ///
    /// ```
    /// use legit_hashes::{minhash_legacy_v1, minhash_v1};
    ///
    /// let first = minhash_v1(["a", "b", "c"]);
    /// assert_eq!(first.matching(&first)?, 128);
    /// // The same set under the other definition doesn't compare...
    /// assert!(first.matching(&minhash_legacy_v1(["a", "b", "c"])).is_err());
    /// # Ok::<(), legit_hashes::Error>(())
    /// ```
    ///
    /// # Errors
    ///
    /// Returns [`Error::SignatureMismatch`] when the signatures come from different algorithms or
    /// versions, such as `minhash-v1` and `minhash-legacy-v1`.
    pub fn matching(&self, other: &Self) -> Result<u32> {
        self.check_same(other)?;
        Ok(self
            .values
            .iter()
            .zip(&other.values)
            .map(|(left, right)| u32::from(left == right))
            .sum())
    }

    /// The estimate of the Jaccard similarity of the two sets, from 0.0 to 1.0: the share of
    /// positions whose values are equal, [`matching`](Self::matching) over the value count.
    ///
    /// Each position agrees with probability equal to the true similarity, so with 128 values the
    /// estimate's standard error is `sqrt(s(1 - s) / 128)`: at most about 0.044, at `s = 0.5`. Two
    /// empty signatures estimate 1.0: see [`is_empty`](Self::is_empty).
    ///
    /// ```
    /// use legit_hashes::minhash_v1;
    ///
    /// let first = minhash_v1(["a", "b", "c"]);
    /// let second = minhash_v1(["x", "y", "z"]);
    /// assert!(first.similarity(&second)? < 0.2);
    /// # Ok::<(), legit_hashes::Error>(())
    /// ```
    ///
    /// # Errors
    ///
    /// Returns [`Error::SignatureMismatch`] when the signatures come from different algorithms or
    /// versions, such as `minhash-v1` and `minhash-legacy-v1`.
    pub fn similarity(&self, other: &Self) -> Result<f64> {
        let matching = self.matching(other)?;
        Ok(f64::from(matching) / f64::from(self.algorithm.value_count()))
    }

    /// The signature of the union of the two sets: the smaller value at each position.
    ///
    /// It's the signature the features of both sets would give together, so an application can
    /// build the signature of a group of texts from theirs. The union with an empty signature
    /// changes nothing.
    ///
    /// ```
    /// use legit_hashes::minhash_v1;
    ///
    /// let first = minhash_v1(["a", "b"]);
    /// let second = minhash_v1(["b", "c"]);
    /// assert_eq!(first.union(&second)?, minhash_v1(["a", "b", "c"]));
    /// # Ok::<(), legit_hashes::Error>(())
    /// ```
    ///
    /// # Errors
    ///
    /// Returns [`Error::SignatureMismatch`] when the signatures come from different algorithms or
    /// versions, such as `minhash-v1` and `minhash-legacy-v1`.
    pub fn union(&self, other: &Self) -> Result<Self> {
        self.check_same(other)?;
        let mut values = self.values;
        for (value, &theirs) in values.iter_mut().zip(&other.values) {
            *value = (*value).min(theirs);
        }
        Ok(Self::from_array(self.algorithm, values))
    }

    /// Split the values into `bands` equal bands and hash each into a 64-bit key, for finding
    /// probable near matches in a database (locality-sensitive hashing).
    ///
    /// The definition, the same for both MinHash definitions and frozen with them: band `i` of
    /// `bands` holds the `r = 128 / bands` values from position `i * r`. Its key is SipHash-2-4
    /// under the key `(0, 0)` of the bytes: `i` as four bytes big-endian, then each of the band's
    /// values as four bytes big-endian, in order, `4 + 4r` bytes in all, written once to
    /// `siphasher::sip::SipHasher24::new_with_keys(0, 0)`, then `finish()`. The index makes equal
    /// values in different bands give different keys, so every key of a signature can share one
    /// indexed column, or each can have a column of its own.
    ///
    /// A key compares only with keys of the same algorithm and the same `bands`: the keys of
    /// `minhash-v1` and `minhash-legacy-v1` signatures of the same set differ, and nothing in a key
    /// says which algorithm made it, so keep each algorithm's keys apart. Two sets with
    /// Jaccard similarity `s` share at least one key at the same position with probability
    /// `1 - (1 - s^r)^b` for `b` bands of `r` values:
    ///
    /// | Bands × values | s = 0.3 | s = 0.5 | s = 0.7 | s = 0.85 |
    /// |---|---|---|---|---|
    /// | 16 × 8 | 0.1% | 6.1% | 61.3% | 99.4% |
    /// | 32 × 4 | 22.9% | 87.3% | > 99.9% | > 99.9% |
    /// | 64 × 2 | 99.8% | > 99.9% | > 99.9% | > 99.9% |
    ///
    /// More bands find more pairs at a lower similarity, and read more candidates. Look the
    /// candidates up by key, then keep those whose [`similarity`](Self::similarity) is high enough.
    /// Unlike [`Hash::chunks`](crate::Hash::chunks), which finds every hash within a distance,
    /// band keys find a match with the probability above, never with certainty. Every empty
    /// signature has the same keys, so leave [empty](Self::is_empty) ones out of the index.
    ///
    /// ```
    /// use legit_hashes::minhash_v1_shingles;
    ///
    /// let first = minhash_v1_shingles("The meeting moved to Thursday at noon.", 5)?;
    /// let second = minhash_v1_shingles("The meeting moved to thursday at noon!", 5)?;
    /// let shared = first.band_keys(32)?.iter().zip(second.band_keys(32)?).filter(|(a, b)| **a == *b).count();
    /// assert!(shared > 0);
    /// # Ok::<(), legit_hashes::Error>(())
    /// ```
    ///
    /// # Errors
    ///
    /// Returns [`Error::BandCount`] unless `bands` divides the value count: 1, 2, 4, 8, 16, 32, 64
    /// or 128 for a MinHash signature.
    pub fn band_keys(&self, bands: u32) -> Result<Vec<u64>> {
        let count = self.algorithm.value_count();
        if !count.is_multiple_of(bands) {
            return Err(Error::BandCount { bands, values: count });
        }
        let width = (count / bands) as usize;
        let keys = self
            .values
            .chunks_exact(width)
            .zip(0_u32..)
            .map(|(band, index)| {
                let mut bytes = Vec::with_capacity(4 + 4 * width);
                bytes.extend_from_slice(&index.to_be_bytes());
                for value in band {
                    bytes.extend_from_slice(&value.to_be_bytes());
                }
                let mut hasher = SipHasher24::new_with_keys(0, 0);
                hasher.write(&bytes);
                hasher.finish()
            })
            .collect();
        Ok(keys)
    }

    /// The [`band_keys`](Self::band_keys) as signed integers, for a signed 64-bit column such as
    /// SQL's `BIGINT`: the same bit patterns read as two's complement.
    ///
    /// ```
    /// use legit_hashes::minhash_v1;
    ///
    /// let signature = minhash_v1(["a", "b"]);
    /// let unsigned = signature.band_keys(16)?;
    /// let signed = signature.band_keys_i64(16)?;
    /// assert_eq!(signed[0], unsigned[0] as i64);
    /// # Ok::<(), legit_hashes::Error>(())
    /// ```
    ///
    /// # Errors
    ///
    /// Returns [`Error::BandCount`] unless `bands` divides the value count.
    pub fn band_keys_i64(&self, bands: u32) -> Result<Vec<i64>> {
        Ok(self
            .band_keys(bands)?
            .into_iter()
            .map(|key| i64::from_be_bytes(key.to_be_bytes()))
            .collect())
    }

    fn check_same(&self, other: &Self) -> Result<()> {
        if self.algorithm == other.algorithm {
            Ok(())
        } else {
            Err(Error::SignatureMismatch {
                left: self.algorithm,
                right: other.algorithm,
            })
        }
    }
}

impl fmt::Display for Signature {
    /// Write the signature as `<algorithm id>:<hex>`, such as `minhash-v1:` and 1,024 hex digits.
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "{}:{}", self.algorithm, self.to_hex())
    }
}

impl FromStr for Signature {
    type Err = Error;

    /// Read the `<algorithm id>:<hex>` form [`Display`](fmt::Display) writes.
    fn from_str(text: &str) -> Result<Self> {
        let (id, hex) = text.split_once(':').ok_or(Error::MissingSeparator)?;
        Self::from_hex(SignatureAlgorithm::from_id(id)?, hex)
    }
}

#[cfg(feature = "serde")]
impl serde::Serialize for Signature {
    /// Serialize as the `<algorithm id>:<hex>` string.
    fn serialize<S: serde::Serializer>(&self, serializer: S) -> std::result::Result<S::Ok, S::Error> {
        serializer.collect_str(self)
    }
}

#[cfg(feature = "serde")]
impl<'de> serde::Deserialize<'de> for Signature {
    /// Deserialize from the `<algorithm id>:<hex>` string.
    fn deserialize<D: serde::Deserializer<'de>>(deserializer: D) -> std::result::Result<Self, D::Error> {
        deserializer.deserialize_str(crate::serde_support::FromStrVisitor::new(
            "a signature written `<algorithm>:<hex>`",
        ))
    }
}