fastmash 0.7.1

Fast command-line statistics on text data, compatible with GNU datamash
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
use crate::numeric_contract::{Raw80, Value80};
use crate::portable_numerics::NumericFailure;
use crate::portable_numerics::arena::{Arena, PrimitiveCell, PrimitiveCells};
use std::cmp::Ordering;

#[derive(Clone, Copy)]
struct Window {
    count: u8,
    latest: i32,
    sticky: bool,
}

impl Arena {
    pub(super) fn subtract_finite(
        &mut self,
        left: Value80,
        right: Value80,
    ) -> Result<Value80, NumericFailure> {
        self.primitive_value_scope(|scratch| subtract(scratch, left, right))
    }

    pub(super) fn multiply_finite(
        &mut self,
        left: Value80,
        right: Value80,
    ) -> Result<Value80, NumericFailure> {
        self.primitive_value_scope(|scratch| multiply(scratch, left, right))
    }

    /// The square root of a positive finite value. It needs no scratch
    /// cells, so it leaves the arena as it is.
    pub(super) fn sqrt_finite(&mut self, value: Value80) -> Result<Value80, NumericFailure> {
        Value80::from_raw(sqrt(value)?).map_err(|_| NumericFailure::Invariant)
    }

    /// [`Arena::sqrt_finite`] by the bit-serial square root it replaced,
    /// the reference its results are checked against.
    #[cfg(test)]
    pub(super) fn bit_serial_sqrt_finite(
        &mut self,
        value: Value80,
    ) -> Result<Value80, NumericFailure> {
        self.primitive_value_scope(|scratch| bit_serial_sqrt(scratch, value))
    }
}

fn finite_parts(value: Value80) -> (bool, u64, i32) {
    let exponent = value.exponent();
    let quantum = if exponent == 0 {
        -16_445
    } else {
        i32::from(exponent) - 16_446
    };
    (value.is_negative(), value.significand(), quantum)
}

fn scaled_cmp(left: u64, left_q: i32, right: u64, right_q: i32) -> Ordering {
    let left_top = left_q + (63 - left.leading_zeros()) as i32;
    let right_top = right_q + (63 - right.leading_zeros()) as i32;
    match left_top.cmp(&right_top) {
        Ordering::Equal => {
            let low = left_q.min(right_q);
            for position in (low..=left_top).rev() {
                let left_bit = operand_bit(left, left_q, position);
                let right_bit = operand_bit(right, right_q, position);
                match left_bit.cmp(&right_bit) {
                    Ordering::Equal => {}
                    order => return order,
                }
            }
            Ordering::Equal
        }
        order => order,
    }
}

fn operand_bit(value: u64, quantum: i32, position: i32) -> u8 {
    let index = position - quantum;
    if (0..64).contains(&index) {
        ((value >> index) & 1) as u8
    } else {
        0
    }
}

fn subtract(
    scratch: &mut PrimitiveCells<'_>,
    left: Value80,
    right: Value80,
) -> Result<Raw80, NumericFailure> {
    let (left_sign, left_magnitude, left_q) = finite_parts(left);
    let (right_sign, right_magnitude, right_q) = finite_parts(right);
    scratch.set(PrimitiveCell::V0, left_magnitude)?;
    scratch.set(PrimitiveCell::V1, right_magnitude)?;

    let right_effective_sign = !right_sign;
    let (add, first_magnitude, first_q, second_magnitude, second_q, sign) =
        if left_sign == right_effective_sign {
            (
                true,
                left_magnitude,
                left_q,
                right_magnitude,
                right_q,
                left_sign,
            )
        } else {
            match scaled_cmp(left_magnitude, left_q, right_magnitude, right_q) {
                Ordering::Equal => return Ok(Raw80::new(0, 0)),
                Ordering::Greater => (
                    false,
                    left_magnitude,
                    left_q,
                    right_magnitude,
                    right_q,
                    left_sign,
                ),
                Ordering::Less => (
                    false,
                    right_magnitude,
                    right_q,
                    left_magnitude,
                    left_q,
                    right_effective_sign,
                ),
            }
        };

    scratch.set(PrimitiveCell::V2, 0)?;
    scratch.set(PrimitiveCell::V3, 0)?;
    let low = first_q.min(second_q);
    let high = (first_q + 63).max(second_q + 63);
    let mut window = Window {
        count: 0,
        latest: low - 1,
        sticky: false,
    };
    let mut carry_or_borrow = 0_u8;
    let mut position = low;
    while position <= high {
        let first_active = (first_q..=first_q + 63).contains(&position);
        let second_active = (second_q..=second_q + 63).contains(&position);
        if !first_active && !second_active {
            let next = [first_q, second_q]
                .into_iter()
                .filter(|start| *start > position)
                .min()
                .ok_or(NumericFailure::Invariant)?;
            let count = (next - position) as u32;
            if add {
                if carry_or_borrow != 0 {
                    push(scratch, &mut window, 1)?;
                    push_run(scratch, &mut window, 0, count - 1)?;
                    carry_or_borrow = 0;
                } else {
                    push_run(scratch, &mut window, 0, count)?;
                }
            } else if carry_or_borrow != 0 {
                push_run(scratch, &mut window, 1, count)?;
            } else {
                push_run(scratch, &mut window, 0, count)?;
            }
            position = next;
            continue;
        }
        let first_bit = operand_bit(first_magnitude, first_q, position);
        let second_bit = operand_bit(second_magnitude, second_q, position);
        let output = if add {
            let sum = first_bit + second_bit + carry_or_borrow;
            carry_or_borrow = sum >> 1;
            sum & 1
        } else {
            let subtrahend = second_bit + carry_or_borrow;
            if first_bit >= subtrahend {
                carry_or_borrow = 0;
                first_bit - subtrahend
            } else {
                carry_or_borrow = 1;
                first_bit + 2 - subtrahend
            }
        };
        push(scratch, &mut window, output)?;
        position += 1;
    }
    if add && carry_or_borrow != 0 {
        push(scratch, &mut window, 1)?;
    } else if !add && carry_or_borrow != 0 {
        return Err(NumericFailure::Invariant);
    }
    let raw = round_window(scratch, window, sign)?;
    scratch.set(PrimitiveCell::V4, raw.significand())?;
    Ok(raw)
}

fn push(
    scratch: &mut PrimitiveCells<'_>,
    window: &mut Window,
    bit: u8,
) -> Result<(), NumericFailure> {
    if bit > 1 {
        return Err(NumericFailure::Invariant);
    }
    if window.count < 66 {
        set_window_bit(scratch, window.count, bit != 0)?;
        window.count += 1;
    } else {
        let low = scratch.get(PrimitiveCell::V2)?;
        let high = scratch.get(PrimitiveCell::V3)?;
        window.sticky |= low & 1 != 0;
        scratch.set(PrimitiveCell::V2, (low >> 1) | (high << 63))?;
        scratch.set(PrimitiveCell::V3, (high >> 1) | (u64::from(bit) << 1))?;
    }
    window.latest += 1;
    Ok(())
}

fn push_run(
    scratch: &mut PrimitiveCells<'_>,
    window: &mut Window,
    bit: u8,
    count: u32,
) -> Result<(), NumericFailure> {
    if count > 66 {
        window.sticky |= scratch.get(PrimitiveCell::V2)? != 0
            || scratch.get(PrimitiveCell::V3)? != 0
            || bit != 0;
        scratch.set(PrimitiveCell::V2, if bit == 0 { 0 } else { u64::MAX })?;
        scratch.set(PrimitiveCell::V3, if bit == 0 { 0 } else { 3 })?;
        window.count = 66;
        window.latest = window
            .latest
            .checked_add(count as i32)
            .ok_or(NumericFailure::Invariant)?;
        return Ok(());
    }
    for _ in 0..count {
        push(scratch, window, bit)?;
    }
    Ok(())
}

fn set_window_bit(
    scratch: &mut PrimitiveCells<'_>,
    index: u8,
    value: bool,
) -> Result<(), NumericFailure> {
    let (cell, shift) = if index < 64 {
        (PrimitiveCell::V2, index)
    } else if index < 66 {
        (PrimitiveCell::V3, index - 64)
    } else {
        return Err(NumericFailure::Invariant);
    };
    let current = scratch.get(cell)?;
    let mask = 1_u64 << shift;
    scratch.set(
        cell,
        if value {
            current | mask
        } else {
            current & !mask
        },
    )
}

fn window_bit(
    scratch: &PrimitiveCells<'_>,
    window: Window,
    position: i32,
) -> Result<bool, NumericFailure> {
    if window.count == 0 {
        return Ok(false);
    }
    let first = window.latest - i32::from(window.count) + 1;
    let index = position - first;
    if !(0..i32::from(window.count)).contains(&index) {
        return Ok(false);
    }
    let index = index as u8;
    if index < 64 {
        Ok(scratch.get(PrimitiveCell::V2)? >> index & 1 != 0)
    } else {
        Ok(scratch.get(PrimitiveCell::V3)? >> (index - 64) & 1 != 0)
    }
}

fn window_any_below(
    scratch: &PrimitiveCells<'_>,
    window: Window,
    cut: i32,
) -> Result<bool, NumericFailure> {
    if window.sticky {
        let first = window.latest - i32::from(window.count) + 1;
        if first <= cut {
            return Ok(true);
        }
        return Err(NumericFailure::Invariant);
    }
    let first = window.latest - i32::from(window.count) + 1;
    let end = cut.min(window.latest + 1);
    for position in first..end {
        if window_bit(scratch, window, position)? {
            return Ok(true);
        }
    }
    Ok(false)
}

fn round_window(
    scratch: &PrimitiveCells<'_>,
    window: Window,
    sign: bool,
) -> Result<Raw80, NumericFailure> {
    let mut top = None;
    for index in (0..window.count).rev() {
        let position = window.latest - i32::from(window.count - 1 - index);
        if window_bit(scratch, window, position)? {
            top = Some(position);
            break;
        }
    }
    let top = top.ok_or(NumericFailure::Invariant)?;
    round_bits(
        sign,
        top,
        |position| window_bit(scratch, window, position),
        |cut| window_any_below(scratch, window, cut),
    )
}

fn multiply(
    scratch: &mut PrimitiveCells<'_>,
    left: Value80,
    right: Value80,
) -> Result<Raw80, NumericFailure> {
    let (left_sign, left_magnitude, left_q) = finite_parts(left);
    let (right_sign, right_magnitude, right_q) = finite_parts(right);
    scratch.set(PrimitiveCell::V0, left_magnitude)?;
    scratch.set(PrimitiveCell::V1, right_magnitude)?;
    let product = u128::from(left_magnitude) * u128::from(right_magnitude);
    scratch.set(PrimitiveCell::V2, product as u64)?;
    scratch.set(PrimitiveCell::V3, (product >> 64) as u64)?;
    let quantum = left_q
        .checked_add(right_q)
        .ok_or(NumericFailure::Invariant)?;
    let high = scratch.get(PrimitiveCell::V3)?;
    let top_index = if high == 0 {
        (63 - scratch.get(PrimitiveCell::V2)?.leading_zeros()) as i32
    } else {
        64 + (63 - high.leading_zeros()) as i32
    };
    let raw = round_bits(
        left_sign ^ right_sign,
        quantum + top_index,
        |position| product_bit(scratch, position - quantum),
        |cut| product_any_below(scratch, cut - quantum),
    )?;
    scratch.set(PrimitiveCell::V4, raw.significand())?;
    Ok(raw)
}

fn product_bit(scratch: &PrimitiveCells<'_>, index: i32) -> Result<bool, NumericFailure> {
    if !(0..128).contains(&index) {
        return Ok(false);
    }
    if index < 64 {
        Ok(scratch.get(PrimitiveCell::V2)? >> index & 1 != 0)
    } else {
        Ok(scratch.get(PrimitiveCell::V3)? >> (index - 64) & 1 != 0)
    }
}

fn product_any_below(scratch: &PrimitiveCells<'_>, cut: i32) -> Result<bool, NumericFailure> {
    for index in 0..cut.clamp(0, 128) {
        if product_bit(scratch, index)? {
            return Ok(true);
        }
    }
    Ok(false)
}

fn round_bits(
    sign: bool,
    top: i32,
    mut bit: impl FnMut(i32) -> Result<bool, NumericFailure>,
    mut any_below: impl FnMut(i32) -> Result<bool, NumericFailure>,
) -> Result<Raw80, NumericFailure> {
    let mut quantum = (top - 63).max(-16_445);
    let mut retained = 0_u64;
    for index in 0..64 {
        if bit(quantum + index)? {
            retained |= 1_u64 << index;
        }
    }
    let guard = bit(quantum - 1)?;
    let sticky = any_below(quantum - 1)?;
    if guard && (sticky || retained & 1 != 0) {
        if retained == u64::MAX {
            retained = 1_u64 << 63;
            quantum = quantum.checked_add(1).ok_or(NumericFailure::Invariant)?;
        } else {
            retained += 1;
        }
    }
    if retained == 0 {
        return Ok(Raw80::new(if sign { 0x8000 } else { 0 }, 0));
    }
    if quantum == -16_445 && retained < 1_u64 << 63 {
        return Ok(Raw80::new(if sign { 0x8000 } else { 0 }, retained));
    }
    let exponent = quantum
        .checked_add(16_446)
        .ok_or(NumericFailure::Invariant)?;
    if exponent >= 0x7fff {
        return Ok(Raw80::new(if sign { 0xffff } else { 0x7fff }, 1_u64 << 63));
    }
    if !(1..0x7fff).contains(&exponent) || retained >> 63 == 0 {
        return Err(NumericFailure::Invariant);
    }
    Ok(Raw80::new(
        exponent as u16 | if sign { 0x8000 } else { 0 },
        retained,
    ))
}

/// The square root of a positive finite `value`, rounded to nearest. The
/// value is a radicand in [2^126, 2^128) times an even power of two, so the
/// radicand's integer square root holds the 64 significand bits. A square
/// root is never a tie: the root rounds up exactly when the remainder exceeds
/// it, since `(r + 1/2)^2 = r^2 + r + 1/4` is never an integer.
fn sqrt(value: Value80) -> Result<Raw80, NumericFailure> {
    let (_, magnitude, quantum) = finite_parts(value);
    let leading = magnitude.leading_zeros();
    let normalized = magnitude
        .checked_shl(leading)
        .ok_or(NumericFailure::Invariant)?;
    let normalized_q = quantum - leading as i32;
    let (radicand, mut result_quantum) = if normalized_q & 1 == 0 {
        (u128::from(normalized) << 64, normalized_q / 2 - 32)
    } else {
        (u128::from(normalized) << 63, (normalized_q - 1) / 2 - 31)
    };
    let root = radicand.isqrt();
    let remainder = radicand - root * root;
    let mut kept = u64::try_from(root).map_err(|_| NumericFailure::Invariant)?;
    if remainder > root {
        if kept == u64::MAX {
            kept = 1_u64 << 63;
            result_quantum += 1;
        } else {
            kept += 1;
        }
    }
    let exponent = result_quantum + 16_446;
    if !(1..0x7fff).contains(&exponent) || kept >> 63 == 0 {
        return Err(NumericFailure::Invariant);
    }
    Ok(Raw80::new(exponent as u16, kept))
}

#[cfg(test)]
fn bit_serial_sqrt(
    scratch: &mut PrimitiveCells<'_>,
    value: Value80,
) -> Result<Raw80, NumericFailure> {
    let (_, magnitude, quantum) = finite_parts(value);
    let leading = magnitude.leading_zeros();
    let normalized = magnitude
        .checked_shl(leading)
        .ok_or(NumericFailure::Invariant)?;
    let normalized_q = quantum - leading as i32;
    scratch.set(PrimitiveCell::V0, normalized)?;
    scratch.set(PrimitiveCell::V1, 0)?;
    let scale = if normalized_q & 1 == 0 {
        scratch.set(PrimitiveCell::V2, normalized << 2)?;
        scratch.set(PrimitiveCell::V3, normalized >> 62)?;
        normalized_q / 2 - 33
    } else {
        scratch.set(PrimitiveCell::V2, normalized << 1)?;
        scratch.set(PrimitiveCell::V3, normalized >> 63)?;
        (normalized_q - 1) / 2 - 32
    };
    for cell in [
        PrimitiveCell::V4,
        PrimitiveCell::V5,
        PrimitiveCell::V6,
        PrimitiveCell::V7,
    ] {
        scratch.set(cell, 0)?;
    }
    for pair_index in (0..65).rev() {
        shift_pair_left(scratch, PrimitiveCell::V6, PrimitiveCell::V7, 2)?;
        let pair = (radicand_bit(scratch, pair_index * 2 + 1)? as u64) << 1
            | radicand_bit(scratch, pair_index * 2)? as u64;
        scratch.set(PrimitiveCell::V6, scratch.get(PrimitiveCell::V6)? | pair)?;
        let take = compare_trial(scratch)? != Ordering::Less;
        if take {
            subtract_trial(scratch)?;
        }
        shift_pair_left(scratch, PrimitiveCell::V4, PrimitiveCell::V5, 1)?;
        if take {
            scratch.set(PrimitiveCell::V4, scratch.get(PrimitiveCell::V4)? | 1)?;
        }
    }
    let root_low = scratch.get(PrimitiveCell::V4)?;
    let root_high = scratch.get(PrimitiveCell::V5)?;
    let guard = root_low & 1 != 0;
    let remainder_nonzero =
        scratch.get(PrimitiveCell::V6)? != 0 || scratch.get(PrimitiveCell::V7)? != 0;
    let mut kept = (root_low >> 1) | (root_high << 63);
    let mut result_quantum = scale + 1;
    if guard && (remainder_nonzero || kept & 1 != 0) {
        if kept == u64::MAX {
            kept = 1_u64 << 63;
            result_quantum += 1;
        } else {
            kept += 1;
        }
    }
    let exponent = result_quantum + 16_446;
    if !(1..0x7fff).contains(&exponent) || kept >> 63 == 0 {
        return Err(NumericFailure::Invariant);
    }
    Ok(Raw80::new(exponent as u16, kept))
}

#[cfg(test)]
fn trial_limb(scratch: &PrimitiveCells<'_>, index: u8) -> Result<u64, NumericFailure> {
    let root_low = scratch.get(PrimitiveCell::V4)?;
    match index {
        0 => Ok((root_low << 2) | 1),
        1 => Ok((scratch.get(PrimitiveCell::V5)? << 2) | (root_low >> 62)),
        _ => Err(NumericFailure::Invariant),
    }
}

#[cfg(test)]
fn compare_trial(scratch: &PrimitiveCells<'_>) -> Result<Ordering, NumericFailure> {
    for (index, remainder_cell) in [(1, PrimitiveCell::V7), (0, PrimitiveCell::V6)] {
        match scratch
            .get(remainder_cell)?
            .cmp(&trial_limb(scratch, index)?)
        {
            Ordering::Equal => {}
            order => return Ok(order),
        }
    }
    Ok(Ordering::Equal)
}

#[cfg(test)]
fn subtract_trial(scratch: &mut PrimitiveCells<'_>) -> Result<(), NumericFailure> {
    let mut borrow = false;
    for (index, remainder_cell) in [(0, PrimitiveCell::V6), (1, PrimitiveCell::V7)] {
        let (difference, limb_borrow) = scratch
            .get(remainder_cell)?
            .overflowing_sub(trial_limb(scratch, index)?);
        let (difference, carry_borrow) = difference.overflowing_sub(u64::from(borrow));
        scratch.set(remainder_cell, difference)?;
        borrow = limb_borrow || carry_borrow;
    }
    if borrow {
        return Err(NumericFailure::Invariant);
    }
    Ok(())
}

#[cfg(test)]
fn shift_pair_left(
    scratch: &mut PrimitiveCells<'_>,
    low_cell: PrimitiveCell,
    high_cell: PrimitiveCell,
    count: u32,
) -> Result<(), NumericFailure> {
    let low = scratch.get(low_cell)?;
    let high = scratch.get(high_cell)?;
    if count == 0 || count >= 64 || high >> (64 - count) != 0 {
        return Err(NumericFailure::Invariant);
    }
    scratch.set(low_cell, low << count)?;
    scratch.set(high_cell, (high << count) | (low >> (64 - count)))
}

#[cfg(test)]
fn radicand_bit(scratch: &PrimitiveCells<'_>, index: i32) -> Result<bool, NumericFailure> {
    if !(0..192).contains(&index) {
        return Ok(false);
    }
    let (cell, shift) = if index < 64 {
        (PrimitiveCell::V1, index)
    } else if index < 128 {
        (PrimitiveCell::V2, index - 64)
    } else {
        (PrimitiveCell::V3, index - 128)
    };
    Ok(scratch.get(cell)? >> shift & 1 != 0)
}

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

    /// The integer square root gives the bit-serial root's result for every
    /// kind of positive finite value: subnormals, every exponent of either
    /// parity, exact squares, the significand extremes and a million random
    /// values.
    #[test]
    fn integer_square_root_matches_the_bit_serial_root() {
        let mut arena = Arena::new().unwrap();
        let mut checked = 0u32;
        let mut check = |exponent: u16, significand: u64| {
            let significand = if exponent == 0 {
                significand >> 1
            } else {
                significand | 1 << 63
            };
            if significand == 0 {
                return;
            }
            let value = Value80::from_raw(Raw80::new(exponent, significand)).unwrap();
            let fast = arena.sqrt_finite(value).unwrap();
            let reference = arena.bit_serial_sqrt_finite(value).unwrap();
            assert!(
                fast.same_bits(reference),
                "{exponent:04x} {significand:016x}"
            );
            checked += 1;
        };
        let edges = [0, 1, 2, 3, u64::MAX, u64::MAX - 1, 1 << 62, (1 << 62) + 1];
        for exponent in 0..0x7fff {
            for significand in edges {
                check(exponent, significand);
            }
        }
        // Exact squares: j^2 at even quanta, 2i^2 at odd ones.
        let mut state = 0x9e37_79b9_7f4a_7c15_u64;
        let mut random = || {
            state ^= state << 13;
            state ^= state >> 7;
            state ^= state << 17;
            state
        };
        for _ in 0..20_000 {
            let j = 3_037_000_500 + random() % (u64::from(u32::MAX) - 3_037_000_500);
            let i = (1 << 31) + random() % 889_516_852;
            for exponent in [0x3ffe, 0x3fff, 0x0001, 0x0002, 0x7ffd, 0x7ffe] {
                check(exponent, j * j);
                check(exponent, 2 * i * i);
                check(exponent, j * j - 1);
                check(exponent, j * j + 1);
            }
        }
        for _ in 0..1_000_000 {
            let exponent = (random() % 0x7fff) as u16;
            check(exponent, random());
        }
        assert!(checked > 1_400_000, "{checked}");
    }
}