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(#[automatically_derived]
impl crate::marker::Copy for Decoded { }Copy, #[automatically_derived]
impl crate::clone::Clone for Decoded {
    #[inline]
    fn clone(&self) -> Decoded {
        let _: crate::clone::AssertParamIsClone<u64>;
        let _: crate::clone::AssertParamIsClone<i16>;
        let _: crate::clone::AssertParamIsClone<bool>;
        *self
    }
}Clone, #[automatically_derived]
impl crate::fmt::Debug for Decoded {
    #[inline]
    fn fmt(&self, f: &mut crate::fmt::Formatter) -> crate::fmt::Result {
        crate::fmt::Formatter::debug_struct_field5_finish(f, "Decoded",
            "mant", &self.mant, "minus", &self.minus, "plus", &self.plus,
            "exp", &self.exp, "inclusive", &&self.inclusive)
    }
}Debug, #[automatically_derived]
impl crate::cmp::PartialEq for Decoded {
    #[inline]
    fn eq(&self, other: &Decoded) -> bool {
        self.mant == other.mant && self.minus == other.minus &&
                    self.plus == other.plus && self.exp == other.exp &&
            self.inclusive == other.inclusive
    }
}PartialEq, #[automatically_derived]
impl crate::cmp::Eq for Decoded {
    #[inline]
    #[doc(hidden)]
    #[coverage(off)]
    fn assert_fields_are_eq(&self) {
        let _: crate::cmp::AssertParamIsEq<u64>;
        let _: crate::cmp::AssertParamIsEq<i16>;
        let _: crate::cmp::AssertParamIsEq<bool>;
    }
}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(#[automatically_derived]
impl crate::marker::Copy for FullDecoded { }Copy, #[automatically_derived]
impl crate::clone::Clone for FullDecoded {
    #[inline]
    fn clone(&self) -> FullDecoded {
        let _: crate::clone::AssertParamIsClone<Decoded>;
        *self
    }
}Clone, #[automatically_derived]
impl crate::fmt::Debug for FullDecoded {
    #[inline]
    fn fmt(&self, f: &mut crate::fmt::Formatter) -> crate::fmt::Result {
        match self {
            FullDecoded::Nan => crate::fmt::Formatter::write_str(f, "Nan"),
            FullDecoded::Infinite =>
                crate::fmt::Formatter::write_str(f, "Infinite"),
            FullDecoded::Zero => crate::fmt::Formatter::write_str(f, "Zero"),
            FullDecoded::Finite(__self_0) =>
                crate::fmt::Formatter::debug_tuple_field1_finish(f, "Finite",
                    &__self_0),
        }
    }
}Debug, #[automatically_derived]
impl crate::cmp::PartialEq for FullDecoded {
    #[inline]
    fn eq(&self, other: &FullDecoded) -> bool {
        let __self_discr = crate::intrinsics::discriminant_value(self);
        let __arg1_discr = crate::intrinsics::discriminant_value(other);
        __self_discr == __arg1_discr &&
            match (self, other) {
                (FullDecoded::Finite(__self_0), FullDecoded::Finite(__arg1_0))
                    => __self_0 == __arg1_0,
                _ => true,
            }
    }
}PartialEq, #[automatically_derived]
impl crate::cmp::Eq for FullDecoded {
    #[inline]
    #[doc(hidden)]
    #[coverage(off)]
    fn assert_fields_are_eq(&self) {
        let _: crate::cmp::AssertParamIsEq<Decoded>;
    }
}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: FloatExt + 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}