Skip to main content

rustorb_cdr/
long_double.rs

1//! `long double`: the IEEE 754 binary128 (quadruple precision) format that
2//! CDR sends in 16 octets (CORBA 3.4 part 2, 9.3.1.2).
3
4use std::fmt;
5
6/// A `long double` value, kept as its IEEE 754 binary128 bits: the sign
7/// in the top bit, a 15-bit exponent biased by 16383 and a 112-bit
8/// fraction.
9///
10/// Rust has no 128-bit float, so arithmetic is left to the caller: the
11/// value converts exactly from `f64` ([`LongDouble::from_f64`]) and
12/// rounds to the nearest `f64` ([`LongDouble::to_f64`]). The bits travel
13/// as they are, so a value received and sent again keeps its precision.
14#[derive(Clone, Copy, PartialEq, Eq, Hash, Default)]
15pub struct LongDouble(u128);
16
17const FRAC_BITS: u32 = 112;
18const EXP_MAX: u128 = 0x7fff;
19const BIAS: i32 = 16383;
20const FRAC_MASK: u128 = (1 << FRAC_BITS) - 1;
21const SIGN: u128 = 1 << 127;
22
23impl LongDouble {
24    /// Zero.
25    pub const ZERO: LongDouble = LongDouble(0);
26
27    /// The value with these binary128 bits.
28    pub const fn from_bits(bits: u128) -> LongDouble {
29        LongDouble(bits)
30    }
31
32    /// The binary128 bits.
33    pub const fn to_bits(self) -> u128 {
34        self.0
35    }
36
37    /// The value of `v`, exactly (binary128 holds every `f64`).
38    pub const fn from_f64(v: f64) -> LongDouble {
39        let bits = v.to_bits();
40        let sign = ((bits >> 63) as u128) << 127;
41        let exp = ((bits >> 52) & 0x7ff) as i32;
42        let frac = (bits & ((1 << 52) - 1)) as u128;
43        LongDouble(
44            sign | match exp {
45                0x7ff => (EXP_MAX << FRAC_BITS) | (frac << (FRAC_BITS - 52)),
46                0 if frac == 0 => 0,
47                // A subnormal double is a normal binary128: move the
48                // leading one into the implicit bit.
49                0 => {
50                    let top = 127 - frac.leading_zeros(); // frac * 2^-1074
51                    let e = top as i32 - 1074 + BIAS;
52                    ((e as u128) << FRAC_BITS) | ((frac << (FRAC_BITS - top)) & FRAC_MASK)
53                }
54                _ => (((exp - 1023 + BIAS) as u128) << FRAC_BITS) | (frac << (FRAC_BITS - 52)),
55            },
56        )
57    }
58
59    /// The nearest `f64` (ties to even); out of range values become
60    /// infinities or zeros, a NaN stays a NaN.
61    pub fn to_f64(self) -> f64 {
62        let sign = ((self.0 >> 127) as u64) << 63;
63        let exp = ((self.0 >> FRAC_BITS) & EXP_MAX) as i32;
64        let frac = self.0 & FRAC_MASK;
65        if exp == EXP_MAX as i32 {
66            return f64::from_bits(if frac == 0 {
67                sign | 0x7ff0_0000_0000_0000
68            } else {
69                sign | 0x7ff8_0000_0000_0000 | (frac >> (FRAC_BITS - 52)) as u64
70            });
71        }
72        if exp == 0 && frac == 0 {
73            return f64::from_bits(sign);
74        }
75        // The value is m * 2^(e - 112), m with its implicit bit.
76        let (m, e) = if exp == 0 {
77            (frac, 1 - BIAS)
78        } else {
79            (frac | (1 << FRAC_BITS), exp - BIAS)
80        };
81        let bits = if e >= -1022 {
82            // Normal: keep 53 bits; rounding may carry into the exponent,
83            // which the addition below takes care of.
84            let r = round_shift(m, FRAC_BITS - 52);
85            let biased = (e + 1023) as u64;
86            if r >> 53 != 0 {
87                if biased + 1 >= 0x7ff {
88                    0x7ff0_0000_0000_0000
89                } else {
90                    ((biased + 1) << 52) | ((r >> 1) as u64 & ((1 << 52) - 1))
91                }
92            } else if biased >= 0x7ff {
93                0x7ff0_0000_0000_0000
94            } else {
95                (biased << 52) | (r as u64 & ((1 << 52) - 1))
96            }
97        } else {
98            // Subnormal (or zero): a mantissa of 2^52 is the smallest
99            // normal, which the bits express as they are.
100            let shift = (FRAC_BITS - 52) as i32 + (-1022 - e);
101            round_shift(m, shift.min(127) as u32) as u64
102        };
103        f64::from_bits(sign | bits)
104    }
105
106    /// Whether the value is a NaN.
107    pub fn is_nan(self) -> bool {
108        (self.0 >> FRAC_BITS) & EXP_MAX == EXP_MAX && self.0 & FRAC_MASK != 0
109    }
110
111    /// Whether the sign bit is set (also for -0 and NaNs).
112    pub fn is_sign_negative(self) -> bool {
113        self.0 & SIGN != 0
114    }
115
116    /// The bytes in big endian order, as CDR sends them in a big endian
117    /// stream.
118    pub fn to_be_bytes(self) -> [u8; 16] {
119        self.0.to_be_bytes()
120    }
121
122    /// The value of these big endian bytes.
123    pub fn from_be_bytes(bytes: [u8; 16]) -> LongDouble {
124        LongDouble(u128::from_be_bytes(bytes))
125    }
126}
127
128/// `m >> shift`, rounded to nearest, ties to even.
129fn round_shift(m: u128, shift: u32) -> u128 {
130    if shift == 0 {
131        return m;
132    }
133    let q = m >> shift;
134    let rest = m & ((1 << shift) - 1);
135    let half = 1 << (shift - 1);
136    if rest > half || (rest == half && q & 1 == 1) {
137        q + 1
138    } else {
139        q
140    }
141}
142
143impl From<f64> for LongDouble {
144    fn from(v: f64) -> LongDouble {
145        LongDouble::from_f64(v)
146    }
147}
148
149impl From<f32> for LongDouble {
150    fn from(v: f32) -> LongDouble {
151        LongDouble::from_f64(f64::from(v))
152    }
153}
154
155impl From<LongDouble> for f64 {
156    fn from(v: LongDouble) -> f64 {
157        v.to_f64()
158    }
159}
160
161impl fmt::Debug for LongDouble {
162    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
163        write!(f, "LongDouble({:?} / {:#034x})", self.to_f64(), self.0)
164    }
165}
166
167/// Shows the nearest `f64`.
168impl fmt::Display for LongDouble {
169    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
170        fmt::Display::fmt(&self.to_f64(), f)
171    }
172}
173
174#[cfg(test)]
175mod tests {
176    use super::*;
177
178    fn round_trip(v: f64) {
179        let ld = LongDouble::from_f64(v);
180        assert_eq!(ld.to_f64().to_bits(), v.to_bits(), "{v:e}");
181    }
182
183    #[test]
184    fn known_bits() {
185        assert_eq!(LongDouble::from_f64(1.0).to_bits(), 0x3fff << 112);
186        assert_eq!(LongDouble::from_f64(-2.0).to_bits(), SIGN | (0x4000 << 112));
187        assert_eq!(
188            LongDouble::from_f64(1.5).to_bits(),
189            (0x3fff << 112) | (1 << 111)
190        );
191        assert_eq!(LongDouble::from_f64(f64::INFINITY).to_bits(), 0x7fff << 112);
192        assert_eq!(LongDouble::from_f64(-0.0).to_bits(), SIGN);
193        // The smallest subnormal double, 2^-1074.
194        assert_eq!(
195            LongDouble::from_f64(f64::from_bits(1)).to_bits(),
196            ((16383 - 1074) as u128) << 112
197        );
198    }
199
200    #[test]
201    fn doubles_round_trip() {
202        for v in [
203            0.0,
204            -0.0,
205            1.0,
206            -1.0,
207            0.1,
208            std::f64::consts::PI,
209            f64::MAX,
210            f64::MIN_POSITIVE,
211            f64::from_bits(1),
212            f64::from_bits(0x000f_ffff_ffff_ffff),
213            f64::from_bits(0x0008_0000_0000_0001),
214            f64::INFINITY,
215            f64::NEG_INFINITY,
216            1e300,
217            -1e-310,
218        ] {
219            round_trip(v);
220        }
221        assert!(LongDouble::from_f64(f64::NAN).is_nan());
222        assert!(LongDouble::from_f64(f64::NAN).to_f64().is_nan());
223    }
224
225    #[test]
226    fn rounding() {
227        let one = 0x3fffu128 << 112;
228        // 1 + 2^-53 is half way between 1 and the next double: ties to even.
229        assert_eq!(LongDouble::from_bits(one | (1 << 59)).to_f64(), 1.0);
230        // Just above half way rounds up.
231        assert_eq!(
232            LongDouble::from_bits(one | (1 << 59) | 1).to_f64(),
233            1.0 + f64::EPSILON
234        );
235        // 1 + 3 * 2^-53 is half way to an even mantissa above.
236        assert_eq!(
237            LongDouble::from_bits(one | (3 << 59)).to_f64(),
238            1.0 + 2.0 * f64::EPSILON
239        );
240        // Every fraction bit set rounds up to 2.
241        assert_eq!(LongDouble::from_bits(one | FRAC_MASK).to_f64(), 2.0);
242        // Past the largest double: infinity.
243        assert_eq!(LongDouble::from_bits(0x43ff << 112).to_f64(), f64::INFINITY);
244        assert_eq!(
245            LongDouble::from_bits((0x43fe << 112) | FRAC_MASK).to_f64(),
246            f64::INFINITY
247        );
248        // Below the smallest subnormal double: zero, keeping the sign.
249        let tiny = LongDouble::from_bits(SIGN | (1 << 112));
250        assert_eq!(tiny.to_f64().to_bits(), (-0.0f64).to_bits());
251        // 2^-1075 is half of the smallest subnormal: ties to even, 0.
252        let half = LongDouble::from_bits(((16383 - 1075) as u128) << 112);
253        assert_eq!(half.to_f64(), 0.0);
254        // A little more rounds up to it.
255        let more = LongDouble::from_bits((((16383 - 1075) as u128) << 112) | 1);
256        assert_eq!(more.to_f64(), f64::from_bits(1));
257        // The largest subnormal plus a bit rounds to the smallest normal.
258        let edge = LongDouble::from_bits((((16383 - 1023) as u128) << 112) | FRAC_MASK);
259        assert_eq!(edge.to_f64(), f64::MIN_POSITIVE);
260        // A binary128 subnormal is far below every double.
261        assert_eq!(LongDouble::from_bits(1).to_f64(), 0.0);
262    }
263}