Skip to main content

core/num/imp/
diy_float.rs

1//! Extended precision "soft float", for internal use only.
2
3// This module is only for dec2flt and flt2dec, and only public because of coretests.
4// It is not intended to ever be stabilized.
5#![doc(hidden)]
6#![unstable(
7    feature = "core_private_diy_float",
8    reason = "internal routines only exposed for testing",
9    issue = "none"
10)]
11
12/// A custom 64-bit floating point type, representing `f * 2^e`.
13#[derive(Copy, Clone, Debug)]
14#[doc(hidden)]
15#[ferrocene::prevalidated]
16pub struct Fp {
17    /// The integer mantissa.
18    pub f: u64,
19    /// The exponent in base 2.
20    pub e: i16,
21}
22
23impl Fp {
24    /// Returns a correctly rounded product of itself and `other`.
25    #[ferrocene::prevalidated]
26    pub fn mul(self, other: Self) -> Self {
27        let (lo, hi) = self.f.carrying_mul(other.f, 0);
28        let f = hi + (lo >> 63) /* round */;
29        let e = self.e + other.e + 64;
30        Self { f, e }
31    }
32
33    /// Normalizes itself so that the resulting mantissa is at least `2^63`.
34    #[ferrocene::prevalidated]
35    pub fn normalize(self) -> Self {
36        let lz = self.f.leading_zeros();
37        let f = self.f << lz;
38        let e = self.e - lz as i16;
39        debug_assert!(f >= (1 << 63));
40        Self { f, e }
41    }
42
43    /// Normalizes itself to have the shared exponent.
44    /// It can only decrease the exponent (and thus increase the mantissa).
45    #[ferrocene::prevalidated]
46    pub fn normalize_to(self, e: i16) -> Self {
47        let edelta = self.e - e;
48        assert!(edelta >= 0);
49        let edelta = edelta as usize;
50        assert_eq!(self.f << edelta >> edelta, self.f);
51        Self { f: self.f << edelta, e }
52    }
53}