softfpu 0.2.4

32-, 64- and 80-bit floating-point arithmetic in safe Rust, including Intel x87 transcendental functions
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
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
// Module-level rounding model. An independent integer reference rounds the exact
// input on the destination grid and with an unbounded exponent. It checks the
// value, flags, magnitude increment and tininess for masked and unmasked responses.

use proptest::prelude::*;

use crate::test_util::{PRECISIONS, ROUNDINGS, Rng, model_config, pattern};
use crate::x86::{Double, Exceptions, Extended, Precision, Rounded, Rounding, Single};
use crate::x86::{Real, extended};
use crate::{Computed, Tininess, Unrounded};

// Format precision, including the integer bit, minimum and maximum normal
// exponents, and the exponent adjustment of an unmasked range response.
#[derive(Clone, Copy)]
struct Grid {
    precision: i32,
    emin: i32,
    emax: i32,
    adjust: i32,
    // The exception an unmasked range response reports when infinity or
    // zero replaces an adjusted result that is still out of range.
    replacement: Exceptions,
}

const SINGLE: Grid = Grid {
    precision: 24,
    emin: -126,
    emax: 127,
    adjust: 192,
    replacement: Exceptions::NONE,
};
const DOUBLE: Grid = Grid {
    precision: 53,
    emin: -1022,
    emax: 1023,
    adjust: 1536,
    replacement: Exceptions::NONE,
};

// Builds the 80-bit grid at `precision`, preserving the full exponent range.
fn extended_grid(precision: Precision) -> Grid {
    Grid {
        precision: match precision {
            Precision::Single => 24,
            Precision::Double => 53,
            Precision::Extended => 64,
        },
        emin: -16382,
        emax: 16383,
        adjust: 24_576,
        replacement: Exceptions::PE,
    }
}

// Magnitude represented as zero, infinity, or significand * 2^exponent.
// Finite significands are odd, so equal magnitudes have equal representations.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
enum Magnitude {
    Zero,
    Infinity,
    Finite { significand: u128, exponent: i32 },
}

impl Magnitude {
    fn of(significand: u128, exponent: i32) -> Magnitude {
        if significand == 0 {
            return Magnitude::Zero;
        }
        let zeros = significand.trailing_zeros();
        Magnitude::Finite {
            significand: significand >> zeros,
            exponent: exponent + zeros as i32,
        }
    }
}

#[derive(Debug, PartialEq, Eq)]
struct Outcome {
    negative: bool,
    magnitude: Magnitude,
    exceptions: Exceptions,
    rounded_up: bool,
    tiny: bool,
}

// Rounds m / 2^k using `rounding` and sign `negative`.
// Returns the rounded integer, whether any discarded bit was set,
// and whether rounding incremented the retained bits.
fn round_at(m: u128, k: u32, rounding: Rounding, negative: bool) -> (u128, bool, bool) {
    let (kept, rest, above_half, at_half) = match k {
        0 => (m, 0, false, false),
        1..=128 => {
            let rest = if k == 128 { m } else { m & ((1 << k) - 1) };
            let half = 1u128 << (k - 1);
            let kept = if k == 128 { 0 } else { m >> k };
            (kept, rest, rest > half, rest == half)
        }
        _ => (0, m, false, false),
    };
    let increment = match rounding {
        Rounding::Nearest => above_half || (at_half && kept & 1 == 1),
        Rounding::TowardZero => false,
        Rounding::Up => !negative && rest != 0,
        Rounding::Down => negative && rest != 0,
    };
    (kept + u128::from(increment), rest != 0, increment)
}

// Checks whether r * 2^q < 2^limit.
fn below(r: u128, q: i32, limit: i32) -> bool {
    r == 0 || 128 - r.leading_zeros() as i32 + q <= limit
}

// Computes the masked response for the exact value m * 2^s on `grid`.
// Requires nonzero m with at least as many bits as the grid precision.
// Compares the exact or unbounded rounded magnitude with the smallest normal.
// Rounds the output on a grid whose step is the larger of the value's
// precision step and the denormal step.
// On overflow, returns infinity for nearest or away-from-zero rounding,
// or the largest finite value otherwise. Both cases report OE and PE.
// Reports UE only when the result is tiny and inexact.
fn reference(
    negative: bool,
    m: u128,
    s: i32,
    grid: Grid,
    rounding: Rounding,
    tininess: Tininess,
) -> Outcome {
    let Grid {
        precision,
        emin,
        emax,
        ..
    } = grid;
    let length = 128 - m.leading_zeros() as i32;
    let own = s + length - precision;
    let (unbounded, _, _) = round_at(m, (own - s) as u32, rounding, negative);
    let tiny = match tininess {
        Tininess::BeforeRounding => below(m, s, emin),
        Tininess::AfterRounding => below(unbounded, own, emin),
    };
    let step = own.max(emin - precision + 1);
    let (r, inexact, rounded_up) = round_at(m, (step - s) as u32, rounding, negative);
    if !below(r, step, emax + 1) {
        let away = match rounding {
            Rounding::Nearest => true,
            Rounding::TowardZero => false,
            Rounding::Up => !negative,
            Rounding::Down => negative,
        };
        let magnitude = if away {
            Magnitude::Infinity
        } else {
            Magnitude::of((1 << precision) - 1, emax - precision + 1)
        };
        return Outcome {
            negative,
            magnitude,
            exceptions: Exceptions::OE | Exceptions::PE,
            rounded_up: away,
            tiny: false,
        };
    }
    let mut exceptions = Exceptions::NONE;
    if inexact {
        exceptions |= Exceptions::PE;
        if tiny {
            exceptions |= Exceptions::UE;
        }
    }
    Outcome {
        negative,
        magnitude: Magnitude::of(r, step),
        exceptions,
        rounded_up,
        tiny,
    }
}

// Computes the x87 unmasked response for nonzero m * 2^s on `grid`.
// Rounds to the selected precision with an unbounded exponent.
// Values with fewer significand bits than the precision remain exact.
// Marks a rounded value below the smallest normal as tiny.
// For overflow, divides the rounded value by 2^adjust and reports OE.
// For a tiny result, multiplies it by 2^adjust and reports UE.
// If it remains out of range, substitutes infinity or zero and reports the
// grid's replacement exception. Infinity sets rounded_up; zero clears it.
// Inexact rounding also reports PE.
fn reference_unmasked(negative: bool, m: u128, s: i32, grid: Grid, rounding: Rounding) -> Outcome {
    let Grid {
        precision,
        emin,
        emax,
        adjust,
        replacement,
    } = grid;
    let length = 128 - m.leading_zeros() as i32;
    let own = s + (length - precision).max(0);
    let (r, inexact, rounded_up) = round_at(m, (own - s) as u32, rounding, negative);
    let tiny = below(r, own, emin);
    let (q, mut exceptions) = if !below(r, own, emax + 1) {
        (own - adjust, Exceptions::OE)
    } else if tiny {
        (own + adjust, Exceptions::UE)
    } else {
        (own, Exceptions::NONE)
    };
    if inexact {
        exceptions |= Exceptions::PE;
    }
    let (magnitude, rounded_up) = if !below(r, q, emax + 1) {
        exceptions |= replacement;
        (Magnitude::Infinity, true)
    } else if below(r, q, emin) {
        exceptions |= replacement;
        (Magnitude::Zero, false)
    } else {
        (Magnitude::of(r, q), rounded_up)
    };
    Outcome {
        negative,
        magnitude,
        exceptions,
        rounded_up,
        tiny,
    }
}

// Decodes a single-precision result into an Outcome for comparison.
fn single_outcome(rounded: Rounded<Single>) -> Outcome {
    let bits = rounded.value.0;
    let (exponent, fraction) = ((bits >> 23) & 0xFF, bits & 0x7F_FFFF);
    let magnitude = match exponent {
        0xFF => {
            assert_eq!(fraction, 0, "a NaN");
            Magnitude::Infinity
        }
        0 => Magnitude::of(fraction.into(), -149),
        _ => Magnitude::of((fraction | 1 << 23).into(), exponent as i32 - 150),
    };
    outcome(bits >> 31 != 0, magnitude, &rounded)
}

fn double_outcome(rounded: Rounded<Double>) -> Outcome {
    let bits = rounded.value.0;
    let (exponent, fraction) = ((bits >> 52) & 0x7FF, bits & 0xF_FFFF_FFFF_FFFF);
    let magnitude = match exponent {
        0x7FF => {
            assert_eq!(fraction, 0, "a NaN");
            Magnitude::Infinity
        }
        0 => Magnitude::of(fraction.into(), -1074),
        _ => Magnitude::of((fraction | 1 << 52).into(), exponent as i32 - 1075),
    };
    outcome(bits >> 63 != 0, magnitude, &rounded)
}

// Decodes an 80-bit result and checks that it is canonical.
// Its integer bit must be set exactly when its exponent is nonzero.
fn extended_outcome(rounded: Rounded<Extended>) -> Outcome {
    let Extended {
        sign_exponent,
        significand,
    } = rounded.value;
    let exponent = i32::from(sign_exponent & 0x7FFF);
    let integer = significand >> 63 != 0;
    assert_eq!(integer, exponent != 0, "a noncanonical {:?}", rounded.value);
    let magnitude = match exponent {
        0x7FFF => {
            assert_eq!(significand, 1 << 63, "a NaN");
            Magnitude::Infinity
        }
        0 => Magnitude::of(significand.into(), -16445),
        _ => Magnitude::of(significand.into(), exponent - 16446),
    };
    outcome(sign_exponent >> 15 != 0, magnitude, &rounded)
}

fn outcome<T>(negative: bool, magnitude: Magnitude, rounded: &Rounded<T>) -> Outcome {
    Outcome {
        negative,
        magnitude,
        exceptions: rounded.exceptions,
        rounded_up: rounded.rounded_up,
        tiny: rounded.tiny,
    }
}

// The two words form one 128-bit integer whose leading bit weighs 2^exponent.
fn exact<F>(u: Unrounded<F>) -> (u128, i32) {
    (
        u128::from(u.significand) << 64 | u128::from(u.extra),
        u.exponent - 127,
    )
}

fn check_single(u: Unrounded<Single>, rounding: Rounding) -> (Outcome, Outcome) {
    let (m, s) = exact(u);
    (
        single_outcome(<Single as Real>::round(u, rounding)),
        reference(u.negative, m, s, SINGLE, rounding, Tininess::AfterRounding),
    )
}

fn check_double(u: Unrounded<Double>, rounding: Rounding) -> (Outcome, Outcome) {
    let (m, s) = exact(u);
    (
        double_outcome(<Double as Real>::round(u, rounding)),
        reference(u.negative, m, s, DOUBLE, rounding, Tininess::AfterRounding),
    )
}

fn check_extended(
    u: Unrounded<Extended>,
    rounding: Rounding,
    precision: Precision,
) -> (Outcome, Outcome) {
    let (m, s) = exact(u);
    (
        extended_outcome(extended::round(u, rounding, precision)),
        reference(
            u.negative,
            m,
            s,
            extended_grid(precision),
            rounding,
            Tininess::AfterRounding,
        ),
    )
}

fn rounding() -> impl Strategy<Value = Rounding> {
    prop_oneof![
        Just(Rounding::Nearest),
        Just(Rounding::Down),
        Just(Rounding::Up),
        Just(Rounding::TowardZero),
    ]
}

fn precision() -> impl Strategy<Value = Precision> {
    prop_oneof![
        Just(Precision::Single),
        Just(Precision::Double),
        Just(Precision::Extended),
    ]
}

// Generates rounding-bit patterns for widths from 1 to 64.
// Samples zero, one, just below half, half, just above half, all ones,
// and random patterns.
fn low_bits(width: u32) -> impl Strategy<Value = u64> {
    let all = u64::MAX >> (64 - width);
    let half = 1u64 << (width - 1);
    prop_oneof![
        Just(0),
        Just(1),
        Just(half - 1),
        Just(half),
        Just((half + 1).min(all)),
        Just(all),
        any::<u64>().prop_map(move |v| v & all),
    ]
}

// Generates retained bits below the integer bit.
// Samples all ones to exercise rounding carries, all zeros, and random patterns.
fn kept_bits(width: u32) -> impl Strategy<Value = u64> {
    let all = u64::MAX >> (64 - width);
    prop_oneof![Just(all), Just(0), any::<u64>().prop_map(move |v| v & all)]
}

// Samples the normal range, rounding carries at both boundaries, and values
// below half the smallest denormal. Unmasked cases also straddle the limits
// of the exponent adjustment.
fn exponent(grid: Grid, unmasked: bool) -> BoxedStrategy<i32> {
    let masked = prop_oneof![
        grid.emin - grid.precision - 4..=grid.emin + 2,
        grid.emax - 4..=grid.emax + 4,
        grid.emin..=grid.emax,
    ];
    if unmasked {
        let low = grid.emin - grid.adjust;
        let high = grid.emax + grid.adjust;
        prop_oneof![low - 4..=low + 4, high - 4..=high + 4, masked].boxed()
    } else {
        masked.boxed()
    }
}

fn unrounded<F: std::fmt::Debug>(
    grid: Grid,
    unmasked: bool,
) -> impl Strategy<Value = Unrounded<F>> {
    // At full precision the tail supplies the round bit. Vary the last
    // significand bit separately to cover both parities at a tie.
    let low = (64 - grid.precision as u32).max(1);
    (
        any::<bool>(),
        exponent(grid, unmasked),
        kept_bits(63 - low),
        low_bits(low),
        low_bits(64),
    )
        .prop_map(move |(negative, exponent, kept, discarded, extra)| {
            Unrounded::from_parts(negative, exponent, 1 << 63 | kept << low | discarded, extra)
        })
}

fn extended_unrounded(unmasked: bool) -> impl Strategy<Value = (Unrounded<Extended>, Precision)> {
    precision()
        .prop_flat_map(move |p| unrounded(extended_grid(p), unmasked).prop_map(move |u| (u, p)))
}

proptest! {
    #![proptest_config(model_config(16384))]

    #[test]
    fn a_32_bit_result_rounds_as_its_exact_value(
        u in unrounded(SINGLE, false),
        rounding in rounding(),
    ) {
        let (subject, reference) = check_single(u, rounding);
        prop_assert_eq!(subject, reference);
    }

    #[test]
    fn a_64_bit_result_rounds_as_its_exact_value(
        u in unrounded(DOUBLE, false),
        rounding in rounding(),
    ) {
        let (subject, reference) = check_double(u, rounding);
        prop_assert_eq!(subject, reference);
    }

    #[test]
    fn an_80_bit_result_rounds_as_its_exact_value(
        (u, precision) in extended_unrounded(false),
        rounding in rounding(),
    ) {
        let (subject, reference) = check_extended(u, rounding, precision);
        prop_assert_eq!(subject, reference);
    }

    #[test]
    fn a_32_bit_result_s_unmasked_exceptions_come_from_its_exact_value(
        u in unrounded(SINGLE, true),
        rounding in rounding(),
    ) {
        let (m, s) = exact(u);
        let subject = <Single as Real>::unmasked_exceptions(u, rounding);
        let reference = reference_unmasked(u.negative, m, s, SINGLE, rounding);
        prop_assert_eq!(subject, reference.exceptions);
    }

    #[test]
    fn a_64_bit_result_s_unmasked_exceptions_come_from_its_exact_value(
        u in unrounded(DOUBLE, true),
        rounding in rounding(),
    ) {
        let (m, s) = exact(u);
        let subject = <Double as Real>::unmasked_exceptions(u, rounding);
        let reference = reference_unmasked(u.negative, m, s, DOUBLE, rounding);
        prop_assert_eq!(subject, reference.exceptions);
    }

    #[test]
    fn an_80_bit_result_s_unmasked_response_is_its_exact_value_rebiased(
        (u, precision) in extended_unrounded(true),
        rounding in rounding(),
    ) {
        let (m, s) = exact(u);
        let subject = extended_outcome(extended::round_unmasked(u, rounding, precision));
        let reference = reference_unmasked(u.negative, m, s, extended_grid(precision), rounding);
        prop_assert_eq!(subject, reference);
    }
}

// The exact products 2^127 * 2, 2^1023 * 2 and 2^16383 * 2 overflow.
// The masked response returns infinity with OE and PE. An unmasked OE
// reports only OE, and the 80-bit response divides the result by 2^24576.
#[test]
fn an_exact_overflow_is_exact_only_unmasked() {
    let s = Unrounded::<Single>::new(false, 128, 1 << 63);
    let masked = <Single as Real>::round(s, Rounding::Nearest);
    assert_eq!(masked.exceptions, Exceptions::OE | Exceptions::PE);
    let unmasked = <Single as Real>::unmasked_exceptions(s, Rounding::Nearest);
    assert_eq!(unmasked, Exceptions::OE);

    let d = Unrounded::<Double>::new(false, 1024, 1 << 63);
    let masked = <Double as Real>::round(d, Rounding::Nearest);
    assert_eq!(masked.exceptions, Exceptions::OE | Exceptions::PE);
    let unmasked = <Double as Real>::unmasked_exceptions(d, Rounding::Nearest);
    assert_eq!(unmasked, Exceptions::OE);

    let u = Unrounded::<Extended>::new(false, 16384, 1 << 63);
    let masked = extended::round(u, Rounding::Nearest, Precision::Extended);
    assert_eq!(masked.exceptions, Exceptions::OE | Exceptions::PE);
    let unmasked = extended::round_unmasked(u, Rounding::Nearest, Precision::Extended);
    assert_eq!(unmasked.exceptions, Exceptions::OE);
    assert_eq!(unmasked.value.sign_exponent, 0x7FFF - 24_576);
}

// 2^-127 * (1 + 2^-23) is exact at an unbounded exponent and inexact on the
// 32-bit denormal grid. The masked response reports UE and PE. An unmasked
// UE reports only UE.
#[test]
fn a_tiny_result_exact_at_an_unbounded_exponent_is_exact_only_unmasked() {
    let u = Unrounded::<Single>::new(false, -127, 1 << 63 | 1 << 40);
    let masked = <Single as Real>::round(u, Rounding::Nearest);
    assert_eq!(masked.exceptions, Exceptions::UE | Exceptions::PE);
    let unmasked = <Single as Real>::unmasked_exceptions(u, Rounding::Nearest);
    assert_eq!(unmasked, Exceptions::UE);
}

// Half the smallest normal is exactly representable as a denormal.
// The result is tiny but raises no exceptions.
#[test]
fn half_the_smallest_normal_is_an_exact_tiny_denormal() {
    let single = Unrounded::<Single>::new(false, -127, 1 << 63);
    let double = Unrounded::<Double>::new(false, -1023, 1 << 63);
    for (subject, reference) in [
        check_single(single, Rounding::Nearest),
        check_double(double, Rounding::Nearest),
    ] {
        assert_eq!(subject, reference);
        assert!(subject.tiny);
        assert_eq!(subject.exceptions, Exceptions::NONE);
    }
}

// At 24- and 53-bit precision, exactly half a rounding unit rounds to even.
// A set bit in the extra fraction moves the value above the tie and makes
// it round up.
#[test]
fn a_reduced_precision_tie_breaks_on_the_fraction_past_the_significand() {
    for (precision, below) in [(Precision::Single, 40), (Precision::Double, 11)] {
        let tie = Unrounded::<Extended>::new(false, 0, 1 << 63 | 1 << (below - 1));
        let (subject, reference) = check_extended(tie, Rounding::Nearest, precision);
        assert_eq!(subject, reference);
        assert!(!subject.rounded_up);
        let past = Unrounded { extra: 1, ..tie };
        let (subject, reference) = check_extended(past, Rounding::Nearest, precision);
        assert_eq!(subject, reference);
        assert!(subject.rounded_up);
    }
}

// An all-ones significand just below the smallest normal remains tiny when
// rounded with an unbounded exponent. Rounding on the denormal grid can
// still produce the smallest normal.
// Adding half a unit makes the unbounded-exponent result normal too,
// so that input is not tiny.
#[test]
fn tininess_is_judged_after_rounding_with_the_exponent_unbounded() {
    let all_ones = Unrounded::<Extended>::new(false, -16383, u64::MAX);
    let (subject, reference) = check_extended(all_ones, Rounding::Nearest, Precision::Extended);
    assert_eq!(subject, reference);
    assert!(subject.tiny);
    assert_eq!(subject.exceptions, Exceptions::UE | Exceptions::PE);
    let past = Unrounded {
        extra: 1 << 63,
        ..all_ones
    };
    let (subject, reference) = check_extended(past, Rounding::Nearest, Precision::Extended);
    assert_eq!(subject, reference);
    assert!(!subject.tiny);
    assert_eq!(subject.exceptions, Exceptions::PE);
    // These 32- and 64-bit inputs sit just below the smallest normal.
    // Nearest rounding reaches that normal even with an unbounded exponent,
    // so the result is not tiny. Toward-zero rounding remains below it,
    // producing a tiny, inexact result.
    let single = Unrounded::<Single>::new(false, -127, u64::MAX);
    let double = Unrounded::<Double>::new(false, -1023, u64::MAX);
    for (rounding, tiny) in [(Rounding::Nearest, false), (Rounding::TowardZero, true)] {
        for (subject, reference) in [
            check_single(single, rounding),
            check_double(double, rounding),
        ] {
            assert_eq!(subject, reference, "{rounding:?}");
            assert_eq!(subject.tiny, tiny, "{rounding:?}");
        }
    }
}

// Rounding an all-ones significand upward carries into the exponent at
// every precision. The result is the next power of two, with rounded_up set.
#[test]
fn a_carry_out_of_the_significand_rounds_up_at_every_precision() {
    let all_ones = Unrounded::<Extended>::from_parts(false, 0, u64::MAX, 1);
    for precision in [Precision::Single, Precision::Double, Precision::Extended] {
        let (subject, reference) = check_extended(all_ones, Rounding::Up, precision);
        assert_eq!(subject, reference, "{precision:?}");
        assert!(subject.rounded_up, "{precision:?}");
        let two = Magnitude::Finite {
            significand: 1,
            exponent: 1,
        };
        assert_eq!(subject.magnitude, two, "{precision:?}");
    }
}

// Checks both signs and every rounding mode at the overflow boundary.
// An exponent beyond the limit always reports overflow. Nearest or
// away-from-zero rounding returns infinity with rounded_up set.
// Other modes return the largest finite value.
// At the maximum exponent, an all-ones significand overflows only for
// nearest or away-from-zero rounding. Other modes return an inexact
// largest finite value.
#[test]
fn an_overflow_goes_to_an_infinity_or_the_largest_value_by_the_rounding() {
    for negative in [false, true] {
        for rounding in [
            Rounding::Nearest,
            Rounding::Down,
            Rounding::Up,
            Rounding::TowardZero,
        ] {
            let away = match rounding {
                Rounding::Nearest => true,
                Rounding::TowardZero => false,
                Rounding::Up => !negative,
                Rounding::Down => negative,
            };
            for past in [true, false] {
                let offset = i32::from(past);
                let single = Unrounded::<Single>::new(negative, 127 + offset, u64::MAX);
                let double = Unrounded::<Double>::new(negative, 1023 + offset, u64::MAX);
                let extended =
                    Unrounded::<Extended>::from_parts(negative, 16383 + offset, u64::MAX, u64::MAX);
                for (subject, reference) in [
                    check_single(single, rounding),
                    check_double(double, rounding),
                    check_extended(extended, rounding, Precision::Extended),
                    check_extended(extended, rounding, Precision::Double),
                    check_extended(extended, rounding, Precision::Single),
                ] {
                    let case = format!("{rounding:?}, negative {negative}, past {past}");
                    assert_eq!(subject, reference, "{case}");
                    let overflows = subject.exceptions.contains(Exceptions::OE);
                    assert_eq!(overflows, past || away, "{case}");
                    assert_eq!(subject.magnitude == Magnitude::Infinity, away, "{case}");
                }
            }
        }
    }
}

// The input denormals have magnitudes (2^40 + 1) and 2 in units of 2^-16445.
#[test]
fn a_denormal_sum_receives_the_adjusted_x87_underflow_result() {
    let a = Extended {
        sign_exponent: 0x8000,
        significand: (1 << 40) + 1,
    };
    let b = Extended {
        sign_exponent: 0x8000,
        significand: 2,
    };
    let Computed::Unfinished(u) = extended::add(a, b, Rounding::Nearest) else {
        panic!("a nonzero denormal sum requires rounding");
    };
    for precision in PRECISIONS {
        let subject = extended_outcome(extended::round_unmasked(u, Rounding::Nearest, precision));
        let expected = reference_unmasked(
            true,
            (1 << 40) + 3,
            -16445,
            extended_grid(precision),
            Rounding::Nearest,
        );
        assert_eq!(subject, expected, "{precision:?}");
        assert!(subject.exceptions.contains(Exceptions::UE) && subject.tiny);
    }
}

fn tail(rng: &mut Rng) -> u64 {
    match rng.next() % 6 {
        0 => 0,
        1 => 1 << 63,
        2 => (1 << 63) | 1,
        3 => (1 << 63) - 1,
        4 => 1,
        _ => rng.next(),
    }
}

// Compare the core's seeded in-range cases directly with the integer model.
#[test]
fn binary_rounding_matches_the_model_in_every_mode() {
    let mut rng = Rng(0x0123_4567_89AB_CDEF);
    for _ in 0..400_000 {
        let (significand, extra) = (pattern(&mut rng), tail(&mut rng));
        let negative = rng.next() & 1 == 1;
        for rounding in ROUNDINGS {
            let exponent = (rng.next() % 2040) as i32 - 1020;
            let u = Unrounded::<Double>::from_parts(negative, exponent, significand, extra);
            let (m, s) = exact(u);
            let r = u
                .round(rounding, Tininess::AfterRounding)
                .map_exceptions(Exceptions::from);
            assert_eq!(
                double_outcome(r),
                reference(negative, m, s, DOUBLE, rounding, Tininess::AfterRounding)
            );

            let exponent = (rng.next() % 250) as i32 - 125;
            let u = Unrounded::<Single>::from_parts(negative, exponent, significand, extra);
            let (m, s) = exact(u);
            let r = u
                .round(rounding, Tininess::BeforeRounding)
                .map_exceptions(Exceptions::from);
            assert_eq!(
                single_outcome(r),
                reference(negative, m, s, SINGLE, rounding, Tininess::BeforeRounding)
            );
        }
    }
}

// The general path and the public rounding entry point must agree with the
// independent model on both sides of each exponent boundary.
#[test]
fn extended_rounding_matches_the_general_path_and_the_model() {
    let mut rng = Rng(0xFEDC_BA98_7654_3210);
    for _ in 0..400_000 {
        let (significand, extra) = (pattern(&mut rng), tail(&mut rng));
        let negative = rng.next() & 1 == 1;
        let exponent = match rng.next() % 4 {
            0 => 16383 - (rng.next() % 3) as i32,
            1 => -16382 + (rng.next() % 3) as i32,
            2 => (rng.next() % 40_000) as i32 - 20_000,
            _ => (rng.next() % 32_000) as i32 - 16_000,
        };
        let u = Unrounded::<Extended>::from_parts(negative, exponent, significand, extra);
        let (m, s) = exact(u);
        for rounding in ROUNDINGS {
            for precision in PRECISIONS {
                for tininess in [Tininess::BeforeRounding, Tininess::AfterRounding] {
                    let r = u.round(rounding, precision, tininess);
                    assert_eq!(r, super::extended_general(u, rounding, precision, tininess));
                    assert_eq!(
                        extended_outcome(r.map_exceptions(Exceptions::from)),
                        reference(negative, m, s, extended_grid(precision), rounding, tininess)
                    );
                }
            }
        }
    }
}