jixel 0.5.13

JPEG XL encoder
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
/*
 * // Copyright (c) Radzivon Bartoshyk 5/2026. All rights reserved.
 * //
 * // Redistribution and use in source and binary forms, with or without modification,
 * // are permitted provided that the following conditions are met:
 * //
 * // 1.  Redistributions of source code must retain the above copyright notice, this
 * // list of conditions and the following disclaimer.
 * //
 * // 2.  Redistributions in binary form must reproduce the above copyright notice,
 * // this list of conditions and the following disclaimer in the documentation
 * // and/or other materials provided with the distribution.
 * //
 * // 3.  Neither the name of the copyright holder nor the names of its
 * // contributors may be used to endorse or promote products derived from
 * // this software without specific prior written permission.
 * //
 * // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
 * // AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 * // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
 * // DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
 * // FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
 * // DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
 * // SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
 * // CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
 * // OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
 * // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 */
use crate::ColorSpace;
use crate::dct::fmla;
use crate::encode_image::MAX_DIMENSION;
use std::fmt;
use std::ops::{Deref, DerefMut};

/// Euclidean length for bounded inputs, without rescaling to avoid overflow or underflow.
#[cfg(any(feature = "splines", test))]
#[inline]
pub(crate) fn fast_hypot(x: f32, y: f32) -> f32 {
    (x * x + y * y).sqrt()
}

/// Double-precision Euclidean length for bounded inputs.
#[inline]
pub(crate) fn fast_hypot_f64(x: f64, y: f64) -> f64 {
    (x * x + y * y).sqrt()
}

pub(crate) fn try_vec_fill<T: Clone>(value: T, len: usize) -> Result<Vec<T>, EncodeError> {
    let size = len
        .checked_mul(size_of::<T>())
        .ok_or(EncodeError::AllocationFailed { size: usize::MAX })?;
    let mut values = Vec::new();
    values
        .try_reserve_exact(len)
        .map_err(|_| EncodeError::AllocationFailed { size })?;
    // `try_reserve_exact` has already made this resize non-allocating.
    values.resize(len, value);
    Ok(values)
}

macro_rules! try_vec {
    ($value:expr; $len:expr) => {
        $crate::util::try_vec_fill($value, $len)
    };
}

pub(crate) use try_vec;

pub(crate) fn heap_array<T: Clone, const N: usize>(value: T) -> Box<[T; N]> {
    let slice = vec![value; N].into_boxed_slice();
    boxed_slice_to_array(slice)
}

pub(crate) fn heap_array_from_fn<T, const N: usize>(make: impl FnMut(usize) -> T) -> Box<[T; N]> {
    let slice = (0..N).map(make).collect::<Vec<_>>().into_boxed_slice();
    boxed_slice_to_array(slice)
}

fn boxed_slice_to_array<T, const N: usize>(slice: Box<[T]>) -> Box<[T; N]> {
    match slice.try_into() {
        Ok(array) => array,
        Err(_) => unreachable!("boxed slice length is the requested array length"),
    }
}

/// A fixed-size two-dimensional array whose elements are initialized directly
/// in one flat heap allocation.
#[derive(Clone)]
pub(crate) struct HeapMatrix<T, const ROWS: usize, const COLS: usize> {
    data: Box<[T]>,
}

impl<T: Clone, const ROWS: usize, const COLS: usize> HeapMatrix<T, ROWS, COLS> {
    pub(crate) fn new(value: T) -> Self {
        Self {
            data: vec![value; ROWS * COLS].into_boxed_slice(),
        }
    }

    pub(crate) fn from_rows(rows: &[[T; COLS]; ROWS]) -> Self {
        Self {
            data: rows.as_flattened().to_vec().into_boxed_slice(),
        }
    }
}

impl<T, const ROWS: usize, const COLS: usize> Deref for HeapMatrix<T, ROWS, COLS> {
    type Target = [[T; COLS]; ROWS];

    fn deref(&self) -> &Self::Target {
        let (rows, remainder) = self.data.as_chunks::<COLS>();
        debug_assert!(remainder.is_empty());
        rows.try_into()
            .unwrap_or_else(|_| unreachable!("heap matrix has its declared dimensions"))
    }
}

impl<T, const ROWS: usize, const COLS: usize> DerefMut for HeapMatrix<T, ROWS, COLS> {
    fn deref_mut(&mut self) -> &mut Self::Target {
        let (rows, remainder) = self.data.as_chunks_mut::<COLS>();
        debug_assert!(remainder.is_empty());
        rows.try_into()
            .unwrap_or_else(|_| unreachable!("heap matrix has its declared dimensions"))
    }
}

/// Errors that can occur during JXL encoding.
#[derive(Debug, Clone, PartialEq)]
pub enum EncodeError {
    /// Image width or height is zero.
    EmptyImage,
    /// The input buffer length does not match `width * height * channels`.
    InputSizeMismatch {
        expected: usize,
        actual: usize,
    },
    /// The alpha plane length does not match `width * height`.
    AlphaSizeMismatch {
        expected: usize,
        actual: usize,
    },
    /// `distance` must be a positive finite number.
    InvalidDistance(f32),
    /// Quality value was NaN.
    QualityIsNaN,
    /// One or both image dimensions exceed the maximum representable value
    /// (2^30 − 1).
    DimensionTooLarge {
        width: usize,
        height: usize,
    },
    /// An internal image plane or other encoding buffer could not be allocated.
    AllocationFailed {
        size: usize,
    },
    /// An alpha bit depth other than 8, 10, or 12 was supplied.
    UnsupportedAlphaBitDepth(u8),
    /// ICC profile injection is not yet implemented.
    IccProfileNotSupported,
    Unsupported(&'static str),
    BadChannelCount(usize),
    BadBitDepth(u32),
    IccNotSupported,
    SizeOverflow,
    InputLength {
        expected: usize,
        got: usize,
    },
    UnsupportedColorSpace(ColorSpace),
    /// The input JPEG could not be transcoded losslessly.
    Jpeg(String),
    /// A caller-provided Brotli backend could not compress metadata.
    Brotli(String),
    /// The gain map sample buffer length does not match
    /// `width * height * channels`.
    GainMapSizeMismatch {
        expected: usize,
        actual: usize,
    },
    /// ISO 21496-1 gain map metadata is malformed or unrepresentable.
    InvalidGainMapMetadata(&'static str),
    /// The attached gain map could not be encoded or bundled.
    GainMap(&'static str),
}

impl fmt::Display for EncodeError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::EmptyImage => write!(f, "image dimensions must be non-zero"),
            Self::InputSizeMismatch { expected, actual } => write!(
                f,
                "input buffer size mismatch: expected {expected} bytes, got {actual}"
            ),
            Self::AlphaSizeMismatch { expected, actual } => write!(
                f,
                "alpha plane size mismatch: expected {expected} pixels, got {actual}"
            ),
            Self::InvalidDistance(d) => write!(
                f,
                "butteraugli distance must be a positive finite number, got {d}"
            ),
            Self::QualityIsNaN => write!(f, "quality value must not be NaN"),
            Self::DimensionTooLarge { width, height } => write!(
                f,
                "image dimensions {width}×{height} exceed the maximum ({})",
                MAX_DIMENSION
            ),
            Self::AllocationFailed { size } => {
                write!(f, "failed to allocate an encoding buffer of {size} bytes")
            }
            Self::UnsupportedAlphaBitDepth(bits) => {
                write!(
                    f,
                    "unsupported alpha bit depth: {bits} (must be 8, 10, or 12)"
                )
            }
            Self::IccProfileNotSupported => {
                write!(f, "ICC profile injection is not yet supported by jixel")
            }
            Self::Unsupported(msg) => write!(f, "unsupported: {msg}"),
            Self::BadChannelCount(n) => write!(f, "channel count {} not in 1..=4", n),
            Self::BadBitDepth(b) => write!(f, "bits_per_sample {} not in 1..=16", b),
            Self::IccNotSupported => write!(
                f,
                "embedded ICC not yet supported; use an enumerated color space"
            ),
            Self::SizeOverflow => write!(f, "image size overflows usize"),
            Self::InputLength { expected, got } => {
                write!(f, "input length {} != expected {}", got, expected)
            }
            Self::Jpeg(msg) => write!(f, "JPEG transcoding failed: {msg}"),
            Self::Brotli(msg) => write!(f, "Brotli compression failed: {msg}"),
            Self::GainMapSizeMismatch { expected, actual } => write!(
                f,
                "gain map buffer size mismatch: expected {expected} samples, got {actual}"
            ),
            Self::InvalidGainMapMetadata(msg) => {
                write!(f, "invalid gain map metadata: {msg}")
            }
            Self::GainMap(msg) => write!(f, "gain map: {msg}"),
            EncodeError::UnsupportedColorSpace(colorspace) => {
                f.write_fmt(format_args!("unsupported color space: {:?}", colorspace))
            }
        }
    }
}

impl std::error::Error for EncodeError {}

pub(crate) trait FastRound {
    fn fast_round(self) -> Self;
}

impl FastRound for f32 {
    fn fast_round(self) -> Self {
        self.round()
    }
}

/// Ties-away rounding followed by a saturating integer conversion, without
/// a libm roundf call on baseline x86 or WebAssembly.
#[inline]
pub(crate) fn round_i32(value: f32) -> i32 {
    if cfg!(any(
        target_arch = "x86",
        target_arch = "x86_64",
        target_family = "wasm"
    )) {
        round_i32_portable(value)
    } else {
        value.round() as i32
    }
}

#[inline]
fn round_i32_portable(value: f32) -> i32 {
    let magnitude = value.abs();
    // Below 0.5, adding half can round the float up to 1.0. At 2^23
    // and above, floats are already integral and must not be biased.
    let biased = if (0.5..8_388_608.0).contains(&magnitude) {
        value + 0.5f32.copysign(value)
    } else {
        value
    };
    biased as i32
}

/// Approximate `e^x` for `-87 <= x <= 88`, where the binary scaling factor is
/// normal. NaN propagates.
#[inline]
pub(crate) fn fast_exp(x: f32) -> f32 {
    debug_assert!(x.is_nan() || (-87.0..=88.0).contains(&x));
    const LN2_HI: f32 = 0.693_145_75;
    const LN2_LO: f32 = 1.428_606_8e-6;

    let exponent = round_i32(x * std::f32::consts::LOG2_E);
    let r = fmla(exponent as f32, -LN2_HI, x);
    let r = fmla(exponent as f32, -LN2_LO, r);
    let square = r * r;
    // Approximate r * (exp(r) + 1) / (exp(r) - 1), then solve for exp(r).
    let p = fmla(-0.002_775_669, square, 0.166_667_07);
    let p = fmla(p, square, 2.0);
    let scale = f32::from_bits(((exponent + 127) as u32) << 23);
    (1.0 + 2.0 * r / (p - r)) * scale
}

#[cfg(test)]
#[test]
fn fast_exp_approximates_exp_over_its_domain() {
    let check = |x: f32| {
        let expected = (x as f64).exp() as f32;
        let actual = fast_exp(x);
        assert!(actual.to_bits().abs_diff(expected.to_bits()) <= 2, "x={x}");
    };
    for i in -8700..=8800 {
        check(i as f32 / 100.0);
    }
    for exponent in -125..127 {
        let boundary = (exponent as f32 + 0.5) * std::f32::consts::LN_2;
        check(boundary.next_down());
        check(boundary);
        check(boundary.next_up());
    }
    assert_eq!(fast_exp(0.0), 1.0);
    assert_eq!(fast_exp(-0.0), 1.0);
    assert!(fast_exp(f32::NAN).is_nan());
}

#[cfg(not(all(target_arch = "aarch64", feature = "neon")))]
#[inline]
fn f32_to_f16_bits_impl(v: f32) -> u16 {
    let bits = v.to_bits();
    let sign = ((bits >> 16) & 0x8000) as u16;
    let exp = ((bits >> 23) & 0xFF) as i32;
    let mant = bits & 0x7F_FFFF;
    let e16 = exp - 112; // rebias 127 -> 15
    if e16 >= 31 {
        return sign | 0x7BFF; // clamp to max finite; NaN/Inf unsupported on the wire
    }
    if e16 <= 0 {
        if e16 < -10 {
            return sign;
        }
        let m = mant | 0x80_0000;
        let shift = (14 - e16) as u32;
        let rounded = (m + (1 << (shift - 1)) - 1 + ((m >> shift) & 1)) >> shift;
        return sign | rounded as u16;
    }
    let m = mant + 0xFFF + ((mant >> 13) & 1);
    let mut e16 = e16 as u32;
    let mut m16 = m >> 13;
    if m16 == 0x400 {
        m16 = 0;
        e16 += 1;
        if e16 >= 31 {
            return sign | 0x7BFF;
        }
    }
    sign | ((e16 as u16) << 10) | (m16 as u16)
}

#[cfg(any(target_arch = "x86", target_arch = "x86_64"))]
#[target_feature(enable = "f16c")]
fn f32_to_f16_bits_f16c(v: f32) -> u16 {
    #[cfg(target_arch = "x86")]
    use std::arch::x86::{_MM_FROUND_TO_NEAREST_INT, _mm_cvtps_ph, _mm_cvtsi128_si32, _mm_set_ss};
    #[cfg(target_arch = "x86_64")]
    use std::arch::x86_64::{
        _MM_FROUND_TO_NEAREST_INT, _mm_cvtps_ph, _mm_cvtsi128_si32, _mm_set_ss,
    };

    _mm_cvtsi128_si32(_mm_cvtps_ph::<_MM_FROUND_TO_NEAREST_INT>(_mm_set_ss(v))) as u16
}

#[inline]
pub(crate) fn f32_to_f16_bits(v: f32) -> u16 {
    #[cfg(all(target_arch = "aarch64", feature = "neon"))]
    {
        use std::arch::aarch64::{vcvt_f16_f32, vdupq_n_f32, vget_lane_u16, vreinterpret_u16_f16};
        unsafe { vget_lane_u16::<0>(vreinterpret_u16_f16(vcvt_f16_f32(vdupq_n_f32(v)))) }
    }
    #[cfg(any(target_arch = "x86", target_arch = "x86_64"))]
    {
        let converter = F16_CONVERTERS.get_or_init(select_f16_converters);
        unsafe { (converter.f32_to_f16_bits)(v) }
    }
    #[cfg(not(any(
        all(target_arch = "aarch64", feature = "neon"),
        target_arch = "x86",
        target_arch = "x86_64"
    )))]
    {
        f32_to_f16_bits_impl(v)
    }
}

#[cfg(not(all(target_arch = "aarch64", feature = "neon")))]
#[inline]
fn f16_bits_to_f32_impl(b: u16) -> f32 {
    let sign = (b >> 15) as u32;
    let biased_exp = ((b >> 10) & 0x1F) as u32;
    let mantissa = (b & 0x3FF) as u32;
    if biased_exp == 0 {
        let v = (1.0f32 / 16384.0) * (mantissa as f32 * (1.0 / 1024.0));
        return if sign != 0 { -v } else { v };
    }
    f32::from_bits((sign << 31) | ((biased_exp + 112) << 23) | (mantissa << 13))
}

#[cfg(any(target_arch = "x86", target_arch = "x86_64"))]
#[target_feature(enable = "f16c")]
fn f16_bits_to_f32_f16c(b: u16) -> f32 {
    #[cfg(target_arch = "x86")]
    use std::arch::x86::{_mm_cvtph_ps, _mm_cvtsi32_si128, _mm_cvtss_f32};
    #[cfg(target_arch = "x86_64")]
    use std::arch::x86_64::{_mm_cvtph_ps, _mm_cvtsi32_si128, _mm_cvtss_f32};

    _mm_cvtss_f32(_mm_cvtph_ps(_mm_cvtsi32_si128(b as i32)))
}

#[cfg(any(target_arch = "x86", target_arch = "x86_64"))]
#[derive(Clone, Copy)]
struct F16Converters {
    f32_to_f16_bits: unsafe fn(f32) -> u16,
    f16_bits_to_f32: unsafe fn(u16) -> f32,
}

#[cfg(any(target_arch = "x86", target_arch = "x86_64"))]
fn select_f16_converters() -> F16Converters {
    if std::is_x86_feature_detected!("f16c") {
        return F16Converters {
            f32_to_f16_bits: f32_to_f16_bits_f16c,
            f16_bits_to_f32: f16_bits_to_f32_f16c,
        };
    }
    F16Converters {
        f32_to_f16_bits: f32_to_f16_bits_impl,
        f16_bits_to_f32: f16_bits_to_f32_impl,
    }
}

#[cfg(any(target_arch = "x86", target_arch = "x86_64"))]
static F16_CONVERTERS: std::sync::OnceLock<F16Converters> = std::sync::OnceLock::new();

/// Mirror of libjxl `F16Coder::Read`: the value the decoder reconstructs from
/// a binary16 bit pattern.
#[inline]
pub(crate) fn f16_bits_to_f32(b: u16) -> f32 {
    #[cfg(all(target_arch = "aarch64", feature = "neon"))]
    {
        use std::arch::aarch64::{vcvt_f32_f16, vdup_n_u16, vgetq_lane_f32, vreinterpret_f16_u16};
        unsafe { vgetq_lane_f32::<0>(vcvt_f32_f16(vreinterpret_f16_u16(vdup_n_u16(b)))) }
    }
    #[cfg(any(target_arch = "x86", target_arch = "x86_64"))]
    {
        let converter = F16_CONVERTERS.get_or_init(select_f16_converters);
        unsafe { (converter.f16_bits_to_f32)(b) }
    }
    #[cfg(not(any(
        all(target_arch = "aarch64", feature = "neon"),
        target_arch = "x86",
        target_arch = "x86_64"
    )))]
    {
        f16_bits_to_f32_impl(b)
    }
}

/// Stable insertion sort for caller-bounded lists of at most 16 candidates.
/// Keep general sorting machinery out of these small candidate-selection paths.
pub(crate) fn sort_small_by<T>(
    items: &mut [T],
    mut compare: impl FnMut(&T, &T) -> std::cmp::Ordering,
) {
    for i in 1..items.len() {
        let mut j = i;
        while j > 0 && compare(&items[j], &items[j - 1]).is_lt() {
            items.swap(j, j - 1);
            j -= 1;
        }
    }
}

#[cfg(test)]
mod rounding_tests {
    use super::{round_i32, round_i32_portable};

    #[test]
    fn integer_rounding_preserves_half_ties_precision_and_saturation() {
        let check = |value: f32| {
            let expected = value.round() as i32;
            assert_eq!(round_i32_portable(value), expected, "portable: {value:?}");
            assert_eq!(round_i32(value), expected, "dispatched: {value:?}");
        };
        // Every layer coverage/byte boundary, including adjacent floats.
        for i in 0..=256 {
            let half = i as f32 + 0.5;
            for value in [half.next_down(), half, half.next_up()] {
                check(value);
                check(-value);
            }
        }
        for value in [
            0.0f32,
            f32::MIN_POSITIVE,
            8_388_607.5,
            8_388_609.0,
            2_147_483_648.0,
            f32::MAX,
            f32::INFINITY,
            f32::NAN,
        ] {
            for value in [value.next_down(), value, value.next_up()] {
                check(value);
                check(-value);
            }
        }
    }
}

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

    #[test]
    fn try_vec_reports_requested_byte_size() {
        let size = isize::MAX as usize + 1;
        assert_eq!(
            try_vec![0u8; size].unwrap_err(),
            EncodeError::AllocationFailed { size }
        );
    }
}

#[cfg(test)]
mod f16_tests {
    use super::{f16_bits_to_f32, f32_to_f16_bits};

    #[test]
    fn known_hdr_luminances() {
        assert_eq!(f32_to_f16_bits(0.0), 0x0000);
        assert_eq!(f32_to_f16_bits(255.0), 0x5BF8);
        assert_eq!(f32_to_f16_bits(1000.0), 0x63D0);
        assert_eq!(f32_to_f16_bits(4000.0), 0x6BD0);
        assert_eq!(f32_to_f16_bits(10000.0), 0x70E2);
    }

    #[test]
    fn known_binary16_values() {
        assert_eq!(f16_bits_to_f32(0x0000).to_bits(), 0.0f32.to_bits());
        assert_eq!(f16_bits_to_f32(0x8000).to_bits(), (-0.0f32).to_bits());
        assert_eq!(f16_bits_to_f32(0x0001), 2.0f32.powi(-24));
        assert_eq!(f16_bits_to_f32(0x3C00), 1.0);
        assert_eq!(f16_bits_to_f32(0x5BF8), 255.0);
        assert_eq!(f16_bits_to_f32(0xFBFF), -65504.0);
    }
}

#[cfg(test)]
mod small_sort_tests {
    #[test]
    fn small_sort_preserves_stable_order_for_bounded_candidates() {
        let mut state = 0x1234_5678u32;
        for len in 0..=16 {
            for _ in 0..128 {
                let mut input: Vec<_> = (0..len)
                    .map(|ordinal| {
                        state = state.wrapping_mul(1664525).wrapping_add(1013904223);
                        ((state >> 29) as u8, ordinal)
                    })
                    .collect();
                let mut expected = input.clone();
                expected.sort_by_key(|&(key, _)| key);
                super::sort_small_by(&mut input, |a, b| a.0.cmp(&b.0));
                assert_eq!(input, expected);
            }
        }
    }
}