core/num/flt2dec/
decoder.rs

1//! Decodes a floating-point value into individual parts and error ranges.
2
3use crate::num::FpCategory;
4use crate::num::dec2flt::float::RawFloat;
5
6/// Decoded unsigned finite value, such that:
7///
8/// - The original value equals to `mant * 2^exp`.
9///
10/// - Any number from `(mant - minus) * 2^exp` to `(mant + plus) * 2^exp` will
11///   round to the original value. The range is inclusive only when
12///   `inclusive` is `true`.
13#[derive(Copy, Clone, Debug, PartialEq, Eq)]
14pub struct Decoded {
15    /// The scaled mantissa.
16    pub mant: u64,
17    /// The lower error range.
18    pub minus: u64,
19    /// The upper error range.
20    pub plus: u64,
21    /// The shared exponent in base 2.
22    pub exp: i16,
23    /// True when the error range is inclusive.
24    ///
25    /// In IEEE 754, this is true when the original mantissa was even.
26    pub inclusive: bool,
27}
28
29/// Decoded unsigned value.
30#[derive(Copy, Clone, Debug, PartialEq, Eq)]
31pub enum FullDecoded {
32    /// Not-a-number.
33    Nan,
34    /// Infinities, either positive or negative.
35    Infinite,
36    /// Zero, either positive or negative.
37    Zero,
38    /// Finite numbers with further decoded fields.
39    Finite(Decoded),
40}
41
42/// A floating point type which can be `decode`d.
43pub trait DecodableFloat: RawFloat + Copy {
44    /// The minimum positive normalized value.
45    fn min_pos_norm_value() -> Self;
46}
47
48impl DecodableFloat for f32 {
49    fn min_pos_norm_value() -> Self {
50        f32::MIN_POSITIVE
51    }
52}
53
54impl DecodableFloat for f64 {
55    fn min_pos_norm_value() -> Self {
56        f64::MIN_POSITIVE
57    }
58}
59
60/// Returns a sign (true when negative) and `FullDecoded` value
61/// from given floating point number.
62pub fn decode<T: DecodableFloat>(v: T) -> (/*negative?*/ bool, FullDecoded) {
63    let (mant, exp, sign) = v.integer_decode();
64    let even = (mant & 1) == 0;
65    let decoded = match v.classify() {
66        FpCategory::Nan => FullDecoded::Nan,
67        FpCategory::Infinite => FullDecoded::Infinite,
68        FpCategory::Zero => FullDecoded::Zero,
69        FpCategory::Subnormal => {
70            // neighbors: (mant - 2, exp) -- (mant, exp) -- (mant + 2, exp)
71            // Float::integer_decode always preserves the exponent,
72            // so the mantissa is scaled for subnormals.
73            FullDecoded::Finite(Decoded { mant, minus: 1, plus: 1, exp, inclusive: even })
74        }
75        FpCategory::Normal => {
76            let minnorm = <T as DecodableFloat>::min_pos_norm_value().integer_decode();
77            if mant == minnorm.0 {
78                // neighbors: (maxmant, exp - 1) -- (minnormmant, exp) -- (minnormmant + 1, exp)
79                // where maxmant = minnormmant * 2 - 1
80                FullDecoded::Finite(Decoded {
81                    mant: mant << 2,
82                    minus: 1,
83                    plus: 2,
84                    exp: exp - 2,
85                    inclusive: even,
86                })
87            } else {
88                // neighbors: (mant - 1, exp) -- (mant, exp) -- (mant + 1, exp)
89                FullDecoded::Finite(Decoded {
90                    mant: mant << 1,
91                    minus: 1,
92                    plus: 1,
93                    exp: exp - 1,
94                    inclusive: even,
95                })
96            }
97        }
98    };
99    (sign < 0, decoded)
100}