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
use super::extended::Reduction;
use super::{
    Computed, Double, Exceptions, Extended, Precision, Rounded, Rounding, Single, double, extended,
    rounding_from_bits,
};
use crate::Flags;
use crate::test_util::{ROUNDINGS, Rng, pattern};

#[test]
fn exception_masks_partition_the_status_word() {
    for bits in 0u8..64 {
        let e = Exceptions(bits);
        assert_eq!(e.pre_computation(), Exceptions(bits & 0b000_111));
        assert_eq!(e.post_computation(), Exceptions(bits & 0b111_000));
        assert_eq!(e & Exceptions::ALL, e);
        assert!(Exceptions::ALL.contains(e));
        assert_eq!(e.when(false), Exceptions::NONE);
    }
}

#[test]
fn rounding_control_reads_two_bits() {
    for bits in 0u16..256 {
        assert_eq!(
            rounding_from_bits(bits as u8),
            ROUNDINGS[usize::from(bits & 3)]
        );
    }
}

#[test]
fn semantic_flags_map_to_x86_bits_without_a_denormal_operand_flag() {
    let mut combined = Flags::NONE;
    for (flag, exception, bits) in [
        (Flags::INVALID, Exceptions::IE, 1),
        (Flags::DIVIDE_BY_ZERO, Exceptions::ZE, 4),
        (Flags::OVERFLOW, Exceptions::OE, 8),
        (Flags::UNDERFLOW, Exceptions::UE, 16),
        (Flags::INEXACT, Exceptions::PE, 32),
    ] {
        assert_eq!(Exceptions::from(flag), exception);
        assert_eq!(exception.0, bits);
        combined |= flag;
    }
    assert_eq!(
        Exceptions::from(Flags::OVERFLOW | Flags::INEXACT),
        Exceptions::OE | Exceptions::PE
    );
    assert_eq!(Exceptions::from(combined).0, 0x3D);
    assert_eq!(Exceptions::from(Flags::NONE), Exceptions::NONE);
}

// Two quiet NaNs with equal significands differ only in sign. The positive
// one is chosen in either operand order, and neither raises IE.
#[test]
fn equal_extended_nans_propagate_the_positive_one() {
    let positive = Extended {
        sign_exponent: 0x7FFF,
        significand: 0xC000_0000_0000_0001,
    };
    let negative = Extended {
        sign_exponent: 0xFFFF,
        ..positive
    };
    for (a, b) in [(positive, negative), (negative, positive)] {
        assert_eq!(extended::propagate_nan(a, b), (positive, Exceptions::NONE));
    }
}

// A NaN keeps its sign and leading payload bits across formats. Narrowing
// drops the low payload bits, and a signalling source raises IE.
#[test]
fn a_nan_keeps_its_leading_payload_across_formats() {
    assert_eq!(
        double::to_single(Double(0xFFFC_0000_2000_0000)),
        Computed::Finished(Single(0xFFE0_0001), Exceptions::NONE)
    );
    assert_eq!(
        double::to_single(Double(0x7FF4_0000_0000_0001)),
        Computed::Finished(Single(0x7FE0_0000), Exceptions::IE)
    );
    assert_eq!(
        double::from_single(Single(0x7FA0_0001)),
        (Double(0x7FFC_0000_2000_0000), Exceptions::IE)
    );
}

// Returns the value (-1)^negative × significand × 2^(exponent − 63).
fn x(negative: bool, exponent: i32, significand: u64) -> Extended {
    Extended {
        sign_exponent: u16::from(negative) << 15 | (exponent + 16383) as u16,
        significand,
    }
}

// Rounds a result that must be exact and returns its value.
fn exact(computed: Computed<Extended>) -> Extended {
    let rounded = computed.settle(|u| extended::round(u, Rounding::Nearest, Precision::Extended));
    assert_eq!(rounded.exceptions, Exceptions::NONE, "an exact result");
    rounded.value
}

#[test]
fn scale_moves_the_exponent_by_the_truncated_count() {
    let mut rng = Rng(0x5CA1_E5CA_1E5C_A1E5);
    for _ in 0..200_000 {
        let negative = rng.next() & 1 == 1;
        let a = x(
            negative,
            (rng.next() % 2001) as i32 - 1000,
            pattern(&mut rng),
        );
        let n = (rng.next() % 4001) as i64 - 2000;
        // Bits below the units place change b without changing its
        // truncation.
        let b = if n == 0 {
            x(
                rng.next() & 1 == 1,
                -1 - (rng.next() % 40) as i32,
                pattern(&mut rng),
            )
        } else {
            let whole = Extended::from_i64(n);
            let units = whole.exponent() - 16383;
            Extended {
                significand: whole.significand | rng.next() >> (units + 1),
                ..whole
            }
        };
        let expected = x(negative, a.exponent() - 16383 + n as i32, a.significand);
        assert_eq!(exact(extended::scale(a, b)), expected, "{a:?} by {b:?}");
    }
}

#[test]
fn scale_handles_zeros_infinities_and_nans() {
    let (two, zero) = (Extended::from_i64(2), Extended::zero(false));
    let (infinity, minus_infinity) = (Extended::infinity(false), Extended::infinity(true));
    let finished = |value, raised| Computed::Finished(value, raised);
    for (a, b, expected) in [
        (
            infinity,
            minus_infinity,
            finished(extended::DEFAULT_NAN, Exceptions::IE),
        ),
        (
            zero,
            infinity,
            finished(extended::DEFAULT_NAN, Exceptions::IE),
        ),
        (two, minus_infinity, finished(zero, Exceptions::NONE)),
        (
            Extended::from_i64(-2),
            infinity,
            finished(minus_infinity, Exceptions::NONE),
        ),
        (infinity, two, finished(infinity, Exceptions::NONE)),
        (
            Extended::zero(true),
            two,
            finished(Extended::zero(true), Exceptions::NONE),
        ),
    ] {
        assert_eq!(extended::scale(a, b), expected, "{a:?} by {b:?}");
    }
    let signalling = x(false, 16384, 0xA000_0000_0000_0000);
    let quieted = Extended {
        significand: 0xE000_0000_0000_0000,
        ..signalling
    };
    assert_eq!(
        extended::scale(two, signalling),
        finished(quieted, Exceptions::IE)
    );
}

// A zero count returns a denormal unchanged, even with UE unmasked. A count of
// 0.5 truncates to zero but still takes the unmasked underflow response, with
// UE and no PE.
#[test]
fn scale_by_zero_leaves_a_denormal_without_underflow() {
    let denormal = Extended {
        sign_exponent: 0x8000,
        significand: 0x413E_A763_4D79_1317,
    };
    for zero in [Extended::zero(false), Extended::zero(true)] {
        assert_eq!(
            extended::scale(denormal, zero),
            Computed::Finished(denormal, Exceptions::NONE)
        );
    }
    let Computed::Unfinished(u) = extended::scale(denormal, x(false, -1, 1 << 63)) else {
        panic!("a fractional count still needs a range response");
    };
    let unmasked = extended::round_unmasked(u, Rounding::Nearest, Precision::Extended);
    assert_eq!(
        (unmasked.value, unmasked.exceptions),
        (
            Extended {
                sign_exponent: 0xE000,
                significand: 0x827D_4EC6_9AF2_262E,
            },
            Exceptions::UE
        )
    );
}

#[test]
fn extract_splits_a_value_that_scale_rebuilds() {
    let mut rng = Rng(0xE7A1_C7E7_A1C7_E7A1);
    for i in 0..200_000 {
        let negative = rng.next() & 1 == 1;
        // Every fourth value is a denormal.
        let a = if i % 4 == 0 {
            Extended {
                sign_exponent: u16::from(negative) << 15,
                significand: pattern(&mut rng) >> (1 + rng.next() % 63),
            }
        } else {
            x(
                negative,
                (rng.next() % 32_765) as i32 - 16_382,
                pattern(&mut rng),
            )
        };
        let (exponent, significand, raised) = extended::extract(a);
        assert_eq!(raised, Exceptions::NONE);
        assert_eq!(significand.sign_exponent, u16::from(negative) << 15 | 16383);
        assert_eq!(exact(extended::scale(significand, exponent)), a);
    }
    let zero = Extended::zero(true);
    assert_eq!(
        extended::extract(zero),
        (Extended::infinity(true), zero, Exceptions::ZE)
    );
    let infinity = Extended::infinity(true);
    assert_eq!(
        extended::extract(infinity),
        (Extended::infinity(false), infinity, Exceptions::NONE)
    );
}

// Returns a remainder's value in units of 2^(exponent − 63), signed relative
// to `sign`: positive when the remainder has that sign.
fn units(r: Extended, exponent: i32, sign: bool) -> i128 {
    if r.is_zero() {
        return 0;
    }
    let shift = exponent - (r.exponent() - 16383);
    assert!((0..64).contains(&shift), "a remainder below the divisor");
    let magnitude = i128::from(r.significand >> shift);
    assert_eq!(
        magnitude << shift,
        i128::from(r.significand),
        "a whole number of units"
    );
    if r.negative() == sign {
        magnitude
    } else {
        -magnitude
    }
}

#[test]
fn remainder_satisfies_the_division_identity() {
    let mut rng = Rng(0x2E3A_17DE_2E3A_17DE);
    for _ in 0..200_000 {
        let (a_negative, b_negative) = (rng.next() & 1 == 1, rng.next() & 1 == 1);
        let exponent = (rng.next() % 201) as i32 - 100;
        let apart = (rng.next() % 63) as i32;
        let (ma, mb) = (pattern(&mut rng), pattern(&mut rng));
        let (a, b) = (
            x(a_negative, exponent + apart, ma),
            x(b_negative, exponent, mb),
        );
        // In units of b's last place, a is ma × 2^apart and b is mb.
        let (whole, divisor) = (i128::from(ma) << apart, i128::from(mb));
        for nearest in [false, true] {
            let (computed, reduction) = if nearest {
                extended::remainder_nearest(a, b)
            } else {
                extended::remainder(a, b)
            };
            let Some(Reduction::Complete(quotient)) = reduction else {
                panic!("a complete reduction of {a:?} by {b:?}");
            };
            let r = exact(computed);
            let rest = units(r, exponent, a_negative);
            assert_eq!(whole, i128::from(quotient) * divisor + rest);
            if r.is_zero() {
                assert_eq!(r.negative(), a_negative);
            }
            if nearest {
                assert!(2 * rest.abs() < divisor || 2 * rest.abs() == divisor && quotient & 1 == 0);
            } else {
                assert!((0..divisor).contains(&rest));
            }
        }
    }
}

// Returns ma × 2^apart modulo mb.
fn power_remainder(ma: u64, apart: u32, mb: u64) -> u128 {
    let mb = u128::from(mb);
    let mut value = u128::from(ma) % mb;
    for _ in 0..apart {
        value = value * 2 % mb;
    }
    value
}

#[test]
fn repeated_partial_remainders_reach_the_full_remainder() {
    let mut rng = Rng(0x9A27_1A19_A271_A19A);
    for _ in 0..20_000 {
        let a_negative = rng.next() & 1 == 1;
        let apart = 64 + (rng.next() % 400) as i32;
        let (ma, mb) = (pattern(&mut rng), pattern(&mut rng));
        let (a, b) = (x(a_negative, apart - 200, ma), x(false, -200, mb));
        let rest = power_remainder(ma, apart as u32, mb) as i128;
        let divisor = i128::from(mb);
        for nearest in [false, true] {
            let mut value = a;
            let mut steps = 0;
            let quotient = loop {
                let (computed, reduction) = if nearest {
                    extended::remainder_nearest(value, b)
                } else {
                    extended::remainder(value, b)
                };
                value = exact(computed);
                steps += 1;
                assert!(steps <= 1 + (apart as usize - 32) / 32, "{a:?} by {b:?}");
                match reduction {
                    Some(Reduction::Complete(quotient)) => break quotient,
                    Some(Reduction::Partial) => {}
                    None => panic!("a reduction of {a:?} by {b:?}"),
                }
            };
            let expected =
                if nearest && (2 * rest > divisor || 2 * rest == divisor && quotient & 1 == 1) {
                    rest - divisor
                } else {
                    rest
                };
            assert_eq!(units(value, -200, a_negative), expected, "{a:?} by {b:?}");
        }
    }
}

#[test]
fn packed_decimals_round_trip() {
    let mut rng = Rng(0xBCD0_BCD0_BCD0_BCD0);
    for _ in 0..200_000 {
        let magnitude = rng.next() % 1_000_000_000_000_000_000;
        let negative = rng.next() & 1 == 1;
        let mut bytes = [0u8; 10];
        let mut rest = magnitude;
        for b in &mut bytes[..9] {
            *b = (rest % 10) as u8 | ((rest / 10 % 10) as u8) << 4;
            rest /= 100;
        }
        bytes[9] = u8::from(negative) << 7;
        let value = extended::from_bcd(bytes);
        let signed = Extended::from_i64(magnitude as i64);
        assert_eq!(value.significand, signed.significand);
        assert_eq!(
            value.sign_exponent,
            signed.sign_exponent | u16::from(negative) << 15
        );
        for rounding in ROUNDINGS {
            assert_eq!(
                extended::to_bcd(value, rounding),
                Rounded::exact(bytes, Exceptions::NONE)
            );
        }
    }
}

#[test]
fn packed_decimal_stores_round_and_reject() {
    let indefinite = Rounded::exact([0, 0, 0, 0, 0, 0, 0, 0xC0, 0xFF, 0xFF], Exceptions::IE);
    let two_and_a_half = x(false, 1, 0xA000_0000_0000_0000);
    let rounded = |digit: u8, negative: bool, up: bool| Rounded {
        value: [digit, 0, 0, 0, 0, 0, 0, 0, 0, u8::from(negative) << 7],
        exceptions: Exceptions::PE,
        rounded_up: up,
        tiny: false,
    };
    assert_eq!(
        extended::to_bcd(two_and_a_half, Rounding::Nearest),
        rounded(2, false, false)
    );
    assert_eq!(
        extended::to_bcd(two_and_a_half, Rounding::Up),
        rounded(3, false, true)
    );
    let minus_half = x(true, -1, 1 << 63);
    assert_eq!(
        extended::to_bcd(minus_half, Rounding::Nearest),
        rounded(0, true, false)
    );
    let too_large = Extended::from_i64(1_000_000_000_000_000_000);
    assert_eq!(extended::to_bcd(too_large, Rounding::Nearest), indefinite);
    for value in [Extended::infinity(false), extended::DEFAULT_NAN] {
        assert_eq!(extended::to_bcd(value, Rounding::Nearest), indefinite);
    }
}