softfpu 0.2.1

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
// Addition and subtraction (doc/addition.md).

use core::hint::select_unpredictable;

use crate::cold::{self, Return};
use crate::format::{Class, Format};
use crate::nan::{self, NanPolicy};
use crate::result::unfinished;
use crate::{Computed, Double, Extended, Flags, Rounding, Single};

impl Single {
    /// Adds the operands. Opposite infinities give the default NaN with INVALID.
    /// Exact cancellation gives −0 under round-toward-negative and +0 otherwise.
    /// Two zeros of the same sign keep that sign. NaNs use [`crate::nan::NanPolicy::choose`].
    pub fn add<N: nan::NanPolicy<Single>>(
        self,
        addend: Single,
        rounding: Rounding,
    ) -> Computed<Single> {
        add::<Single, N>(self, addend, false, rounding)
    }

    /// Subtracts the second operand. Like-signed infinities give the default NaN
    /// with INVALID. Zero signs follow addition with the second sign reversed.
    /// NaN selection receives the original operands in subtraction order.
    pub fn subtract<N: nan::NanPolicy<Single>>(
        self,
        subtrahend: Single,
        rounding: Rounding,
    ) -> Computed<Single> {
        add::<Single, N>(self, subtrahend, true, rounding)
    }
}

impl Double {
    /// Adds the operands. Opposite infinities give the default NaN with INVALID.
    /// Exact cancellation gives −0 under round-toward-negative and +0 otherwise.
    /// Two zeros of the same sign keep that sign. NaNs use [`crate::nan::NanPolicy::choose`].
    pub fn add<N: nan::NanPolicy<Double>>(
        self,
        addend: Double,
        rounding: Rounding,
    ) -> Computed<Double> {
        add::<Double, N>(self, addend, false, rounding)
    }

    /// Subtracts the second operand. Like-signed infinities give the default NaN
    /// with INVALID. Zero signs follow addition with the second sign reversed.
    /// NaN selection receives the original operands in subtraction order.
    pub fn subtract<N: nan::NanPolicy<Double>>(
        self,
        subtrahend: Double,
        rounding: Rounding,
    ) -> Computed<Double> {
        add::<Double, N>(self, subtrahend, true, rounding)
    }
}

impl Extended {
    /// Adds the operands. Opposite infinities give the default NaN with INVALID.
    /// Exact cancellation gives −0 under round-toward-negative and +0 otherwise.
    /// Two zeros of the same sign keep that sign. NaNs use [`crate::nan::NanPolicy::choose`].
    pub fn add<N: nan::NanPolicy<Extended>>(
        self,
        addend: Extended,
        rounding: Rounding,
    ) -> Computed<Extended> {
        add::<Extended, N>(self, addend, false, rounding)
    }

    /// Subtracts the second operand. Like-signed infinities give the default NaN
    /// with INVALID. Zero signs follow addition with the second sign reversed.
    /// NaN selection receives the original operands in subtraction order.
    pub fn subtract<N: nan::NanPolicy<Extended>>(
        self,
        subtrahend: Extended,
        rounding: Rounding,
    ) -> Computed<Extended> {
        add::<Extended, N>(self, subtrahend, true, rounding)
    }
}

trait Addition: Format {
    // `add` calls `sum_inline` only if both operands are normal. For the
    // 80-bit format, `inline` also excludes magnitude subtraction when
    // the exponents are equal or adjacent.
    fn inline(self, other: Self, subtract: bool) -> bool;
    fn sum_inline(
        a_negative: bool,
        a_exponent: i32,
        a: u64,
        b_negative: bool,
        b_exponent: i32,
        b: u64,
    ) -> Option<(bool, i32, u64, u64)>;

    // Returns the sum of two finite nonzero values. The 80-bit format uses
    // the 128-bit form, `sum128`, and the others use the 64-bit form, `sum64`.
    fn sum(
        a_negative: bool,
        a_exponent: i32,
        a: u64,
        b_negative: bool,
        b_exponent: i32,
        b: u64,
    ) -> Option<(bool, i32, u64, u64)>;
}

impl Addition for Single {
    #[inline]
    fn inline(self, other: Single, _: bool) -> bool {
        self.is_normal() & other.is_normal()
    }

    #[inline]
    fn sum_inline(
        a_negative: bool,
        a_exponent: i32,
        a: u64,
        b_negative: bool,
        b_exponent: i32,
        b: u64,
    ) -> Option<(bool, i32, u64, u64)> {
        sum64(a_negative, a_exponent, a, b_negative, b_exponent, b)
    }

    #[inline(always)]
    fn sum(
        a_negative: bool,
        a_exponent: i32,
        a: u64,
        b_negative: bool,
        b_exponent: i32,
        b: u64,
    ) -> Option<(bool, i32, u64, u64)> {
        sum64(a_negative, a_exponent, a, b_negative, b_exponent, b)
    }
}

impl Addition for Double {
    #[inline]
    fn inline(self, other: Double, _: bool) -> bool {
        self.is_normal() & other.is_normal()
    }

    #[inline]
    fn sum_inline(
        a_negative: bool,
        a_exponent: i32,
        a: u64,
        b_negative: bool,
        b_exponent: i32,
        b: u64,
    ) -> Option<(bool, i32, u64, u64)> {
        sum64(a_negative, a_exponent, a, b_negative, b_exponent, b)
    }

    #[inline(always)]
    fn sum(
        a_negative: bool,
        a_exponent: i32,
        a: u64,
        b_negative: bool,
        b_exponent: i32,
        b: u64,
    ) -> Option<(bool, i32, u64, u64)> {
        sum64(a_negative, a_exponent, a, b_negative, b_exponent, b)
    }
}

impl Addition for Extended {
    // A difference of magnitudes with equal or adjacent exponents goes to the
    // slow path. It is the only sum that can cancel by more than one place.
    #[inline]
    fn inline(self, other: Extended, subtract: bool) -> bool {
        let (a, b) = (
            self.sign_exponent,
            other.sign_exponent ^ u16::from(subtract) << 15,
        );
        let mask = Extended::EXPONENT_MASK;
        let cancels = near(
            a >> 15 != 0,
            i32::from(a & mask),
            b >> 15 != 0,
            i32::from(b & mask),
        );
        // Both operands are normal when both integer bits are set and neither
        // exponent field is zero or all ones.
        let integers = (self.significand & other.significand) >> 63 != 0;
        let fields =
            ((a & mask).wrapping_sub(1) < mask - 1) & ((b & mask).wrapping_sub(1) < mask - 1);
        integers & fields & !cancels
    }

    #[inline]
    fn sum_inline(
        a_negative: bool,
        a_exponent: i32,
        a: u64,
        b_negative: bool,
        b_exponent: i32,
        b: u64,
    ) -> Option<(bool, i32, u64, u64)> {
        far128(a_negative, a_exponent, a, b_negative, b_exponent, b)
    }

    #[inline(always)]
    fn sum(
        a_negative: bool,
        a_exponent: i32,
        a: u64,
        b_negative: bool,
        b_exponent: i32,
        b: u64,
    ) -> Option<(bool, i32, u64, u64)> {
        sum128(a_negative, a_exponent, a, b_negative, b_exponent, b)
    }
}

// Adds signed normalized magnitudes whose difference cannot cancel by more
// than one bit. Always returns Some for these inputs.
#[inline(always)]
fn far128(
    a_negative: bool,
    a_exponent: i32,
    a: u64,
    b_negative: bool,
    b_exponent: i32,
    b: u64,
) -> Option<(bool, i32, u64, u64)> {
    // Which operand is larger depends on the data, so the choices avoid a
    // branch.
    let swap = b_exponent > a_exponent;
    let large = select_unpredictable(swap, b, a);
    let small = select_unpredictable(swap, a, b);
    let exponent = a_exponent.max(b_exponent);
    let negative = select_unpredictable(swap, b_negative, a_negative);
    let apart = a_exponent.wrapping_sub(b_exponent).unsigned_abs();
    // Align small in high:low. Capping the distance at 127 preserves every
    // rounding decision (doc/addition.md#extended-precision).
    let distance = apart.min(127);
    let within = distance & 63;
    let upper = small >> within;
    let spill = (small << 1) << (63 - within);
    let beyond = distance >= 64;
    let high = if beyond { 0 } else { upper };
    let low = if beyond { upper } else { spill };
    let lost = u64::from(beyond & (spill != 0));
    if a_negative == b_negative {
        let (total, carry) = large.overflowing_add(high);
        let down = u32::from(carry);
        let carried = u64::from(carry).wrapping_neg();
        let moved_low = ((total << 63 | low >> 1 | (low & 1)) & carried) | (low & !carried);
        return Some((
            negative,
            exponent + down as i32,
            total >> down | u64::from(carry) << 63,
            moved_low,
        ));
    }
    {
        // A lost fraction borrows one unit from the floor of the difference.
        let borrow = u64::from(low != 0);
        let low = 0u64.wrapping_sub(low).wrapping_sub(lost) | lost;
        let high = large.wrapping_sub(high).wrapping_sub(borrow);
        let up = (high >> 63) as u32 ^ 1;
        Some((
            negative,
            exponent - up as i32,
            high << up | (low >> 63 & u64::from(up)),
            low << up,
        ))
    }
}

// Returns whether a sum is a difference of magnitudes with equal or adjacent
// exponents. It is the only case that can cancel by more than one place.
fn near(a_negative: bool, a_exponent: i32, b_negative: bool, b_exponent: i32) -> bool {
    (a_negative != b_negative) & (a_exponent.wrapping_sub(b_exponent).wrapping_add(1) as u32 <= 2)
}

// Returns the general 128-bit sum. It handles the cancelling case itself and
// passes every other sum to `far128`.
#[inline(always)]
fn sum128(
    a_negative: bool,
    a_exponent: i32,
    a: u64,
    b_negative: bool,
    b_exponent: i32,
    b: u64,
) -> Option<(bool, i32, u64, u64)> {
    if !near(a_negative, a_exponent, b_negative, b_exponent) {
        return far128(a_negative, a_exponent, a, b_negative, b_exponent, b);
    }
    near128(a_negative, b_negative, a_exponent, b_exponent, a, b)
}

// Returns the difference of two magnitudes whose exponents are equal or
// adjacent. The difference is exact, with at most 65 significant bits.
// Returns None for a zero difference.
#[inline(always)]
fn near128(
    a_negative: bool,
    b_negative: bool,
    a_exponent: i32,
    b_exponent: i32,
    a: u64,
    b: u64,
) -> Option<(bool, i32, u64, u64)> {
    let (negative, mut exponent, mut high, mut low) = if a_exponent > b_exponent {
        (
            a_negative,
            a_exponent,
            a - (b >> 1) - (b & 1),
            (b & 1) << 63,
        )
    } else if b_exponent > a_exponent {
        (
            b_negative,
            b_exponent,
            b - (a >> 1) - (a & 1),
            (a & 1) << 63,
        )
    } else if b > a {
        (b_negative, b_exponent, b - a, 0)
    } else {
        (a_negative, a_exponent, a - b, 0)
    };
    if high == 0 {
        if low == 0 {
            return None;
        }
        high = low;
        low = 0;
        exponent -= 64;
    }
    let shift = high.leading_zeros();
    Some((
        negative,
        exponent - shift as i32,
        high << shift | (low >> 1) >> (63 - shift),
        low << shift,
    ))
}

// Adds signed magnitudes for binary32 and binary64 in one word. Both input
// significands leave at least two low bits clear (doc/addition.md#binary32-and-binary64).
#[inline(always)]
fn sum64(
    a_negative: bool,
    a_exponent: i32,
    a: u64,
    b_negative: bool,
    b_exponent: i32,
    b: u64,
) -> Option<(bool, i32, u64, u64)> {
    // Which operand is larger depends on the data, so the choices avoid a
    // branch.
    let swap = b_exponent > a_exponent;
    let large = select_unpredictable(swap, b, a);
    let small = select_unpredictable(swap, a, b);
    let exponent = a_exponent.max(b_exponent);
    let negative = select_unpredictable(swap, b_negative, a_negative);
    // At a distance of 64 or more only the sticky bit survives.
    let distance = a_exponent.wrapping_sub(b_exponent).unsigned_abs();
    let far = distance > 63;
    let within = distance & 63;
    let shifted = if far { 0 } else { small >> within };
    // Whether nonzero bits of `small` were shifted out.
    let lost = u64::from(far | (small & ((1u64 << within) - 1) != 0));
    if a_negative == b_negative {
        let (total, carry) = large.overflowing_add(shifted);
        let carry = u32::from(carry);
        let moved = total >> carry | (total & u64::from(carry)) | lost | u64::from(carry) << 63;
        return Some((negative, exponent + carry as i32, moved, 0));
    }
    if distance > 1 {
        // Subtract the borrow before setting the sticky bit of the difference.
        let difference = large.wrapping_sub(shifted).wrapping_sub(lost) | lost;
        let shift = (difference >> 63) as u32 ^ 1;
        return Some((negative, exponent - shift as i32, difference << shift, 0));
    }
    let (negative, difference) = if distance == 1 {
        (negative, large - shifted)
    } else if b > a {
        (b_negative, b - a)
    } else {
        (a_negative, a - b)
    };
    if difference == 0 {
        return None;
    }
    let shift = difference.leading_zeros();
    Some((negative, exponent - shift as i32, difference << shift, 0))
}

// Handles normal pairs inline except for extended differences that can
// cancel by more than one bit.
#[inline(always)]
fn add<T: Addition, N: NanPolicy<T>>(
    x: T,
    y: T,
    subtract: bool,
    rounding: Rounding,
) -> Computed<T> {
    if T::inline(x, y, subtract) {
        let ((a_negative, a_exponent, a), (b_negative, b_exponent, b)) = (x.normal(), y.normal());
        return match T::sum_inline(
            a_negative,
            a_exponent,
            a,
            b_negative ^ subtract,
            b_exponent,
            b,
        ) {
            Some((negative, exponent, significand, extra)) => {
                unfinished(negative, exponent, significand, extra)
            }
            None => Computed::Finished(T::zero(rounding == Rounding::Down), Flags::NONE),
        };
    }
    slow::<T, N>(x, y, subtract, rounding).into_computed()
}

#[cold]
#[inline(never)]
fn slow<T: Addition, N: NanPolicy<T>>(x: T, y: T, subtract: bool, rounding: Rounding) -> Return {
    let (a, b) = (x.decode(), y.decode());
    let b_negative = b.negative ^ subtract;
    match (a.class, b.class) {
        (Class::Nan, _) | (_, Class::Nan) => cold::nan::<T, N>(x, y),
        (Class::Infinity, Class::Infinity) if a.negative != b_negative => cold::invalid::<T, N>(),
        (Class::Infinity, _) => Return::finished(T::infinity(a.negative), Flags::NONE),
        (_, Class::Infinity) => Return::finished(T::infinity(b_negative), Flags::NONE),
        (Class::Zero, Class::Zero) => {
            let negative = if a.negative == b_negative {
                a.negative
            } else {
                rounding == Rounding::Down
            };
            Return::finished(T::zero(negative), Flags::NONE)
        }
        // The result is the other operand exactly. That operand may be a
        // denormal or wider than a reduced precision, so it is rounded like
        // any result.
        (Class::Zero, _) => Return::unfinished(b_negative, b.exponent, b.significand, 0),
        (_, Class::Zero) => Return::unfinished(a.negative, a.exponent, a.significand, 0),
        _ => match T::sum(
            a.negative,
            a.exponent,
            a.significand,
            b_negative,
            b.exponent,
            b.significand,
        ) {
            Some((negative, exponent, significand, extra)) => {
                Return::unfinished(negative, exponent, significand, extra)
            }
            None => Return::finished(T::zero(rounding == Rounding::Down), Flags::NONE),
        },
    }
}