Skip to main content

core/num/imp/
traits.rs

1//! Numeric traits used for internal implementations.
2
3#![doc(hidden)]
4#![unstable(
5    feature = "num_internals",
6    reason = "internal routines only exposed for testing",
7    issue = "none"
8)]
9
10use crate::num::FpCategory;
11use crate::{f64, fmt, ops};
12
13/// Lossy `as` casting between two types.
14pub trait CastInto<T: Copy>: Copy {
15    fn cast(self) -> T;
16}
17
18/// Collection of traits that allow us to be generic over integer size.
19pub trait Int:
20    Sized
21    + Clone
22    + Copy
23    + fmt::Debug
24    + ops::Shr<u32, Output = Self>
25    + ops::Shl<u32, Output = Self>
26    + ops::BitAnd<Output = Self>
27    + ops::BitOr<Output = Self>
28    + PartialEq
29    + CastInto<i16>
30{
31    const ZERO: Self;
32    const ONE: Self;
33}
34
35macro_rules! int {
36    ($($ty:ty),+) => {
37        $(
38            impl CastInto<i16> for $ty {
39                #[ferrocene::prevalidated]
40                fn cast(self) -> i16 {
41                    self as i16
42                }
43            }
44
45            impl Int for $ty {
46                const ZERO: Self = 0;
47                const ONE: Self = 1;
48            }
49        )+
50    }
51}
52
53int!(u16, u32, u64);
54
55/// A helper trait to avoid duplicating basically all the conversion code for IEEE floats.
56#[doc(hidden)]
57pub trait Float:
58    Sized
59    + ops::Div<Output = Self>
60    + ops::Neg<Output = Self>
61    + ops::Mul<Output = Self>
62    + ops::Add<Output = Self>
63    + fmt::Debug
64    + PartialEq
65    + PartialOrd
66    + Default
67    + Clone
68    + Copy
69{
70    /// The unsigned integer with the same size as the float
71    type Int: Int + Into<u64>;
72
73    /* general constants */
74
75    const INFINITY: Self;
76    const NEG_INFINITY: Self;
77    const NAN: Self;
78    const NEG_NAN: Self;
79
80    /// Bit width of the float
81    const BITS: u32;
82
83    /// The number of bits in the significand, *including* the hidden bit.
84    const SIG_TOTAL_BITS: u32;
85
86    const EXP_MASK: Self::Int;
87    const SIG_MASK: Self::Int;
88
89    /// The number of bits in the significand, *excluding* the hidden bit.
90    const SIG_BITS: u32 = Self::SIG_TOTAL_BITS - 1;
91
92    /// Number of bits in the exponent.
93    const EXP_BITS: u32 = Self::BITS - Self::SIG_BITS - 1;
94
95    /// The saturated (maximum bitpattern) value of the exponent, i.e. the infinite
96    /// representation.
97    ///
98    /// This shifted fully right, use `EXP_MASK` for the shifted value.
99    const EXP_SAT: u32 = (1 << Self::EXP_BITS) - 1;
100
101    /// Signed version of `EXP_SAT` since we convert a lot.
102    const INFINITE_POWER: i32 = Self::EXP_SAT as i32;
103
104    /// The exponent bias value. This is also the maximum value of the exponent.
105    const EXP_BIAS: u32 = Self::EXP_SAT >> 1;
106
107    /// Minimum exponent value of normal values.
108    const EXP_MIN: i32 = -(Self::EXP_BIAS as i32 - 1);
109
110    /// Round-to-even only happens for negative values of q
111    /// when q ≥ −4 in the 64-bit case and when q ≥ −17 in
112    /// the 32-bit case.
113    ///
114    /// When q ≥ 0,we have that 5^q ≤ 2m+1. In the 64-bit case,we
115    /// have 5^q ≤ 2m+1 ≤ 2^54 or q ≤ 23. In the 32-bit case,we have
116    /// 5^q ≤ 2m+1 ≤ 2^25 or q ≤ 10.
117    ///
118    /// When q < 0, we have w ≥ (2m+1)×5^−q. We must have that w < 2^64
119    /// so (2m+1)×5^−q < 2^64. We have that 2m+1 > 2^53 (64-bit case)
120    /// or 2m+1 > 2^24 (32-bit case). Hence,we must have 2^53×5^−q < 2^64
121    /// (64-bit) and 2^24×5^−q < 2^64 (32-bit). Hence we have 5^−q < 2^11
122    /// or q ≥ −4 (64-bit case) and 5^−q < 2^40 or q ≥ −17 (32-bit case).
123    ///
124    /// Thus we have that we only need to round ties to even when
125    /// we have that q ∈ [−4,23](in the 64-bit case) or q∈[−17,10]
126    /// (in the 32-bit case). In both cases,the power of five(5^|q|)
127    /// fits in a 64-bit word.
128    const MIN_EXPONENT_ROUND_TO_EVEN: i32;
129    const MAX_EXPONENT_ROUND_TO_EVEN: i32;
130
131    /// Largest decimal exponent for a non-infinite value.
132    ///
133    /// This is the max exponent in binary converted to the max exponent in decimal. Allows fast
134    /// pathing anything larger than `10^LARGEST_POWER_OF_TEN`, which will round to infinity.
135    const LARGEST_POWER_OF_TEN: i32 = {
136        let largest_pow2 = Self::EXP_BIAS + 1;
137        pow2_to_pow10(largest_pow2 as i64) as i32
138    };
139
140    /// Smallest decimal exponent for a non-zero value. This allows for fast pathing anything
141    /// smaller than `10^SMALLEST_POWER_OF_TEN`, which will round to zero.
142    ///
143    /// The smallest power of ten is represented by `⌊log10(2^-n / (2^64 - 1))⌋`, where `n` is
144    /// the smallest power of two. The `2^64 - 1)` denominator comes from the number of values
145    /// that are representable by the intermediate storage format. I don't actually know _why_
146    /// the storage format is relevant here.
147    ///
148    /// The values may be calculated using the formula. Unfortunately we cannot calculate them at
149    /// compile time since intermediates exceed the range of an `f64`.
150    const SMALLEST_POWER_OF_TEN: i32;
151
152    /// Returns the category that this number falls into.
153    fn classify(self) -> FpCategory;
154
155    /// Transmute to the integer representation
156    fn to_bits(self) -> Self::Int;
157}
158
159/// Items that ideally would be on `Float`, but don't apply to all float types because they
160/// rely on the mantissa fitting into a `u64` (which isn't true for `f128`).
161#[doc(hidden)]
162pub trait FloatExt: Float {
163    /// Performs a raw transmutation from an integer.
164    fn from_u64_bits(v: u64) -> Self;
165
166    /// Returns the mantissa, exponent and sign as integers.
167    ///
168    /// This returns `(m, p, s)` such that `s * m * 2^p` represents the original float. For 0, the
169    /// exponent will be `-(EXP_BIAS + SIG_BITS)`, which is the minimum subnormal power. For
170    /// infinity or NaN, the exponent will be `EXP_SAT - EXP_BIAS - SIG_BITS`.
171    ///
172    /// If subnormal, the mantissa will be shifted one bit to the left. Otherwise, it is returned
173    /// with the explicit bit set but otherwise unshifted
174    ///
175    /// `s` is only ever +/-1.
176    #[ferrocene::prevalidated]
177    fn integer_decode(self) -> (u64, i16, i8) {
178        let bits = self.to_bits();
179        let sign: i8 = if bits >> (Self::BITS - 1) == Self::Int::ZERO { 1 } else { -1 };
180        let mut exponent: i16 = ((bits & Self::EXP_MASK) >> Self::SIG_BITS).cast();
181        let mantissa = if exponent == 0 {
182            (bits & Self::SIG_MASK) << 1
183        } else {
184            (bits & Self::SIG_MASK) | (Self::Int::ONE << Self::SIG_BITS)
185        };
186        // Exponent bias + mantissa shift
187        exponent -= (Self::EXP_BIAS + Self::SIG_BITS) as i16;
188        (mantissa.into(), exponent, sign)
189    }
190}
191
192/// Solve for `b` in `10^b = 2^a`
193#[ferrocene::annotation("This function is only being used in constants and cannot be covered")]
194#[ferrocene::prevalidated]
195const fn pow2_to_pow10(a: i64) -> i64 {
196    let res = (a as f64) / f64::consts::LOG2_10;
197    res as i64
198}
199
200#[cfg(target_has_reliable_f16)]
201impl Float for f16 {
202    type Int = u16;
203
204    const INFINITY: Self = Self::INFINITY;
205    const NEG_INFINITY: Self = Self::NEG_INFINITY;
206    const NAN: Self = Self::NAN;
207    const NEG_NAN: Self = -Self::NAN;
208
209    const BITS: u32 = 16;
210    const SIG_TOTAL_BITS: u32 = Self::MANTISSA_DIGITS;
211    const EXP_MASK: Self::Int = Self::EXPONENT_MASK;
212    const SIG_MASK: Self::Int = Self::MANTISSA_MASK;
213
214    const MIN_EXPONENT_ROUND_TO_EVEN: i32 = -22;
215    const MAX_EXPONENT_ROUND_TO_EVEN: i32 = 5;
216    const SMALLEST_POWER_OF_TEN: i32 = -27;
217
218    #[ferrocene::prevalidated]
219    fn to_bits(self) -> Self::Int {
220        self.to_bits()
221    }
222
223    #[ferrocene::prevalidated]
224    fn classify(self) -> FpCategory {
225        self.classify()
226    }
227}
228
229#[cfg(target_has_reliable_f16)]
230impl FloatExt for f16 {
231    #[inline]
232    fn from_u64_bits(v: u64) -> Self {
233        Self::from_bits((v & 0xFFFF) as u16)
234    }
235}
236
237impl Float for f32 {
238    type Int = u32;
239
240    const INFINITY: Self = f32::INFINITY;
241    const NEG_INFINITY: Self = f32::NEG_INFINITY;
242    const NAN: Self = f32::NAN;
243    const NEG_NAN: Self = -f32::NAN;
244
245    const BITS: u32 = 32;
246    const SIG_TOTAL_BITS: u32 = Self::MANTISSA_DIGITS;
247    const EXP_MASK: Self::Int = Self::EXPONENT_MASK;
248    const SIG_MASK: Self::Int = Self::MANTISSA_MASK;
249
250    const MIN_EXPONENT_ROUND_TO_EVEN: i32 = -17;
251    const MAX_EXPONENT_ROUND_TO_EVEN: i32 = 10;
252    const SMALLEST_POWER_OF_TEN: i32 = -65;
253
254    #[ferrocene::prevalidated]
255    fn to_bits(self) -> Self::Int {
256        self.to_bits()
257    }
258
259    #[ferrocene::prevalidated]
260    fn classify(self) -> FpCategory {
261        self.classify()
262    }
263}
264
265impl FloatExt for f32 {
266    #[inline]
267    fn from_u64_bits(v: u64) -> Self {
268        f32::from_bits((v & 0xFFFFFFFF) as u32)
269    }
270}
271
272impl Float for f64 {
273    type Int = u64;
274
275    const INFINITY: Self = Self::INFINITY;
276    const NEG_INFINITY: Self = Self::NEG_INFINITY;
277    const NAN: Self = Self::NAN;
278    const NEG_NAN: Self = -Self::NAN;
279
280    const BITS: u32 = 64;
281    const SIG_TOTAL_BITS: u32 = Self::MANTISSA_DIGITS;
282    const EXP_MASK: Self::Int = Self::EXPONENT_MASK;
283    const SIG_MASK: Self::Int = Self::MANTISSA_MASK;
284
285    const MIN_EXPONENT_ROUND_TO_EVEN: i32 = -4;
286    const MAX_EXPONENT_ROUND_TO_EVEN: i32 = 23;
287    const SMALLEST_POWER_OF_TEN: i32 = -342;
288
289    #[ferrocene::prevalidated]
290    fn to_bits(self) -> Self::Int {
291        self.to_bits()
292    }
293
294    #[ferrocene::prevalidated]
295    fn classify(self) -> FpCategory {
296        self.classify()
297    }
298}
299
300impl FloatExt for f64 {
301    #[inline]
302    fn from_u64_bits(v: u64) -> Self {
303        f64::from_bits(v)
304    }
305}