Skip to main content

core/num/imp/flt2dec/
decoder.rs

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