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
48#[cfg(target_has_reliable_f16)]
49impl DecodableFloat for f16 {
50    fn min_pos_norm_value() -> Self {
51        f16::MIN_POSITIVE
52    }
53}
54
55impl DecodableFloat for f32 {
56    fn min_pos_norm_value() -> Self {
57        f32::MIN_POSITIVE
58    }
59}
60
61impl DecodableFloat for f64 {
62    fn min_pos_norm_value() -> Self {
63        f64::MIN_POSITIVE
64    }
65}
66
67/// Returns a sign (true when negative) and `FullDecoded` value
68/// from given floating point number.
69pub fn decode<T: DecodableFloat>(v: T) -> (/*negative?*/ bool, FullDecoded) {
70    let (mant, exp, sign) = v.integer_decode();
71    let even = (mant & 1) == 0;
72    let decoded = match v.classify() {
73        FpCategory::Nan => FullDecoded::Nan,
74        FpCategory::Infinite => FullDecoded::Infinite,
75        FpCategory::Zero => FullDecoded::Zero,
76        FpCategory::Subnormal => {
77            // neighbors: (mant - 2, exp) -- (mant, exp) -- (mant + 2, exp)
78            // Float::integer_decode always preserves the exponent,
79            // so the mantissa is scaled for subnormals.
80            FullDecoded::Finite(Decoded { mant, minus: 1, plus: 1, exp, inclusive: even })
81        }
82        FpCategory::Normal => {
83            let minnorm = <T as DecodableFloat>::min_pos_norm_value().integer_decode();
84            if mant == minnorm.0 {
85                // neighbors: (maxmant, exp - 1) -- (minnormmant, exp) -- (minnormmant + 1, exp)
86                // where maxmant = minnormmant * 2 - 1
87                FullDecoded::Finite(Decoded {
88                    mant: mant << 2,
89                    minus: 1,
90                    plus: 2,
91                    exp: exp - 2,
92                    inclusive: even,
93                })
94            } else {
95                // neighbors: (mant - 1, exp) -- (mant, exp) -- (mant + 1, exp)
96                FullDecoded::Finite(Decoded {
97                    mant: mant << 1,
98                    minus: 1,
99                    plus: 1,
100                    exp: exp - 1,
101                    inclusive: even,
102                })
103            }
104        }
105    };
106    (sign < 0, decoded)
107}