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
//! x87 arithmetic on canonical 80-bit encodings. These functions use [`super::X86`]
//! and report [`super::Exceptions`]. Rounding detects tininess after rounding.

use super::{
    Computed, Double, Exceptions, Extended, Precision, Relation, Rounded, Rounding, Single,
    Unrounded, X86, indefinite,
};
use crate::nan::NanPolicy;
use crate::{Tininess, round};

/// The x87 real indefinite, a negative quiet NaN with a zero payload.
pub const DEFAULT_NAN: Extended = Extended {
    sign_exponent: 0xFFFF,
    significand: 0xC000_0000_0000_0000,
};

/// Tests whether a canonical operand is a signalling NaN.
#[inline]
pub fn is_signalling_nan(value: Extended) -> bool {
    <X86 as NanPolicy<Extended>>::is_signalling(value)
}

/// Adds using the x86 policy. See [`crate::Extended::add`] for the operand cases.
#[inline]
pub fn add(a: Extended, b: Extended, rounding: Rounding) -> Computed<Extended> {
    a.add::<X86>(b, rounding).map_exceptions(Exceptions::from)
}

/// Subtracts using the x86 policy. See [`crate::Extended::subtract`] for the operand cases.
#[inline]
pub fn subtract(a: Extended, b: Extended, rounding: Rounding) -> Computed<Extended> {
    a.subtract::<X86>(b, rounding)
        .map_exceptions(Exceptions::from)
}

/// Multiplies using the x86 policy. See [`crate::Extended::multiply`] for the operand cases.
#[inline]
pub fn multiply(a: Extended, b: Extended) -> Computed<Extended> {
    a.multiply::<X86>(b).map_exceptions(Exceptions::from)
}

/// Divides using the x86 policy. See [`crate::Extended::divide`] for the operand cases.
#[inline]
pub fn divide(a: Extended, b: Extended) -> Computed<Extended> {
    a.divide::<X86>(b).map_exceptions(Exceptions::from)
}

/// Takes the square root using the x86 policy. See [`crate::Extended::sqrt`] for the operand cases.
#[inline]
pub fn sqrt(a: Extended) -> Computed<Extended> {
    a.sqrt::<X86>().map_exceptions(Exceptions::from)
}

/// Compares using the x86 policy. See [`crate::Extended::compare`] for the operand cases.
#[inline]
pub fn compare(a: Extended, b: Extended, signalling: bool) -> (Relation, Exceptions) {
    let (relation, flags) = a.compare::<X86>(b, signalling);
    (relation, Exceptions::from(flags))
}

/// Selects and quiets the x87 NaN result. At least one operand must be NaN.
/// A signalling operand raises IE.
#[inline]
pub fn propagate_nan(a: Extended, b: Extended) -> (Extended, Exceptions) {
    let (value, flags) = a.propagate_nan::<X86>(b);
    (value, Exceptions::from(flags))
}

/// Rounds at `precision` on the extended grid with masked exceptions and
/// after-rounding tininess.
#[inline]
pub fn round(
    value: Unrounded<Extended>,
    rounding: Rounding,
    precision: Precision,
) -> Rounded<Extended> {
    value
        .round(rounding, precision, Tininess::AfterRounding)
        .map_exceptions(Exceptions::from)
}

/// Rounds at `precision` with an unbounded exponent. On overflow, subtracts
/// 24,576 from the exponent and raises OE. On a tiny result, adds 24,576 and
/// raises UE, even if exact. If the exponent remains out of range, returns
/// signed infinity or signed zero and raises PE. Inexact rounding also raises PE.
///
/// Half the smallest normal is exact. Masked rounding delivers a denormal.
/// The unmasked response raises UE and adjusts the exponent.
///
/// ```
/// use softfpu::{Computed, Extended, Precision, Rounding};
/// use softfpu::x86::{Exceptions, extended};
///
/// let min_normal = Extended { sign_exponent: 1, significand: 1 << 63 };
/// let half = Extended { sign_exponent: 0x3ffe, significand: 1 << 63 };
/// let Computed::Unfinished(u) = extended::multiply(min_normal, half) else {
///     panic!("an exact tiny product still needs a range response");
/// };
/// let masked = extended::round(u, Rounding::Nearest, Precision::Extended);
/// let unmasked = extended::round_unmasked(u, Rounding::Nearest, Precision::Extended);
/// assert_eq!((masked.value.exponent(), masked.exceptions), (0, Exceptions::NONE));
/// assert_eq!((unmasked.value.exponent(), unmasked.exceptions), (24_576, Exceptions::UE));
/// ```
#[inline]
pub fn round_unmasked(
    value: Unrounded<Extended>,
    rounding: Rounding,
    precision: Precision,
) -> Rounded<Extended> {
    let (negative, exponent, significand, extra) = value.parts();
    let parts = adjusted(negative, exponent, significand, extra, rounding, precision);
    let (overflow, underflow, inexact) = parts.flags;
    Rounded {
        value: Extended {
            sign_exponent: u16::from(negative) << 15 | parts.field,
            significand: parts.significand,
        },
        exceptions: Exceptions::OE.when(overflow)
            | Exceptions::UE.when(underflow)
            | Exceptions::PE.when(inexact),
        rounded_up: parts.rounded_up,
        tiny: parts.tiny,
    }
}

/// Rounds to the destination integer width. NaN, infinity or an out-of-range
/// rounded value returns the most negative integer with IE alone.
#[inline]
pub fn to_i16(a: Extended, rounding: Rounding) -> Rounded<i16> {
    indefinite(a.to_i16(rounding), i16::MIN)
}

/// Rounds to the destination integer width. NaN, infinity or an out-of-range
/// rounded value returns the most negative integer with IE alone.
#[inline]
pub fn to_i32(a: Extended, rounding: Rounding) -> Rounded<i32> {
    indefinite(a.to_i32(rounding), i32::MIN)
}

/// Rounds to the destination integer width. NaN, infinity or an out-of-range
/// rounded value returns the most negative integer with IE alone.
#[inline]
pub fn to_i64(a: Extended, rounding: Rounding) -> Rounded<i64> {
    indefinite(a.to_i64(rounding), i64::MIN)
}

/// Rounds to an integral extended value under the x86 NaN policy.
/// A zero result retains its sign. Precision control does not apply.
#[inline]
pub fn round_to_integral(a: Extended, rounding: Rounding) -> Rounded<Extended> {
    a.round_to_integral::<X86>(rounding)
        .map_exceptions(Exceptions::from)
}

/// Widens binary32 exactly. A signalling NaN is quieted and raises IE.
#[inline]
pub fn from_single(value: Single) -> (Extended, Exceptions) {
    let (converted, flags) = Extended::from_single::<X86>(value);
    (converted, Exceptions::from(flags))
}

/// Widens binary64 exactly. A signalling NaN is quieted and raises IE.
#[inline]
pub fn from_double(value: Double) -> (Extended, Exceptions) {
    let (converted, flags) = Extended::from_double::<X86>(value);
    (converted, Exceptions::from(flags))
}

/// Narrows to binary32 with the x86 NaN policy. Finite nonzero inputs return
/// an intermediate for the destination rounding.
#[inline]
pub fn to_single(a: Extended) -> Computed<Single> {
    a.to_single::<X86>().map_exceptions(Exceptions::from)
}

/// Narrows to binary64 with the x86 NaN policy. Finite nonzero inputs return
/// an intermediate for the destination rounding.
#[inline]
pub fn to_double(a: Extended) -> Computed<Double> {
    a.to_double::<X86>().map_exceptions(Exceptions::from)
}

/// Scales `a` by 2 to the power of `b` truncated toward zero, as FSCALE does.
/// NaNs propagate. An infinite `b` gives zero or infinity with the sign of
/// `a`, except that infinity scaled by −∞ and zero scaled by +∞ raise IE. A
/// finite `b` leaves zero and infinity unchanged. A finite nonzero `a` returns
/// the exact scaled value for rounding at full precision.
#[inline]
pub fn scale(a: Extended, b: Extended) -> Computed<Extended> {
    if a.is_nan() || b.is_nan() {
        let (value, raised) = propagate_nan(a, b);
        return Computed::Finished(value, raised);
    }
    if b.is_infinity() {
        let value = match (b.negative(), a.is_infinity(), a.is_zero()) {
            (true, true, _) | (false, _, true) => {
                return Computed::Finished(DEFAULT_NAN, Exceptions::IE);
            }
            (true, false, _) => Extended::zero(a.negative()),
            (false, _, false) => Extended::infinity(a.negative()),
        };
        return Computed::Finished(value, Exceptions::NONE);
    }
    if a.is_infinity() || a.is_zero() {
        return Computed::Finished(a, Exceptions::NONE);
    }
    // A scale of 2^17 exceeds the unmasked-response range for any finite
    // nonzero `a`.
    const HELD: i32 = 1 << 17;
    let count = match b.exponent() - Extended::BIAS {
        ..0 => 0,
        e @ 0..=16 => (b.significand >> (63 - e)) as i32,
        _ => HELD,
    };
    let count = if b.negative() { -count } else { count };
    let (exponent, significand) = a.normalized().expect("a finite nonzero value");
    Computed::Unfinished(Unrounded::new(
        a.negative(),
        exponent - Extended::BIAS + count,
        significand,
    ))
}

/// Splits `a` into its exponent and significand, as FXTRACT does. Returns the
/// unbiased exponent as a value, then the significand with the sign of `a` and
/// an unbiased exponent of zero. A NaN propagates to both results. Zero returns
/// −∞ and `a` with ZE. Infinity returns +∞ and `a`.
#[inline]
pub fn extract(a: Extended) -> (Extended, Extended, Exceptions) {
    if a.is_nan() {
        let (nan, raised) = propagate_nan(a, Extended::zero(false));
        return (nan, nan, raised);
    }
    if a.is_zero() {
        return (Extended::infinity(true), a, Exceptions::ZE);
    }
    if a.is_infinity() {
        return (Extended::infinity(false), a, Exceptions::NONE);
    }
    let (exponent, significand) = a.normalized().expect("a finite nonzero value");
    let fraction = Extended {
        sign_exponent: a.sign_exponent & 0x8000 | Extended::BIAS as u16,
        significand,
    };
    let exponent = Extended::from_i64(i64::from(exponent - Extended::BIAS));
    (exponent, fraction, Exceptions::NONE)
}

/// The progress of a partial remainder.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum Reduction {
    /// The reduction finished. Holds the low 64 bits of the quotient.
    Complete(u64),
    /// The exponents were 64 or more apart, and the result needs another step.
    Partial,
}

/// Returns the partial remainder of `a` by `b` with the quotient truncated
/// toward zero, as FPREM does. See [`remainder_nearest`] for the operand cases.
#[inline]
pub fn remainder(a: Extended, b: Extended) -> (Computed<Extended>, Option<Reduction>) {
    reduce(a, b, false)
}

/// Returns the partial remainder of `a` by `b` with the quotient rounded to
/// nearest, ties to even, as FPREM1 does.
///
/// NaNs propagate and return no reduction. An infinite `a` or a zero `b` raises
/// IE and returns no reduction. A zero `a` or an infinite `b` returns `a` with a
/// complete reduction and a zero quotient. Otherwise the remainder is exact. When
/// the normalized exponent of `a` exceeds that of `b` by 64 or more, the
/// reduction is partial (doc/division.md#partial-remainders). A zero remainder
/// keeps the sign of `a`.
#[inline]
pub fn remainder_nearest(a: Extended, b: Extended) -> (Computed<Extended>, Option<Reduction>) {
    reduce(a, b, true)
}

// Reduces `a` by `b` (doc/division.md#partial-remainders). With `nearest`, a
// complete reduction rounds the quotient to nearest with ties to even.
fn reduce(a: Extended, b: Extended, nearest: bool) -> (Computed<Extended>, Option<Reduction>) {
    if a.is_nan() || b.is_nan() {
        let (value, raised) = propagate_nan(a, b);
        return (Computed::Finished(value, raised), None);
    }
    if a.is_infinity() || b.is_zero() {
        return (Computed::Finished(DEFAULT_NAN, Exceptions::IE), None);
    }
    if a.is_zero() || b.is_infinity() {
        return (
            Computed::Finished(a, Exceptions::NONE),
            Some(Reduction::Complete(0)),
        );
    }
    let nonzero = |x: Extended| x.normalized().expect("a finite nonzero value");
    let ((ea, ma), (eb, mb)) = (nonzero(a), nonzero(b));
    let difference = ea - eb;
    let unrounded = |negative, exponent, significand| {
        Computed::Unfinished(Unrounded::new(
            negative,
            exponent - Extended::BIAS,
            significand,
        ))
    };
    if difference < -1 {
        return (
            unrounded(a.negative(), ea, ma),
            Some(Reduction::Complete(0)),
        );
    }
    let complete = difference < 64;
    let step = if complete {
        difference
    } else {
        difference & 31 | 32
    };
    // Align a and b × 2^(difference − step) for integer division. The extra
    // bit allows step = −1 without discarding a significand bit.
    let x = u128::from(ma) << (step + 1);
    let y = u128::from(mb) << 1;
    let (mut quotient, mut rest, mut negative) = (x / y, x % y, a.negative());
    if nearest && complete && (2 * rest > y || 2 * rest == y && quotient & 1 == 1) {
        (quotient, rest, negative) = (quotient + 1, y - rest, !negative);
    }
    let reduction = if complete {
        Reduction::Complete(quotient as u64)
    } else {
        Reduction::Partial
    };
    if rest == 0 {
        let zero = Computed::Finished(Extended::zero(a.negative()), Exceptions::NONE);
        return (zero, Some(reduction));
    }
    let length = 128 - rest.leading_zeros() as i32;
    let significand = ((rest << rest.leading_zeros()) >> 64) as u64;
    let exponent = eb + (difference - step) + length - 65;
    (unrounded(negative, exponent, significand), Some(reduction))
}

/// Decodes 18 packed decimal digits, as FBLD does. The low nibble of byte 0
/// holds the least significant digit. Bit 7 of byte 9 supplies the sign,
/// including for zero.
#[inline]
pub fn from_bcd(bytes: [u8; 10]) -> Extended {
    let magnitude = bytes[..BCD_DIGIT_BYTES].iter().rev().fold(0u64, |v, &b| {
        v * 100 + u64::from(b >> 4) * 10 + u64::from(b & 0xf)
    });
    let value = Extended::from_i64(magnitude as i64);
    Extended {
        sign_exponent: value.sign_exponent | u16::from(bytes[BCD_DIGIT_BYTES] & 0x80) << 8,
        ..value
    }
}

/// Rounds `a` to an integer and packs it as 18 decimal digits, as FBSTP does.
/// The sign bit keeps the sign of the rounded value, including for zero. NaN,
/// infinity or a rounded magnitude above 18 digits returns the decimal
/// indefinite with IE alone.
#[inline]
pub fn to_bcd(a: Extended, rounding: Rounding) -> Rounded<[u8; 10]> {
    let invalid = Rounded::exact(BCD_INDEFINITE, Exceptions::IE);
    if a.exponent() == i32::from(Extended::EXPONENT_MASK) {
        return invalid;
    }
    let r = round_to_integral(a, rounding);
    let unbiased = r.value.exponent() - Extended::BIAS;
    let magnitude = match unbiased {
        ..0 => 0,
        0..=63 => r.value.significand >> (63 - unbiased),
        _ => return invalid,
    };
    if magnitude > BCD_MAX {
        return invalid;
    }
    r.map(|v| {
        let mut bytes = [0u8; 10];
        let mut rest = magnitude;
        for b in &mut bytes[..BCD_DIGIT_BYTES] {
            *b = (rest % 10) as u8 | ((rest / 10 % 10) as u8) << 4;
            rest /= 100;
        }
        bytes[BCD_DIGIT_BYTES] = u8::from(v.negative()) << 7;
        bytes
    })
}

// Packed decimal: 18 digits, two per byte below the sign byte.
const BCD_DIGIT_BYTES: usize = 9;
const BCD_MAX: u64 = 10u64.pow(18) - 1;
// The decimal indefinite that a failed packed-decimal store writes.
const BCD_INDEFINITE: [u8; 10] = [0, 0, 0, 0, 0, 0, 0, 0xC0, 0xFF, 0xFF];

// The exponent adjustment of the x87 unmasked overflow and underflow
// responses (doc/rounding.md#unmasked-range-responses).
const ADJUSTMENT: i32 = 24_576;

// Computes the x87 register response to an unmasked overflow or underflow
// (doc/rounding.md#unmasked-range-responses). It
// reports the flags as (overflow, underflow, inexact), and the facade names
// them.
#[inline]
fn adjusted(
    negative: bool,
    exponent: i32,
    significand: u64,
    extra: u64,
    rounding: Rounding,
    precision: Precision,
) -> round::ExtendedParts<(bool, bool, bool)> {
    let (exponent, significand, inexact, up) = round::unbounded(
        negative,
        exponent,
        significand,
        extra,
        rounding,
        precision.discarded(),
    );
    let overflow = exponent > Extended::MAX_EXPONENT;
    let tiny = exponent < Extended::MIN_EXPONENT;
    let adjusted = if overflow {
        exponent - ADJUSTMENT
    } else if tiny {
        exponent + ADJUSTMENT
    } else {
        exponent
    };
    if adjusted > Extended::MAX_EXPONENT {
        round::ExtendedParts {
            field: Extended::EXPONENT_MASK,
            significand: 1 << 63,
            flags: (overflow, tiny, true),
            rounded_up: true,
            tiny,
        }
    } else if adjusted < Extended::MIN_EXPONENT {
        round::ExtendedParts {
            field: 0,
            significand: 0,
            flags: (overflow, tiny, true),
            rounded_up: false,
            tiny,
        }
    } else {
        round::ExtendedParts {
            field: (adjusted + Extended::BIAS) as u16,
            significand,
            flags: (overflow, tiny, inexact),
            rounded_up: up,
            tiny,
        }
    }
}