legit-hashes 0.2.1

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
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
//! `pdq-v1`, Meta's PDQ.

use std::ops::{Add, AddAssign, Div, Mul, Sub, SubAssign};

use crate::strict_f32::StrictF32;
use crate::{Algorithm, Hash, Luma, Rgba};

/// The side of the reduced image the DCT reads.
const REDUCED: usize = 64;

/// The side of the block of frequencies that is kept.
const KEPT: usize = 16;

/// The smallest width or height the reference hashes; a smaller image hashes to all zeros.
const MIN_SIDE: u32 = 5;

/// The luma weights, `0.299`, `0.587` and `0.114` as the nearest `f32`, as the reference's
/// `const float` coefficients hold them, as bit patterns.
const LUMA_RED: u32 = 0x3e99_1687;
const LUMA_GREEN: u32 = 0x3f16_45a2;
const LUMA_BLUE: u32 = 0x3de9_78d5;

/// IEEE-754 single precision: what `pdq-v1` computes with.
///
/// Rust guarantees `f32` arithmetic is IEEE-754, each operation rounded to nearest, ties to even,
/// with no extra precision kept between operations, on x86-64 and aarch64 (RFC 3514), so `pdq-v1`
/// uses `f32` there. Elsewhere it uses [`StrictF32`], the same operations in integer arithmetic,
/// because some targets fall short: 32-bit x86 without SSE2 computes on the x87 unit, which keeps
/// extra precision. The two give the same bits, which the tests check on every hash they compute.
trait Float:
    Copy
    + PartialOrd
    + Add<Output = Self>
    + Sub<Output = Self>
    + Mul<Output = Self>
    + Div<Output = Self>
    + AddAssign
    + SubAssign
{
    /// Positive zero.
    const ZERO: Self;

    /// The value whose bit pattern is `bits`.
    fn from_bits(bits: u32) -> Self;

    /// A small integer, exactly.
    fn from_u16(value: u16) -> Self;

    /// The value truncated toward zero, for one whose integer part fits an `i32`.
    fn truncate(self) -> i32;
}

impl Float for f32 {
    const ZERO: Self = 0.0;

    fn from_bits(bits: u32) -> Self {
        Self::from_bits(bits)
    }

    fn from_u16(value: u16) -> Self {
        Self::from(value)
    }

    fn truncate(self) -> i32 {
        self as i32
    }
}

impl Float for StrictF32 {
    const ZERO: Self = Self::ZERO;

    fn from_bits(bits: u32) -> Self {
        Self::new(f32::from_bits(bits))
    }

    fn from_u16(value: u16) -> Self {
        Self::from_u16(value)
    }

    fn truncate(self) -> i32 {
        self.truncate()
    }
}

/// The arithmetic `pdq-v1` uses on this target.
#[cfg(any(target_arch = "x86_64", target_arch = "aarch64"))]
type Target = f32;

/// The arithmetic `pdq-v1` uses on this target.
#[cfg(not(any(target_arch = "x86_64", target_arch = "aarch64")))]
type Target = StrictF32;

/// A `pdq-v1` hash and the quality score the reference computes with it.
///
/// The quality isn't part of the hash and isn't stored with it: it says how much the hash can be
/// trusted. It counts the strong gradients of the 64×64 reduction, from 0 for a flat image to 100
/// for a detailed one. Meta suggests discarding hashes of quality 49 or less, whose bits are
/// mostly decided by noise, and starting to match at a distance of 31 bits or less; measure both
/// on your own images.
///
/// ```
/// use legit_hashes::{Rgba, pdq_v1};
///
/// let pixels: Vec<u8> = (0..64 * 64 * 4).map(|i| (i * 7 % 251) as u8).collect();
/// let pdq = pdq_v1(Rgba::new(64, 64, &pixels)?);
/// assert!(pdq.quality > 49);
/// println!("{}", pdq.hash); // "pdq-v1:…"
/// # Ok::<(), legit_hashes::Error>(())
/// ```
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
#[non_exhaustive]
pub struct Pdq {
    /// The 256-bit hash.
    pub hash: Hash,
    /// The quality score, from 0 to 100.
    pub quality: u8,
}

/// Hash an image with `pdq-v1`, Meta's PDQ, and score its quality.
///
/// The definition, frozen, is Meta's C++ reference: `pdq/cpp` in
/// [ThreatExchange](https://github.com/facebook/ThreatExchange) at commit
/// `4af74a5ef94ff58b5744379a017b1f44be18bd3a`, the code the PyPI package `pdqhash` 0.2.9 wraps.
/// Given the same RGB pixels, this function gives the bits and the quality that reference gives,
/// built with GCC for x86-64 Linux with its default flags. Every step is the reference's `f32`
/// arithmetic, operation by operation, in its order:
///
/// 1. Luma: each pixel is `0.299 · R + 0.587 · G + 0.114 · B`, the weights rounded to `f32`, the
///    two products summed first. Alpha is ignored.
/// 2. If the image is narrower or shorter than 5 pixels, the hash is all zeros and the quality 0.
/// 3. Unless the image is 64×64, blur it with two passes of a Jarosz box filter, each a pass along
///    every row then along every column. The window is `(n + 127) / 128` pixels for a side of `n`
///    pixels, in integer division. Each window is a running sum, divided by the number of pixels
///    in it, with shorter windows at the ends; [`pdq/cpp/downscaling`] spells it out. Then take
///    the 64×64 pixels at rows `(2i + 1) · height / 128` and columns `(2j + 1) · width / 128`.
/// 4. The quality: for each pair of vertical, then horizontal, neighbours `u` and `v` of the
///    64×64 image, `d = (u - v) · 100 / 255` truncated to an integer; the sum of `|d|`, divided by
///    90 in integer division, at most 100.
/// 5. The DCT: `B = D · A · Dᵀ`, where `A` is the 64×64 image and `D` the reference's 16×64
///    matrix, `D[i][j] = sqrt(2 / 64) · cos(π / 128 · (i + 1) · (2j + 1))` as it holds it in
///    `f32`. `D · A` first, then that times `Dᵀ`, each sum from 0 in order of the inner index.
/// 6. The median of the 256 coefficients by Torben Mogensen's method, as the reference implements
///    it: one of the coefficients, or the midpoint it lands on when some equal it.
/// 7. Bit `16i + j` is set when `B[i][j]` is above the median.
///
/// Bit `k` is the bit worth `2^k` in a 256-bit big-endian number, as Meta prints it, so
/// [`Hash::to_hex`] gives the reference's hex and the first byte holds bits 255 to 248. The bits
/// of the last row of frequencies come first, and [`Hash::chunks`] reads them in that order. This
/// is the opposite of the v1 image hashes, whose first bit is their first coefficient.
///
/// The matrix `D` is a table of `f32` bit patterns, written by `tools/hash-ref/pdq_table.py` in the
/// repository, and nothing calls a platform maths function. Every operation is IEEE-754 single
/// precision, rounded to nearest with ties to even: Rust's `f32` on x86-64 and aarch64, where the
/// language guarantees exactly that and never fuses or reorders operations, and an integer
/// implementation of the same four operations on every other target, such as 32-bit x86 without
/// SSE2, whose x87 unit keeps extra precision. So every platform computes the same hash. The
/// tests check that the two arithmetics agree, and that the integer one alone reproduces the
/// reference vectors. The reference itself isn't so stable: built where the compiler fuses `a · b + c` into one instruction, as GCC does for
/// aarch64 and for x86-64 with FMA enabled, it rounds the luma and the DCT differently, and gives
/// different bits on some images. The crate follows the x86-64 build without FMA.
///
/// The reference reads a greyscale file's values directly as luma; hash those with
/// [`pdq_v1_luma`]. Through step 1 a grey pixel `(v, v, v)` lands a rounding step away from `v`
/// for 35 of the 256 levels.
///
/// Hashing needs two `f32` copies of the image, 8 bytes a pixel.
///
/// ```
/// use legit_hashes::{Algorithm, RgbaBuf, pdq_v1};
///
/// let rgb: Vec<u8> = (0..120 * 90 * 3).map(|i| (i * 13 % 256) as u8).collect();
/// let pdq = pdq_v1(RgbaBuf::from_rgb8(120, 90, &rgb)?.view());
/// assert_eq!(pdq.hash.algorithm(), Algorithm::PdqV1);
/// assert_eq!(pdq.hash.to_hex().len(), 64);
///
/// // Too small to hash...
/// let tiny = pdq_v1(RgbaBuf::from_rgb8(4, 4, &[9; 48])?.view());
/// assert_eq!(tiny.hash.to_hex(), "0".repeat(64));
/// assert_eq!(tiny.quality, 0);
/// # Ok::<(), legit_hashes::Error>(())
/// ```
///
/// [`pdq/cpp/downscaling`]: https://github.com/facebook/ThreatExchange/blob/4af74a5ef94ff58b5744379a017b1f44be18bd3a/pdq/cpp/downscaling/downscaling.cpp
#[must_use]
pub fn pdq_v1(image: Rgba<'_>) -> Pdq {
    hash_rgba::<Target>(image)
}

/// [`pdq_v1`] in the arithmetic `F`.
fn hash_rgba<F: Float>(image: Rgba<'_>) -> Pdq {
    if image.width() < MIN_SIDE || image.height() < MIN_SIDE {
        return empty();
    }
    let weights = (
        F::from_bits(LUMA_RED),
        F::from_bits(LUMA_GREEN),
        F::from_bits(LUMA_BLUE),
    );
    let (pixels, _) = image.pixels().as_chunks::<4>();
    let luma = pixels
        .iter()
        .map(|&[red, green, blue, _]| weights.0 * level(red) + weights.1 * level(green) + weights.2 * level(blue))
        .collect();
    hash_from_luma::<F>(luma, image.width(), image.height())
}

/// Hash a greyscale image with `pdq-v1`, taking each grey level as the luma.
///
/// The same definition as [`pdq_v1`] from step 2, with step 1 replaced by the reference's
/// greyscale path, `fillFloatLumaFromGrey`: the luma of a pixel is its level, exactly. The
/// reference's own file hasher takes this path for a single-channel file.
/// [`Algorithm::hash_luma`] hashes with it too.
///
/// ```
/// use legit_hashes::{Luma, pdq_v1_luma};
///
/// let grey: Vec<u8> = (0..100 * 80).map(|i| (i * 31 % 256) as u8).collect();
/// let pdq = pdq_v1_luma(Luma::new(100, 80, &grey)?);
/// assert_eq!(pdq.quality, 100);
/// # Ok::<(), legit_hashes::Error>(())
/// ```
#[must_use]
pub fn pdq_v1_luma(image: Luma<'_>) -> Pdq {
    hash_levels::<Target>(image)
}

/// [`pdq_v1_luma`] in the arithmetic `F`.
fn hash_levels<F: Float>(image: Luma<'_>) -> Pdq {
    if image.width() < MIN_SIDE || image.height() < MIN_SIDE {
        return empty();
    }
    let luma = image.pixels().iter().map(|&value| level(value)).collect();
    hash_from_luma::<F>(luma, image.width(), image.height())
}

/// An 8-bit level as a float, exactly.
fn level<F: Float>(value: u8) -> F {
    F::from_u16(u16::from(value))
}

/// The hash of an image too small to hash: all zeros, quality 0.
fn empty() -> Pdq {
    Pdq {
        hash: Hash::from_wide(Algorithm::PdqV1, [0; 32]),
        quality: 0,
    }
}

/// Steps 3 to 7, from the luma of an image at least 5 pixels a side.
fn hash_from_luma<F: Float>(mut luma: Vec<F>, width: u32, height: u32) -> Pdq {
    let reduced = reduce(&mut luma, width as usize, height as usize);
    let quality = quality(&reduced);
    let coefficients = dct(&reduced);
    let flat = coefficients.as_flattened();
    let median = torben(flat);
    let mut bytes = [0; 32];
    for (k, &coefficient) in flat.iter().enumerate() {
        if coefficient > median {
            bytes[31 - k / 8] |= 1 << (k % 8);
        }
    }
    Pdq {
        hash: Hash::from_wide(Algorithm::PdqV1, bytes),
        quality,
    }
}

/// Step 3: blur and decimate to 64×64, or copy a 64×64 image as it is. Blurs `luma` in place.
fn reduce<F: Float>(luma: &mut [F], width: usize, height: usize) -> [[F; REDUCED]; REDUCED] {
    let mut reduced = [[F::ZERO; REDUCED]; REDUCED];
    if (width, height) == (REDUCED, REDUCED) {
        for (row, source) in reduced.iter_mut().zip(luma.as_chunks::<REDUCED>().0) {
            row.copy_from_slice(source);
        }
        return reduced;
    }
    let along_rows = window(width);
    let along_columns = window(height);
    let mut scratch = vec![F::ZERO; luma.len()];
    for _ in 0..2 {
        for (source, target) in luma.chunks_exact(width).zip(scratch.chunks_exact_mut(width)) {
            box_filter(source, target, width, 1, along_rows);
        }
        for column in 0..width {
            box_filter(&scratch[column..], &mut luma[column..], height, width, along_columns);
        }
    }
    for (i, row) in reduced.iter_mut().enumerate() {
        let source_row = (2 * i + 1) * height / (2 * REDUCED);
        for (j, value) in row.iter_mut().enumerate() {
            *value = luma[source_row * width + (2 * j + 1) * width / (2 * REDUCED)];
        }
    }
    reduced
}

/// The Jarosz window for a side of `side` pixels: half of `side / 64`, rounded up.
const fn window(side: usize) -> usize {
    side.div_ceil(2 * REDUCED)
}

/// One pass of the box filter along `length` values `stride` apart, as the reference's
/// `box1DFloat`: a running sum over a window of `full` values centred on each output, shorter at
/// the ends, divided by the number of values in it.
fn box_filter<F: Float>(input: &[F], output: &mut [F], length: usize, stride: usize, full: usize) {
    let half = (full + 2) / 2;
    let (mut left, mut right, mut out) = (0, 0, 0);
    let mut sum = F::ZERO;
    // The window is at most 512 values, from a side of at most 65,535...
    let mut count = 0_u16;
    for _ in 0..half - 1 {
        sum += input[right];
        count += 1;
        right += stride;
    }
    for _ in 0..full - half + 1 {
        sum += input[right];
        count += 1;
        output[out] = sum / F::from_u16(count);
        right += stride;
        out += stride;
    }
    for _ in 0..length - full {
        sum += input[right];
        sum -= input[left];
        output[out] = sum / F::from_u16(count);
        left += stride;
        right += stride;
        out += stride;
    }
    for _ in 0..half - 1 {
        sum -= input[left];
        count -= 1;
        output[out] = sum / F::from_u16(count);
        left += stride;
        out += stride;
    }
}

/// Step 4: the quality score of the 64×64 image.
fn quality<F: Float>(image: &[[F; REDUCED]; REDUCED]) -> u8 {
    let (hundred, scale) = (F::from_u16(100), F::from_u16(255));
    // Each step is at most 100, and there are 8,064 of them, so the sum fits an `i32`...
    let step = |u: F, v: F| (((u - v) * hundred) / scale).truncate();
    let mut sum = 0_i32;
    for (row, next) in image.iter().zip(&image[1..]) {
        for (&u, &v) in row.iter().zip(next) {
            sum += step(u, v).abs();
        }
    }
    for row in image {
        for pair in row.windows(2) {
            sum += step(pair[0], pair[1]).abs();
        }
    }
    // ...and the score is at most 100, so it fits a `u8`.
    (sum / 90).min(100) as u8
}

/// Step 5: the 16×16 lowest frequencies past the DC term, `D · A · Dᵀ`, in the reference's order.
fn dct<F: Float>(image: &[[F; REDUCED]; REDUCED]) -> [[F; KEPT]; KEPT] {
    let matrix: [[F; REDUCED]; KEPT] =
        std::array::from_fn(|i| std::array::from_fn(|k| F::from_bits(DCT[i * REDUCED + k])));
    let mut partial = [[F::ZERO; REDUCED]; KEPT];
    for (i, row) in partial.iter_mut().enumerate() {
        for (j, value) in row.iter_mut().enumerate() {
            let mut sum = F::ZERO;
            for (k, image_row) in image.iter().enumerate() {
                sum += matrix[i][k] * image_row[j];
            }
            *value = sum;
        }
    }
    let mut coefficients = [[F::ZERO; KEPT]; KEPT];
    for (row, partial_row) in coefficients.iter_mut().zip(&partial) {
        for (value, matrix_row) in row.iter_mut().zip(&matrix) {
            let mut sum = F::ZERO;
            for (&t, &d) in partial_row.iter().zip(matrix_row) {
                sum += t * d;
            }
            *value = sum;
        }
    }
    coefficients
}

/// Step 6: Torben Mogensen's median, exactly as the reference's `torben.cpp` computes it.
fn torben<F: Float>(values: &[F]) -> F {
    let half = values.len().div_ceil(2);
    let (mut min, mut max) = (values[0], values[0]);
    for &value in &values[1..] {
        if value < min {
            min = value;
        }
        if value > max {
            max = value;
        }
    }
    loop {
        let guess = (min + max) / F::from_u16(2);
        let (mut less, mut greater, mut equal) = (0, 0, 0);
        let (mut max_below, mut min_above) = (min, max);
        for &value in values {
            if value < guess {
                less += 1;
                if value > max_below {
                    max_below = value;
                }
            } else if value > guess {
                greater += 1;
                if value < min_above {
                    min_above = value;
                }
            } else {
                equal += 1;
            }
        }
        if less <= half && greater <= half {
            return if less >= half {
                max_below
            } else if less + equal >= half {
                guess
            } else {
                min_above
            };
        } else if less > greater {
            max = max_below;
        } else {
            min = min_above;
        }
    }
}

/// `D[i][j] = sqrt(2 / 64) · cos(π / 128 · (i + 1) · (2j + 1))` as the reference holds it in
/// `f32`, row by row, as bit patterns.
///
/// Written by `tools/hash-ref/pdq_table.py` in the repository, which follows the reference's
/// double-precision computation step by step with a cosine in 60-digit decimal arithmetic, and
/// checks that no entry depends on the last bit of a platform's cosine. The capture script checks
/// it against the matrix the compiled reference holds. Frozen with `pdq-v1`.
#[rustfmt::skip]
const DCT: [u32; 1024] = [
    0x3e34f6fe, 0x3e348763, 0x3e33a872, 0x3e325ab4, 0x3e309ef6, 0x3e2e764c, 0x3e2be20a, 0x3e28e3c6,
    0x3e257d59, 0x3e21b0dd, 0x3e1d80a8, 0x3e18ef51, 0x3e13ffa8, 0x3e0eb4b9, 0x3e0911c7, 0x3e031a4c,
    0x3df9a3ed, 0x3dec794d, 0x3ddebcd5, 0x3dd076ff, 0x3dc1b098, 0x3db272bd, 0x3da2c6d5, 0x3d92b689,
    0x3d824bc1, 0x3d63213d, 0x3d411ee4, 0x3d1ea570, 0x3cf7944a, 0x3cb14504, 0x3c5510d4, 0x3b8e2871,
    0xbb8e2871, 0xbc5510d4, 0xbcb14504, 0xbcf7944a, 0xbd1ea570, 0xbd411ee4, 0xbd63213d, 0xbd824bc1,
    0xbd92b689, 0xbda2c6d5, 0xbdb272bd, 0xbdc1b098, 0xbdd076ff, 0xbddebcd5, 0xbdec794d, 0xbdf9a3ed,
    0xbe031a4c, 0xbe0911c7, 0xbe0eb4b9, 0xbe13ffa8, 0xbe18ef51, 0xbe1d80a8, 0xbe21b0dd, 0xbe257d59,
    0xbe28e3c6, 0xbe2be20a, 0xbe2e764c, 0xbe309ef6, 0xbe325ab4, 0xbe33a872, 0xbe348763, 0xbe34f6fe,
    0x3e34cd21, 0x3e330f61, 0x3e2f982b, 0x3e2a700c, 0x3e23a3b9, 0x3e1b43f5, 0x3e116566, 0x3e062061,
    0x3df3215c, 0x3dd7aa8b, 0x3dba2005, 0x3d9aca9e, 0x3d73ef2f, 0x3d2fefbb, 0x3cd47d09, 0x3c0e1d7b,
    0xbc0e1d7b, 0xbcd47d09, 0xbd2fefbb, 0xbd73ef2f, 0xbd9aca9e, 0xbdba2005, 0xbdd7aa8b, 0xbdf3215c,
    0xbe062061, 0xbe116566, 0xbe1b43f5, 0xbe23a3b9, 0xbe2a700c, 0xbe2f982b, 0xbe330f61, 0xbe34cd21,
    0xbe34cd21, 0xbe330f61, 0xbe2f982b, 0xbe2a700c, 0xbe23a3b9, 0xbe1b43f5, 0xbe116566, 0xbe062061,
    0xbdf3215c, 0xbdd7aa8b, 0xbdba2005, 0xbd9aca9e, 0xbd73ef2f, 0xbd2fefbb, 0xbcd47d09, 0xbc0e1d7b,
    0x3c0e1d7b, 0x3cd47d09, 0x3d2fefbb, 0x3d73ef2f, 0x3d9aca9e, 0x3dba2005, 0x3dd7aa8b, 0x3df3215c,
    0x3e062061, 0x3e116566, 0x3e1b43f5, 0x3e23a3b9, 0x3e2a700c, 0x3e2f982b, 0x3e330f61, 0x3e34cd21,
    0x3e348763, 0x3e309ef6, 0x3e28e3c6, 0x3e1d80a8, 0x3e0eb4b9, 0x3df9a3ed, 0x3dd076ff, 0x3da2c6d5,
    0x3d63213d, 0x3cf7944a, 0x3b8e2871, 0xbcb14504, 0xbd411ee4, 0xbd92b689, 0xbdc1b098, 0xbdec794d,
    0xbe0911c7, 0xbe18ef51, 0xbe257d59, 0xbe2e764c, 0xbe33a872, 0xbe34f6fe, 0xbe325ab4, 0xbe2be20a,
    0xbe21b0dd, 0xbe13ffa8, 0xbe031a4c, 0xbddebcd5, 0xbdb272bd, 0xbd824bc1, 0xbd1ea570, 0xbc5510d4,
    0x3c5510d4, 0x3d1ea570, 0x3d824bc1, 0x3db272bd, 0x3ddebcd5, 0x3e031a4c, 0x3e13ffa8, 0x3e21b0dd,
    0x3e2be20a, 0x3e325ab4, 0x3e34f6fe, 0x3e33a872, 0x3e2e764c, 0x3e257d59, 0x3e18ef51, 0x3e0911c7,
    0x3dec794d, 0x3dc1b098, 0x3d92b689, 0x3d411ee4, 0x3cb14504, 0xbb8e2871, 0xbcf7944a, 0xbd63213d,
    0xbda2c6d5, 0xbdd076ff, 0xbdf9a3ed, 0xbe0eb4b9, 0xbe1d80a8, 0xbe28e3c6, 0xbe309ef6, 0xbe348763,
    0x3e3425ce, 0x3e2d3986, 0x3e1fa512, 0x3e0bee0a, 0x3de5acc6, 0x3daaa9f2, 0x3d523045, 0x3c8df1a9,
    0xbc8df1a9, 0xbd523045, 0xbdaaa9f2, 0xbde5acc6, 0xbe0bee0a, 0xbe1fa512, 0xbe2d3986, 0xbe3425ce,
    0xbe3425ce, 0xbe2d3986, 0xbe1fa512, 0xbe0bee0a, 0xbde5acc6, 0xbdaaa9f2, 0xbd523045, 0xbc8df1a9,
    0x3c8df1a9, 0x3d523045, 0x3daaa9f2, 0x3de5acc6, 0x3e0bee0a, 0x3e1fa512, 0x3e2d3986, 0x3e3425ce,
    0x3e3425ce, 0x3e2d3986, 0x3e1fa512, 0x3e0bee0a, 0x3de5acc6, 0x3daaa9f2, 0x3d523045, 0x3c8df1a9,
    0xbc8df1a9, 0xbd523045, 0xbdaaa9f2, 0xbde5acc6, 0xbe0bee0a, 0xbe1fa512, 0xbe2d3986, 0xbe3425ce,
    0xbe3425ce, 0xbe2d3986, 0xbe1fa512, 0xbe0bee0a, 0xbde5acc6, 0xbdaaa9f2, 0xbd523045, 0xbc8df1a9,
    0x3c8df1a9, 0x3d523045, 0x3daaa9f2, 0x3de5acc6, 0x3e0bee0a, 0x3e1fa512, 0x3e2d3986, 0x3e3425ce,
    0x3e33a872, 0x3e28e3c6, 0x3e13ffa8, 0x3dec794d, 0x3da2c6d5, 0x3d1ea570, 0xbb8e2871, 0xbd411ee4,
    0xbdb272bd, 0xbdf9a3ed, 0xbe18ef51, 0xbe2be20a, 0xbe348763, 0xbe325ab4, 0xbe257d59, 0xbe0eb4b9,
    0xbddebcd5, 0xbd92b689, 0xbcf7944a, 0x3c5510d4, 0x3d63213d, 0x3dc1b098, 0x3e031a4c, 0x3e1d80a8,
    0x3e2e764c, 0x3e34f6fe, 0x3e309ef6, 0x3e21b0dd, 0x3e0911c7, 0x3dd076ff, 0x3d824bc1, 0x3cb14504,
    0xbcb14504, 0xbd824bc1, 0xbdd076ff, 0xbe0911c7, 0xbe21b0dd, 0xbe309ef6, 0xbe34f6fe, 0xbe2e764c,
    0xbe1d80a8, 0xbe031a4c, 0xbdc1b098, 0xbd63213d, 0xbc5510d4, 0x3cf7944a, 0x3d92b689, 0x3ddebcd5,
    0x3e0eb4b9, 0x3e257d59, 0x3e325ab4, 0x3e348763, 0x3e2be20a, 0x3e18ef51, 0x3df9a3ed, 0x3db272bd,
    0x3d411ee4, 0x3b8e2871, 0xbd1ea570, 0xbda2c6d5, 0xbdec794d, 0xbe13ffa8, 0xbe28e3c6, 0xbe33a872,
    0x3e330f61, 0x3e23a3b9, 0x3e062061, 0x3dba2005, 0x3d2fefbb, 0xbc0e1d7b, 0xbd73ef2f, 0xbdd7aa8b,
    0xbe116566, 0xbe2a700c, 0xbe34cd21, 0xbe2f982b, 0xbe1b43f5, 0xbdf3215c, 0xbd9aca9e, 0xbcd47d09,
    0x3cd47d09, 0x3d9aca9e, 0x3df3215c, 0x3e1b43f5, 0x3e2f982b, 0x3e34cd21, 0x3e2a700c, 0x3e116566,
    0x3dd7aa8b, 0x3d73ef2f, 0x3c0e1d7b, 0xbd2fefbb, 0xbdba2005, 0xbe062061, 0xbe23a3b9, 0xbe330f61,
    0xbe330f61, 0xbe23a3b9, 0xbe062061, 0xbdba2005, 0xbd2fefbb, 0x3c0e1d7b, 0x3d73ef2f, 0x3dd7aa8b,
    0x3e116566, 0x3e2a700c, 0x3e34cd21, 0x3e2f982b, 0x3e1b43f5, 0x3df3215c, 0x3d9aca9e, 0x3cd47d09,
    0xbcd47d09, 0xbd9aca9e, 0xbdf3215c, 0xbe1b43f5, 0xbe2f982b, 0xbe34cd21, 0xbe2a700c, 0xbe116566,
    0xbdd7aa8b, 0xbd73ef2f, 0xbc0e1d7b, 0x3d2fefbb, 0x3dba2005, 0x3e062061, 0x3e23a3b9, 0x3e330f61,
    0x3e325ab4, 0x3e1d80a8, 0x3dec794d, 0x3d824bc1, 0x3b8e2871, 0xbd63213d, 0xbddebcd5, 0xbe18ef51,
    0xbe309ef6, 0xbe33a872, 0xbe21b0dd, 0xbdf9a3ed, 0xbd92b689, 0xbc5510d4, 0x3d411ee4, 0x3dd076ff,
    0x3e13ffa8, 0x3e2e764c, 0x3e348763, 0x3e257d59, 0x3e031a4c, 0x3da2c6d5, 0x3cb14504, 0xbd1ea570,
    0xbdc1b098, 0xbe0eb4b9, 0xbe2be20a, 0xbe34f6fe, 0xbe28e3c6, 0xbe0911c7, 0xbdb272bd, 0xbcf7944a,
    0x3cf7944a, 0x3db272bd, 0x3e0911c7, 0x3e28e3c6, 0x3e34f6fe, 0x3e2be20a, 0x3e0eb4b9, 0x3dc1b098,
    0x3d1ea570, 0xbcb14504, 0xbda2c6d5, 0xbe031a4c, 0xbe257d59, 0xbe348763, 0xbe2e764c, 0xbe13ffa8,
    0xbdd076ff, 0xbd411ee4, 0x3c5510d4, 0x3d92b689, 0x3df9a3ed, 0x3e21b0dd, 0x3e33a872, 0x3e309ef6,
    0x3e18ef51, 0x3ddebcd5, 0x3d63213d, 0xbb8e2871, 0xbd824bc1, 0xbdec794d, 0xbe1d80a8, 0xbe325ab4,
    0x3e318a85, 0x3e168317, 0x3dc9234e, 0x3d0d42af, 0xbd0d42af, 0xbdc9234e, 0xbe168317, 0xbe318a85,
    0xbe318a85, 0xbe168317, 0xbdc9234e, 0xbd0d42af, 0x3d0d42af, 0x3dc9234e, 0x3e168317, 0x3e318a85,
    0x3e318a85, 0x3e168317, 0x3dc9234e, 0x3d0d42af, 0xbd0d42af, 0xbdc9234e, 0xbe168317, 0xbe318a85,
    0xbe318a85, 0xbe168317, 0xbdc9234e, 0xbd0d42af, 0x3d0d42af, 0x3dc9234e, 0x3e168317, 0x3e318a85,
    0x3e318a85, 0x3e168317, 0x3dc9234e, 0x3d0d42af, 0xbd0d42af, 0xbdc9234e, 0xbe168317, 0xbe318a85,
    0xbe318a85, 0xbe168317, 0xbdc9234e, 0xbd0d42af, 0x3d0d42af, 0x3dc9234e, 0x3e168317, 0x3e318a85,
    0x3e318a85, 0x3e168317, 0x3dc9234e, 0x3d0d42af, 0xbd0d42af, 0xbdc9234e, 0xbe168317, 0xbe318a85,
    0xbe318a85, 0xbe168317, 0xbdc9234e, 0xbd0d42af, 0x3d0d42af, 0x3dc9234e, 0x3e168317, 0x3e318a85,
    0x3e309ef6, 0x3e0eb4b9, 0x3da2c6d5, 0x3b8e2871, 0xbd92b689, 0xbe0911c7, 0xbe2e764c, 0xbe325ab4,
    0xbe13ffa8, 0xbdb272bd, 0xbc5510d4, 0x3d824bc1, 0x3e031a4c, 0x3e2be20a, 0x3e33a872, 0x3e18ef51,
    0x3dc1b098, 0x3cb14504, 0xbd63213d, 0xbdf9a3ed, 0xbe28e3c6, 0xbe348763, 0xbe1d80a8, 0xbdd076ff,
    0xbcf7944a, 0x3d411ee4, 0x3dec794d, 0x3e257d59, 0x3e34f6fe, 0x3e21b0dd, 0x3ddebcd5, 0x3d1ea570,
    0xbd1ea570, 0xbddebcd5, 0xbe21b0dd, 0xbe34f6fe, 0xbe257d59, 0xbdec794d, 0xbd411ee4, 0x3cf7944a,
    0x3dd076ff, 0x3e1d80a8, 0x3e348763, 0x3e28e3c6, 0x3df9a3ed, 0x3d63213d, 0xbcb14504, 0xbdc1b098,
    0xbe18ef51, 0xbe33a872, 0xbe2be20a, 0xbe031a4c, 0xbd824bc1, 0x3c5510d4, 0x3db272bd, 0x3e13ffa8,
    0x3e325ab4, 0x3e2e764c, 0x3e0911c7, 0x3d92b689, 0xbb8e2871, 0xbda2c6d5, 0xbe0eb4b9, 0xbe309ef6,
    0x3e2f982b, 0x3e062061, 0x3d73ef2f, 0xbcd47d09, 0xbdd7aa8b, 0xbe23a3b9, 0xbe34cd21, 0xbe1b43f5,
    0xbdba2005, 0xbc0e1d7b, 0x3d9aca9e, 0x3e116566, 0x3e330f61, 0x3e2a700c, 0x3df3215c, 0x3d2fefbb,
    0xbd2fefbb, 0xbdf3215c, 0xbe2a700c, 0xbe330f61, 0xbe116566, 0xbd9aca9e, 0x3c0e1d7b, 0x3dba2005,
    0x3e1b43f5, 0x3e34cd21, 0x3e23a3b9, 0x3dd7aa8b, 0x3cd47d09, 0xbd73ef2f, 0xbe062061, 0xbe2f982b,
    0xbe2f982b, 0xbe062061, 0xbd73ef2f, 0x3cd47d09, 0x3dd7aa8b, 0x3e23a3b9, 0x3e34cd21, 0x3e1b43f5,
    0x3dba2005, 0x3c0e1d7b, 0xbd9aca9e, 0xbe116566, 0xbe330f61, 0xbe2a700c, 0xbdf3215c, 0xbd2fefbb,
    0x3d2fefbb, 0x3df3215c, 0x3e2a700c, 0x3e330f61, 0x3e116566, 0x3d9aca9e, 0xbc0e1d7b, 0xbdba2005,
    0xbe1b43f5, 0xbe34cd21, 0xbe23a3b9, 0xbdd7aa8b, 0xbcd47d09, 0x3d73ef2f, 0x3e062061, 0x3e2f982b,
    0x3e2e764c, 0x3df9a3ed, 0x3d1ea570, 0xbd63213d, 0xbe0911c7, 0xbe325ab4, 0xbe28e3c6, 0xbddebcd5,
    0xbcb14504, 0x3d92b689, 0x3e13ffa8, 0x3e348763, 0x3e21b0dd, 0x3dc1b098, 0x3b8e2871, 0xbdb272bd,
    0xbe1d80a8, 0xbe34f6fe, 0xbe18ef51, 0xbda2c6d5, 0x3c5510d4, 0x3dd076ff, 0x3e257d59, 0x3e33a872,
    0x3e0eb4b9, 0x3d824bc1, 0xbcf7944a, 0xbdec794d, 0xbe2be20a, 0xbe309ef6, 0xbe031a4c, 0xbd411ee4,
    0x3d411ee4, 0x3e031a4c, 0x3e309ef6, 0x3e2be20a, 0x3dec794d, 0x3cf7944a, 0xbd824bc1, 0xbe0eb4b9,
    0xbe33a872, 0xbe257d59, 0xbdd076ff, 0xbc5510d4, 0x3da2c6d5, 0x3e18ef51, 0x3e34f6fe, 0x3e1d80a8,
    0x3db272bd, 0xbb8e2871, 0xbdc1b098, 0xbe21b0dd, 0xbe348763, 0xbe13ffa8, 0xbd92b689, 0x3cb14504,
    0x3ddebcd5, 0x3e28e3c6, 0x3e325ab4, 0x3e0911c7, 0x3d63213d, 0xbd1ea570, 0xbdf9a3ed, 0xbe2e764c,
    0x3e2d3986, 0x3de5acc6, 0x3c8df1a9, 0xbdaaa9f2, 0xbe1fa512, 0xbe3425ce, 0xbe0bee0a, 0xbd523045,
    0x3d523045, 0x3e0bee0a, 0x3e3425ce, 0x3e1fa512, 0x3daaa9f2, 0xbc8df1a9, 0xbde5acc6, 0xbe2d3986,
    0xbe2d3986, 0xbde5acc6, 0xbc8df1a9, 0x3daaa9f2, 0x3e1fa512, 0x3e3425ce, 0x3e0bee0a, 0x3d523045,
    0xbd523045, 0xbe0bee0a, 0xbe3425ce, 0xbe1fa512, 0xbdaaa9f2, 0x3c8df1a9, 0x3de5acc6, 0x3e2d3986,
    0x3e2d3986, 0x3de5acc6, 0x3c8df1a9, 0xbdaaa9f2, 0xbe1fa512, 0xbe3425ce, 0xbe0bee0a, 0xbd523045,
    0x3d523045, 0x3e0bee0a, 0x3e3425ce, 0x3e1fa512, 0x3daaa9f2, 0xbc8df1a9, 0xbde5acc6, 0xbe2d3986,
    0xbe2d3986, 0xbde5acc6, 0xbc8df1a9, 0x3daaa9f2, 0x3e1fa512, 0x3e3425ce, 0x3e0bee0a, 0x3d523045,
    0xbd523045, 0xbe0bee0a, 0xbe3425ce, 0xbe1fa512, 0xbdaaa9f2, 0x3c8df1a9, 0x3de5acc6, 0x3e2d3986,
    0x3e2be20a, 0x3dd076ff, 0xbb8e2871, 0xbddebcd5, 0xbe2e764c, 0xbe28e3c6, 0xbdc1b098, 0x3c5510d4,
    0x3dec794d, 0x3e309ef6, 0x3e257d59, 0x3db272bd, 0xbcb14504, 0xbdf9a3ed, 0xbe325ab4, 0xbe21b0dd,
    0xbda2c6d5, 0x3cf7944a, 0x3e031a4c, 0x3e33a872, 0x3e1d80a8, 0x3d92b689, 0xbd1ea570, 0xbe0911c7,
    0xbe348763, 0xbe18ef51, 0xbd824bc1, 0x3d411ee4, 0x3e0eb4b9, 0x3e34f6fe, 0x3e13ffa8, 0x3d63213d,
    0xbd63213d, 0xbe13ffa8, 0xbe34f6fe, 0xbe0eb4b9, 0xbd411ee4, 0x3d824bc1, 0x3e18ef51, 0x3e348763,
    0x3e0911c7, 0x3d1ea570, 0xbd92b689, 0xbe1d80a8, 0xbe33a872, 0xbe031a4c, 0xbcf7944a, 0x3da2c6d5,
    0x3e21b0dd, 0x3e325ab4, 0x3df9a3ed, 0x3cb14504, 0xbdb272bd, 0xbe257d59, 0xbe309ef6, 0xbdec794d,
    0xbc5510d4, 0x3dc1b098, 0x3e28e3c6, 0x3e2e764c, 0x3ddebcd5, 0x3b8e2871, 0xbdd076ff, 0xbe2be20a,
    0x3e2a700c, 0x3dba2005, 0xbcd47d09, 0xbe062061, 0xbe34cd21, 0xbe116566, 0xbd2fefbb, 0x3d9aca9e,
    0x3e23a3b9, 0x3e2f982b, 0x3dd7aa8b, 0xbc0e1d7b, 0xbdf3215c, 0xbe330f61, 0xbe1b43f5, 0xbd73ef2f,
    0x3d73ef2f, 0x3e1b43f5, 0x3e330f61, 0x3df3215c, 0x3c0e1d7b, 0xbdd7aa8b, 0xbe2f982b, 0xbe23a3b9,
    0xbd9aca9e, 0x3d2fefbb, 0x3e116566, 0x3e34cd21, 0x3e062061, 0x3cd47d09, 0xbdba2005, 0xbe2a700c,
    0xbe2a700c, 0xbdba2005, 0x3cd47d09, 0x3e062061, 0x3e34cd21, 0x3e116566, 0x3d2fefbb, 0xbd9aca9e,
    0xbe23a3b9, 0xbe2f982b, 0xbdd7aa8b, 0x3c0e1d7b, 0x3df3215c, 0x3e330f61, 0x3e1b43f5, 0x3d73ef2f,
    0xbd73ef2f, 0xbe1b43f5, 0xbe330f61, 0xbdf3215c, 0xbc0e1d7b, 0x3dd7aa8b, 0x3e2f982b, 0x3e23a3b9,
    0x3d9aca9e, 0xbd2fefbb, 0xbe116566, 0xbe34cd21, 0xbe062061, 0xbcd47d09, 0x3dba2005, 0x3e2a700c,
    0x3e28e3c6, 0x3da2c6d5, 0xbd411ee4, 0xbe18ef51, 0xbe325ab4, 0xbddebcd5, 0x3c5510d4, 0x3e031a4c,
    0x3e34f6fe, 0x3e0911c7, 0x3cb14504, 0xbdd076ff, 0xbe309ef6, 0xbe1d80a8, 0xbd63213d, 0x3d92b689,
    0x3e257d59, 0x3e2be20a, 0x3db272bd, 0xbd1ea570, 0xbe13ffa8, 0xbe33a872, 0xbdec794d, 0x3b8e2871,
    0x3df9a3ed, 0x3e348763, 0x3e0eb4b9, 0x3cf7944a, 0xbdc1b098, 0xbe2e764c, 0xbe21b0dd, 0xbd824bc1,
    0x3d824bc1, 0x3e21b0dd, 0x3e2e764c, 0x3dc1b098, 0xbcf7944a, 0xbe0eb4b9, 0xbe348763, 0xbdf9a3ed,
    0xbb8e2871, 0x3dec794d, 0x3e33a872, 0x3e13ffa8, 0x3d1ea570, 0xbdb272bd, 0xbe2be20a, 0xbe257d59,
    0xbd92b689, 0x3d63213d, 0x3e1d80a8, 0x3e309ef6, 0x3dd076ff, 0xbcb14504, 0xbe0911c7, 0xbe34f6fe,
    0xbe031a4c, 0xbc5510d4, 0x3ddebcd5, 0x3e325ab4, 0x3e18ef51, 0x3d411ee4, 0xbda2c6d5, 0xbe28e3c6,
    0x3e273d74, 0x3d8a8bd4, 0xbd8a8bd4, 0xbe273d74, 0xbe273d74, 0xbd8a8bd4, 0x3d8a8bd4, 0x3e273d74,
    0x3e273d74, 0x3d8a8bd4, 0xbd8a8bd4, 0xbe273d74, 0xbe273d74, 0xbd8a8bd4, 0x3d8a8bd4, 0x3e273d74,
    0x3e273d74, 0x3d8a8bd4, 0xbd8a8bd4, 0xbe273d74, 0xbe273d74, 0xbd8a8bd4, 0x3d8a8bd4, 0x3e273d74,
    0x3e273d74, 0x3d8a8bd4, 0xbd8a8bd4, 0xbe273d74, 0xbe273d74, 0xbd8a8bd4, 0x3d8a8bd4, 0x3e273d74,
    0x3e273d74, 0x3d8a8bd4, 0xbd8a8bd4, 0xbe273d74, 0xbe273d74, 0xbd8a8bd4, 0x3d8a8bd4, 0x3e273d74,
    0x3e273d74, 0x3d8a8bd4, 0xbd8a8bd4, 0xbe273d74, 0xbe273d74, 0xbd8a8bd4, 0x3d8a8bd4, 0x3e273d74,
    0x3e273d74, 0x3d8a8bd4, 0xbd8a8bd4, 0xbe273d74, 0xbe273d74, 0xbd8a8bd4, 0x3d8a8bd4, 0x3e273d74,
    0x3e273d74, 0x3d8a8bd4, 0xbd8a8bd4, 0xbe273d74, 0xbe273d74, 0xbd8a8bd4, 0x3d8a8bd4, 0x3e273d74,
];

/// The integration tests' generators, to rebuild the reference buffers in the unit tests.
#[cfg(test)]
#[path = "../tests/support/mod.rs"]
#[expect(dead_code, reason = "only the generators and the seeded stream are used here")]
mod test_support;

#[cfg(test)]
mod tests {
    use super::*;

    use super::test_support::Generator;

    /// A seeded stream of `f32` values in `[-500, 500)`, some repeated.
    fn values(seed: u64, count: usize) -> Vec<StrictF32> {
        let mut state = seed;
        (0..count)
            .map(|_| {
                state = state
                    .wrapping_mul(6_364_136_223_846_793_005)
                    .wrapping_add(1_442_695_040_888_963_407);
                StrictF32::new(((state >> 40) % 1000) as f32 - 500.0)
            })
            .collect()
    }

    #[test]
    fn torben_gives_the_128th_smallest_of_256_values() {
        for seed in 0..200 {
            let values = values(seed, 256);
            let mut sorted: Vec<f32> = values.iter().map(|value| value.get()).collect();
            sorted.sort_by(f32::total_cmp);
            assert_eq!(torben(&values).get(), sorted[127], "seed {seed}");
        }
        assert_eq!(torben(&[StrictF32::new(3.0); 256]).get(), 3.0);
    }

    #[test]
    fn the_matrix_holds_the_cosines_it_stands_for() {
        for (index, &bits) in DCT.iter().enumerate() {
            let (i, j) = (index / REDUCED, index % REDUCED);
            let angle = std::f64::consts::PI / 128.0 * (i + 1) as f64 * (2 * j + 1) as f64;
            let expected = (2.0_f64 / 64.0).sqrt() * angle.cos();
            assert!((f64::from(f32::from_bits(bits)) - expected).abs() < 1e-7, "D[{i}][{j}]");
        }
    }

    #[test]
    fn the_strict_arithmetic_matches_meta_s_reference_bit_for_bit() {
        // The reference vectors through `StrictF32`, whatever this target uses for `pdq_v1`...
        let reference: serde_json::Value =
            serde_json::from_str(include_str!("../tests/fixtures/pdq-blockhash.json")).expect("the file is JSON");
        let entries = reference["pdq"]["entries"]
            .as_array()
            .expect("the PDQ entries are a list");
        for entry in entries {
            let size = |key: &str| entry[key].as_u64().and_then(|n| u32::try_from(n).ok()).expect("a size");
            let (width, height) = (size("width"), size("height"));
            let rgba = Generator::from_json(&entry["generator"]).rgba(width, height);
            let pdq = if entry["path"] == "grey" {
                let levels: Vec<u8> = rgba.iter().step_by(4).copied().collect();
                hash_levels::<StrictF32>(Luma::new(width, height, &levels).expect("the size fits"))
            } else {
                hash_rgba::<StrictF32>(Rgba::new(width, height, &rgba).expect("the size fits"))
            };
            assert_eq!(
                pdq.hash.to_hex(),
                entry["hash"].as_str().expect("a hash"),
                "{}",
                entry["name"]
            );
            assert_eq!(
                u64::from(pdq.quality),
                entry["quality"].as_u64().expect("a quality"),
                "{}",
                entry["name"]
            );
        }
        assert!(entries.len() >= 40);
    }

    // On a target whose `f32` is IEEE-754, both arithmetics must give the same bits; elsewhere,
    // `f32` is what `pdq-v1` avoids...
    #[cfg(any(target_arch = "x86_64", target_arch = "aarch64"))]
    #[test]
    fn both_arithmetics_give_the_same_hashes() {
        let mut rng = super::test_support::Rng::new(60);
        let sizes = [
            (5, 5),
            (7, 300),
            (64, 64),
            (63, 65),
            (127, 129),
            (200, 150),
            (300, 17),
            (513, 257),
        ];
        for (width, height) in sizes {
            let noise = rng.bytes((width * height * 4) as usize);
            // Flat, mirrored and smooth images leave coefficients at rounding residue, where any
            // difference in rounding would show...
            let flat = Generator::Flat([128, 128, 128, 255]).rgba(width, height);
            let mirrored: Vec<u8> = (0..width * height)
                .flat_map(|i| {
                    let (x, y) = (i % width, i / width);
                    let v = (x.min(width - 1 - x) * 7 + y * 3) as u8;
                    [v, v / 2, 255 - v, 255]
                })
                .collect();
            let gradient = Generator::Gradient.rgba(width, height);
            for rgba in [&noise, &flat, &mirrored, &gradient] {
                let image = Rgba::new(width, height, rgba).expect("the size fits");
                assert_eq!(
                    hash_rgba::<f32>(image),
                    hash_rgba::<StrictF32>(image),
                    "{width}×{height}"
                );
                let levels: Vec<u8> = rgba.iter().step_by(4).copied().collect();
                let grey = Luma::new(width, height, &levels).expect("the size fits");
                assert_eq!(
                    hash_levels::<f32>(grey),
                    hash_levels::<StrictF32>(grey),
                    "{width}×{height}"
                );
            }
        }
    }

    #[test]
    fn the_window_is_half_the_reduction_ratio_rounded_up() {
        assert_eq!(window(5), 1);
        assert_eq!(window(128), 1);
        assert_eq!(window(129), 2);
        assert_eq!(window(1024), 8);
        assert_eq!(window(65_535), 512);
    }

    #[test]
    fn the_box_filter_averages_a_centred_window_shorter_at_the_ends() {
        // A window of 3 over 0, 3, 6, 9, 12: the first output averages 0 and 3, the last 9 and 12...
        let filter = |input: &[f32], length: usize, stride: usize, full: usize| -> Vec<f32> {
            let input: Vec<StrictF32> = input.iter().map(|&value| StrictF32::new(value)).collect();
            let mut output = vec![StrictF32::ZERO; input.len()];
            box_filter(&input, &mut output, length, stride, full);
            output.iter().map(|value| value.get()).collect()
        };
        assert_eq!(filter(&[0.0, 3.0, 6.0, 9.0, 12.0], 5, 1, 3), [1.5, 3.0, 6.0, 9.0, 10.5]);
        // A window of 1 leaves the values, and the stride skips between them...
        let stepped = filter(&[1.0, -1.0, 2.0, -1.0, 4.0, -1.0], 3, 2, 1);
        assert_eq!(stepped, [1.0, 0.0, 2.0, 0.0, 4.0, 0.0]);
    }
}