softfpu 0.2.2

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
// Integer and format conversions (doc/conversions.md).

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

/// Failure of a rounded conversion to a signed integer.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum InvalidConversion {
    /// The operand is NaN.
    Nan,
    /// The operand is positive infinity or rounds above the destination maximum.
    PositiveOverflow,
    /// The operand is negative infinity or rounds below the destination minimum.
    NegativeOverflow,
}

impl Single {
    /// Converts an i32 to binary32. Zero finishes as +0. Nonzero inputs return
    /// an exact intermediate to round at binary32 precision.
    #[inline]
    pub fn from_i32(value: i32) -> Computed<Single> {
        if value == 0 {
            return Computed::Finished(Single(0), Flags::NONE);
        }
        let magnitude = value.unsigned_abs();
        let shift = magnitude.leading_zeros();
        unfinished(
            value < 0,
            31 - shift as i32,
            u64::from(magnitude << shift) << 32,
            0,
        )
    }

    /// Rounds to a signed integer, then checks the destination range. Returns
    /// [`crate::InvalidConversion`] for NaN, infinity or an out-of-range rounded
    /// value. On success, inexact records a discarded nonzero fraction.
    #[inline]
    pub fn to_i32(self, rounding: Rounding) -> Result<Rounded<i32>, InvalidConversion> {
        to_integer(self, rounding, 32).map(|r| r.map(|value| value as i32))
    }

    /// Converts an i64 to binary32. Zero finishes as +0. Nonzero inputs return
    /// an exact intermediate to round at binary32 precision.
    #[inline]
    pub fn from_i64(value: i64) -> Computed<Single> {
        binary_from_i64(value)
    }

    /// Rounds to a signed integer, then checks the destination range. Returns
    /// [`crate::InvalidConversion`] for NaN, infinity or an out-of-range rounded
    /// value. On success, inexact records a discarded nonzero fraction.
    #[inline]
    pub fn to_i64(self, rounding: Rounding) -> Result<Rounded<i64>, InvalidConversion> {
        to_integer(self, rounding, 64)
    }
}

impl Double {
    /// Converts an i32 exactly to binary64.
    #[inline]
    pub fn from_i32(value: i32) -> Double {
        if value == 0 {
            return Double(0);
        }
        let magnitude = value.unsigned_abs();
        let shift = magnitude.leading_zeros();
        // The leading bit, at bit 52 of the second term, adds one to the field.
        let bits = (u64::from(1022 + 31 - shift) << 52) + (u64::from(magnitude << shift) << 21);
        Double(u64::from(value < 0) << 63 | bits)
    }

    /// Rounds to a signed integer, then checks the destination range. Returns
    /// [`crate::InvalidConversion`] for NaN, infinity or an out-of-range rounded
    /// value. On success, inexact records a discarded nonzero fraction.
    #[inline]
    pub fn to_i32(self, rounding: Rounding) -> Result<Rounded<i32>, InvalidConversion> {
        to_integer(self, rounding, 32).map(|r| r.map(|value| value as i32))
    }

    /// Converts an i64 to binary64. Zero finishes as +0. Nonzero inputs return
    /// an exact intermediate to round at binary64 precision.
    #[inline]
    pub fn from_i64(value: i64) -> Computed<Double> {
        binary_from_i64(value)
    }

    /// Rounds to a signed integer, then checks the destination range. Returns
    /// [`crate::InvalidConversion`] for NaN, infinity or an out-of-range rounded
    /// value. On success, inexact records a discarded nonzero fraction.
    #[inline]
    pub fn to_i64(self, rounding: Rounding) -> Result<Rounded<i64>, InvalidConversion> {
        to_integer(self, rounding, 64)
    }

    /// Widens exactly, preserving the sign of zeros and infinities. For NaNs,
    /// the source policy exports the payload and the destination policy imports it.
    pub fn from_single<N: nan::NanPolicy<Double> + nan::NanPolicy<Single>>(
        value: Single,
    ) -> (Double, Flags) {
        widen::<Single, Double, N>(value)
    }

    /// Narrows a finite nonzero operand through an exact intermediate. Returns a
    /// finished signed zero, signed infinity or policy-converted NaN for other inputs.
    pub fn to_single<N: nan::NanPolicy<Double> + nan::NanPolicy<Single>>(self) -> Computed<Single> {
        narrow::<Double, Single, N>(self)
    }
}

impl Extended {
    /// Converts a signed 64-bit integer exactly.
    #[inline]
    pub fn from_i64(value: i64) -> Extended {
        if value == 0 {
            return Extended::zero(false);
        }
        let magnitude = value.unsigned_abs();
        let shift = magnitude.leading_zeros();
        Extended {
            sign_exponent: u16::from(value < 0) << 15 | (Extended::BIAS as u32 + 63 - shift) as u16,
            significand: magnitude << shift,
        }
    }

    /// Rounds to a signed integer, then checks the destination range. Returns
    /// [`crate::InvalidConversion`] for NaN, infinity or an out-of-range rounded
    /// value. On success, inexact records a discarded nonzero fraction.
    #[inline]
    pub fn to_i16(self, rounding: Rounding) -> Result<Rounded<i16>, InvalidConversion> {
        to_integer(self, rounding, 16).map(|r| r.map(|value| value as i16))
    }

    /// Rounds to a signed integer, then checks the destination range. Returns
    /// [`crate::InvalidConversion`] for NaN, infinity or an out-of-range rounded
    /// value. On success, inexact records a discarded nonzero fraction.
    #[inline]
    pub fn to_i32(self, rounding: Rounding) -> Result<Rounded<i32>, InvalidConversion> {
        to_integer(self, rounding, 32).map(|r| r.map(|value| value as i32))
    }

    /// Rounds to a signed integer, then checks the destination range. Returns
    /// [`crate::InvalidConversion`] for NaN, infinity or an out-of-range rounded
    /// value. On success, inexact records a discarded nonzero fraction.
    #[inline]
    pub fn to_i64(self, rounding: Rounding) -> Result<Rounded<i64>, InvalidConversion> {
        to_integer(self, rounding, 64)
    }

    /// Rounds to an integral extended value without applying precision control.
    /// Preserves zero signs and infinities. A NaN uses [`crate::nan::NanPolicy::quiet`].
    /// Sets inexact if rounding changes a finite value.
    pub fn round_to_integral<N: nan::NanPolicy<Extended>>(
        self,
        rounding: Rounding,
    ) -> Rounded<Extended> {
        round_to_integral::<N>(self, rounding)
    }

    /// Widens exactly, preserving the sign of zeros and infinities. For NaNs,
    /// the source policy exports the payload and the destination policy imports it.
    pub fn from_single<N: nan::NanPolicy<Extended> + nan::NanPolicy<Single>>(
        value: Single,
    ) -> (Extended, Flags) {
        widen::<Single, Extended, N>(value)
    }

    /// Widens exactly, preserving the sign of zeros and infinities. For NaNs,
    /// the source policy exports the payload and the destination policy imports it.
    pub fn from_double<N: nan::NanPolicy<Extended> + nan::NanPolicy<Double>>(
        value: Double,
    ) -> (Extended, Flags) {
        widen::<Double, Extended, N>(value)
    }

    /// Narrows a finite nonzero operand through an exact intermediate. Returns a
    /// finished signed zero, signed infinity or policy-converted NaN for other inputs.
    pub fn to_single<N: nan::NanPolicy<Extended> + nan::NanPolicy<Single>>(
        self,
    ) -> Computed<Single> {
        narrow::<Extended, Single, N>(self)
    }

    /// Narrows a finite nonzero operand through an exact intermediate. Returns a
    /// finished signed zero, signed infinity or policy-converted NaN for other inputs.
    pub fn to_double<N: nan::NanPolicy<Extended> + nan::NanPolicy<Double>>(
        self,
    ) -> Computed<Double> {
        narrow::<Extended, Double, N>(self)
    }
}

// Conversions to integers (doc/conversions.md#conversion-to-a-signed-integer).

// Rounds the magnitude significand * 2^(exponent - 63), for exponent <= 63,
// to an integer. Returns the integer, whether it is inexact, and whether it
// was rounded up. For exponent < 63 the integer is at most 2^63. At exponent 63
// it is the significand, which can be any value up to u64::MAX.
#[inline]
fn integral(
    significand: u64,
    exponent: i32,
    rounding: Rounding,
    negative: bool,
) -> (u64, bool, bool) {
    // The number of significand bits below the units place.
    let fraction_bits = 63i32.wrapping_sub(exponent) as u32;
    if fraction_bits == 0 {
        (significand, false, false)
    } else {
        round::units(significand, 0, 0, fraction_bits, rounding, negative)
    }
}

fn overflow(negative: bool) -> InvalidConversion {
    if negative {
        InvalidConversion::NegativeOverflow
    } else {
        InvalidConversion::PositiveOverflow
    }
}

// Converts a finite nonzero value to a signed integer of `bits` bits, which
// is 16, 32 or 64.
#[inline(always)]
fn finite_to_integer(
    negative: bool,
    exponent: i32,
    significand: u64,
    rounding: Rounding,
    bits: u32,
) -> Result<Rounded<i64>, InvalidConversion> {
    // At 2^bits or more nothing rounds into range.
    if exponent >= bits as i32 {
        return Err(overflow(negative));
    }
    let (magnitude, inexact, up) = integral(significand, exponent, rounding, negative);
    // The range is checked after rounding. The limit is 2^(bits-1) - 1, or
    // 2^(bits-1) for a negative value.
    let limit = (1u64 << (bits - 1)) - u64::from(!negative);
    if magnitude > limit {
        return Err(overflow(negative));
    }
    let value = if negative {
        (magnitude as i64).wrapping_neg()
    } else {
        magnitude as i64
    };
    Ok(Rounded {
        value,
        exceptions: Flags::INEXACT.when(inexact),
        rounded_up: up,
        tiny: false,
    })
}

#[inline]
fn to_integer<T: Format>(
    x: T,
    rounding: Rounding,
    bits: u32,
) -> Result<Rounded<i64>, InvalidConversion> {
    if x.is_normal() {
        let (negative, exponent, significand) = x.normal();
        return finite_to_integer(negative, exponent, significand, rounding, bits);
    }
    // The slow path returns its answer in one word. Bits 0 and 1 select Ok,
    // NaN, positive overflow or negative overflow. For Ok, bit 2 is inexact
    // and bit 3 is rounded up. The top half holds the value, which is -1, 0
    // or 1.
    let packed = to_integer_slow(x, rounding, bits);
    match packed & 3 {
        0 => Ok(Rounded {
            value: packed as i64 >> 32,
            exceptions: Flags::INEXACT.when(packed & 4 != 0),
            rounded_up: packed & 8 != 0,
            tiny: false,
        }),
        1 => Err(InvalidConversion::Nan),
        2 => Err(InvalidConversion::PositiveOverflow),
        _ => Err(InvalidConversion::NegativeOverflow),
    }
}

// Converts a zero, a denormal, an infinity or a NaN. It also takes any
// noncanonical 80-bit encoding, whose result is unspecified.
#[cold]
#[inline(never)]
fn to_integer_slow<T: Format>(x: T, rounding: Rounding, bits: u32) -> u64 {
    let decoded = x.decode();
    match decoded.class {
        Class::Nan => 1,
        Class::Infinity => 2 + u64::from(decoded.negative),
        Class::Zero => 0,
        Class::Finite => match finite_to_integer(
            decoded.negative,
            decoded.exponent,
            decoded.significand,
            rounding,
            bits,
        ) {
            Ok(rounded) => {
                (rounded.value as u64) << 32
                    | u64::from(rounded.exceptions.contains(Flags::INEXACT)) << 2
                    | u64::from(rounded.rounded_up) << 3
            }
            Err(InvalidConversion::PositiveOverflow) => 2,
            Err(_) => 3,
        },
    }
}

// Conversions from integers (doc/conversions.md#conversion-from-a-signed-integer).

fn binary_from_i64<T: Format>(value: i64) -> Computed<T> {
    if value == 0 {
        return Computed::Finished(T::zero(false), Flags::NONE);
    }
    let magnitude = value.unsigned_abs();
    let shift = magnitude.leading_zeros();
    unfinished(value < 0, 63 - shift as i32, magnitude << shift, 0)
}

// Conversions between formats (doc/conversions.md#conversion-between-formats).

// Widens a value. The conversion is exact for every finite value and for
// infinity.
fn widen<S: Format, T: Format, N: NanPolicy<S> + NanPolicy<T>>(x: S) -> (T, Flags) {
    if x.is_normal() {
        let (negative, exponent, significand) = x.normal();
        return (T::encode(negative, exponent, significand), Flags::NONE);
    }
    widen_slow::<S, T, N>(x)
}

#[cold]
#[inline(never)]
fn widen_slow<S: Format, T: Format, N: NanPolicy<S> + NanPolicy<T>>(x: S) -> (T, Flags) {
    let decoded = x.decode();
    match decoded.class {
        Class::Nan => <N as NanPolicy<T>>::import(<N as NanPolicy<S>>::export(x)),
        Class::Zero => (T::zero(decoded.negative), Flags::NONE),
        Class::Infinity => (T::infinity(decoded.negative), Flags::NONE),
        // A denormal of the source is a normal number of the wider format.
        Class::Finite => (
            T::encode(decoded.negative, decoded.exponent, decoded.significand),
            Flags::NONE,
        ),
    }
}

// For a finite, nonzero input, returns an exact intermediate for the caller
// to round in the destination format. For zero, infinity or NaN, returns a
// finished result.
fn narrow<S: Format, T: Format, N: NanPolicy<S> + NanPolicy<T>>(x: S) -> Computed<T> {
    if x.is_normal() {
        let (negative, exponent, significand) = x.normal();
        return unfinished(negative, exponent, significand, 0);
    }
    narrow_slow::<S, T, N>(x).into_computed()
}

#[cold]
#[inline(never)]
fn narrow_slow<S: Format, T: Format, N: NanPolicy<S> + NanPolicy<T>>(x: S) -> Return {
    let decoded = x.decode();
    match decoded.class {
        Class::Nan => {
            let (value, flags) = <N as NanPolicy<T>>::import(<N as NanPolicy<S>>::export(x));
            Return::finished(value, flags)
        }
        Class::Zero => Return::finished(T::zero(decoded.negative), Flags::NONE),
        Class::Infinity => Return::finished(T::infinity(decoded.negative), Flags::NONE),
        // A denormal source is normalized so that the range responses see
        // its true exponent.
        Class::Finite => {
            Return::unfinished(decoded.negative, decoded.exponent, decoded.significand, 0)
        }
    }
}

// Rounding to an integral value (doc/conversions.md#rounding-to-an-integral-value).

fn round_to_integral<N: NanPolicy<Extended>>(x: Extended, rounding: Rounding) -> Rounded<Extended> {
    let decoded = x.decode();
    match decoded.class {
        Class::Nan => {
            let (value, flags) = N::quiet(x);
            Rounded::exact(value, flags)
        }
        Class::Zero | Class::Infinity => Rounded::exact(x, Flags::NONE),
        // At 2^63 or more every value is an integer.
        Class::Finite if decoded.exponent >= 63 => Rounded::exact(x, Flags::NONE),
        Class::Finite => {
            let (magnitude, inexact, up) = integral(
                decoded.significand,
                decoded.exponent,
                rounding,
                decoded.negative,
            );
            let value = if magnitude == 0 {
                Extended::zero(decoded.negative)
            } else {
                let shift = magnitude.leading_zeros();
                Extended {
                    sign_exponent: u16::from(decoded.negative) << 15
                        | (Extended::BIAS as u32 + 63 - shift) as u16,
                    significand: magnitude << shift,
                }
            };
            Rounded {
                value,
                exceptions: Flags::INEXACT.when(inexact),
                rounded_up: up,
                tiny: false,
            }
        }
    }
}