Skip to main content

core/fmt/
float.rs

1use crate::fmt::{Debug, Display, Formatter, LowerExp, Result, UpperExp};
2use crate::mem::MaybeUninit;
3use crate::num::imp::{flt2dec, fmt as numfmt};
4
5#[doc(hidden)]
6trait GeneralFormat: PartialOrd {
7    /// Determines if a value should use exponential based on its magnitude, given the precondition
8    /// that it will not be rounded any further before it is displayed.
9    fn already_rounded_value_should_use_exponential(&self) -> bool;
10}
11
12macro_rules! impl_general_format {
13    ($($t:ident)*) => {
14        $(impl GeneralFormat for $t {
15            #[ferrocene::prevalidated]
16            fn already_rounded_value_should_use_exponential(&self) -> bool {
17                // `max_abs` rounds to infinity for `f16`. This is fine to save us from a more
18                // complex macro, it just means a positive-exponent `f16` will never print as
19                // scientific notation by default (reasonably, the max is 65504.0).
20                #[allow(overflowing_literals)]
21                let max_abs = 1e+16;
22
23                let abs = $t::abs(*self);
24                (abs != 0.0 && abs < 1e-4) || abs >= max_abs
25            }
26        })*
27    }
28}
29
30#[cfg(target_has_reliable_f16)]
31impl_general_format! { f16 }
32impl_general_format! { f32 f64 }
33
34// Don't inline this so callers don't use the stack space this function
35// requires unless they have to.
36#[inline(never)]
37#[ferrocene::prevalidated]
38fn float_to_decimal_common_exact<T>(
39    fmt: &mut Formatter<'_>,
40    num: &T,
41    sign: flt2dec::Sign,
42    precision: u16,
43) -> Result
44where
45    T: flt2dec::DecodableFloat,
46{
47    let mut buf: [MaybeUninit<u8>; 1024] = [MaybeUninit::uninit(); 1024]; // enough for f32 and f64
48    let mut parts: [MaybeUninit<numfmt::Part<'_>>; 4] = [MaybeUninit::uninit(); 4];
49    let formatted = flt2dec::to_exact_fixed_str(
50        flt2dec::strategy::grisu::format_exact,
51        *num,
52        sign,
53        precision.into(),
54        &mut buf,
55        &mut parts,
56    );
57    // SAFETY: `to_exact_fixed_str` and `format_exact` produce only ASCII characters.
58    unsafe { fmt.pad_formatted_parts(&formatted) }
59}
60
61// Don't inline this so callers that call both this and the above won't wind
62// up using the combined stack space of both functions in some cases.
63#[inline(never)]
64#[ferrocene::prevalidated]
65fn float_to_decimal_common_shortest<T>(
66    fmt: &mut Formatter<'_>,
67    num: &T,
68    sign: flt2dec::Sign,
69    precision: u16,
70) -> Result
71where
72    T: flt2dec::DecodableFloat,
73{
74    // enough for f32 and f64
75    let mut buf: [MaybeUninit<u8>; flt2dec::MAX_SIG_DIGITS] =
76        [MaybeUninit::uninit(); flt2dec::MAX_SIG_DIGITS];
77    let mut parts: [MaybeUninit<numfmt::Part<'_>>; 4] = [MaybeUninit::uninit(); 4];
78    let formatted = flt2dec::to_shortest_str(
79        flt2dec::strategy::grisu::format_shortest,
80        *num,
81        sign,
82        precision.into(),
83        &mut buf,
84        &mut parts,
85    );
86    // SAFETY: `to_shortest_str` and `format_shortest` produce only ASCII characters.
87    unsafe { fmt.pad_formatted_parts(&formatted) }
88}
89
90#[ferrocene::prevalidated]
91fn float_to_decimal_display<T>(fmt: &mut Formatter<'_>, num: &T) -> Result
92where
93    T: flt2dec::DecodableFloat,
94{
95    let force_sign = fmt.sign_plus();
96    let sign = match force_sign {
97        false => flt2dec::Sign::Minus,
98        true => flt2dec::Sign::MinusPlus,
99    };
100
101    if let Some(precision) = fmt.options.get_precision() {
102        float_to_decimal_common_exact(fmt, num, sign, precision)
103    } else {
104        let min_precision = 0;
105        float_to_decimal_common_shortest(fmt, num, sign, min_precision)
106    }
107}
108
109// Don't inline this so callers don't use the stack space this function
110// requires unless they have to.
111#[inline(never)]
112#[ferrocene::prevalidated]
113fn float_to_exponential_common_exact<T>(
114    fmt: &mut Formatter<'_>,
115    num: &T,
116    sign: flt2dec::Sign,
117    precision: u16,
118    upper: bool,
119) -> Result
120where
121    T: flt2dec::DecodableFloat,
122{
123    let mut buf: [MaybeUninit<u8>; 1024] = [MaybeUninit::uninit(); 1024]; // enough for f32 and f64
124    let mut parts: [MaybeUninit<numfmt::Part<'_>>; 6] = [MaybeUninit::uninit(); 6];
125    let formatted = flt2dec::to_exact_exp_str(
126        flt2dec::strategy::grisu::format_exact,
127        *num,
128        sign,
129        precision.into(),
130        upper,
131        &mut buf,
132        &mut parts,
133    );
134    // SAFETY: `to_exact_exp_str` and `format_exact` produce only ASCII characters.
135    unsafe { fmt.pad_formatted_parts(&formatted) }
136}
137
138// Don't inline this so callers that call both this and the above won't wind
139// up using the combined stack space of both functions in some cases.
140#[inline(never)]
141#[ferrocene::prevalidated]
142fn float_to_exponential_common_shortest<T>(
143    fmt: &mut Formatter<'_>,
144    num: &T,
145    sign: flt2dec::Sign,
146    upper: bool,
147) -> Result
148where
149    T: flt2dec::DecodableFloat,
150{
151    // enough for f32 and f64
152    let mut buf: [MaybeUninit<u8>; flt2dec::MAX_SIG_DIGITS] =
153        [MaybeUninit::uninit(); flt2dec::MAX_SIG_DIGITS];
154    let mut parts: [MaybeUninit<numfmt::Part<'_>>; 6] = [MaybeUninit::uninit(); 6];
155    let formatted = flt2dec::to_shortest_exp_str(
156        flt2dec::strategy::grisu::format_shortest,
157        *num,
158        sign,
159        (0, 0),
160        upper,
161        &mut buf,
162        &mut parts,
163    );
164    // SAFETY: `to_shortest_exp_str` and `format_shortest` produce only ASCII characters.
165    unsafe { fmt.pad_formatted_parts(&formatted) }
166}
167
168// Common code of floating point LowerExp and UpperExp.
169#[ferrocene::prevalidated]
170fn float_to_exponential_common<T>(fmt: &mut Formatter<'_>, num: &T, upper: bool) -> Result
171where
172    T: flt2dec::DecodableFloat,
173{
174    let force_sign = fmt.sign_plus();
175    let sign = match force_sign {
176        false => flt2dec::Sign::Minus,
177        true => flt2dec::Sign::MinusPlus,
178    };
179
180    if let Some(precision) = fmt.options.get_precision() {
181        float_to_exponential_common_exact(fmt, num, sign, precision, upper)
182    } else {
183        float_to_exponential_common_shortest(fmt, num, sign, upper)
184    }
185}
186
187#[ferrocene::prevalidated]
188fn float_to_general_debug<T>(fmt: &mut Formatter<'_>, num: &T) -> Result
189where
190    T: flt2dec::DecodableFloat + GeneralFormat,
191{
192    let force_sign = fmt.sign_plus();
193    let sign = match force_sign {
194        false => flt2dec::Sign::Minus,
195        true => flt2dec::Sign::MinusPlus,
196    };
197
198    if let Some(precision) = fmt.options.get_precision() {
199        // this behavior of {:.PREC?} predates exponential formatting for {:?}
200        float_to_decimal_common_exact(fmt, num, sign, precision)
201    } else {
202        // since there is no precision, there will be no rounding
203        if num.already_rounded_value_should_use_exponential() {
204            let upper = false;
205            float_to_exponential_common_shortest(fmt, num, sign, upper)
206        } else {
207            let min_precision = 1;
208            float_to_decimal_common_shortest(fmt, num, sign, min_precision)
209        }
210    }
211}
212
213macro_rules! floating {
214    ($($ty:ident)*) => {
215        $(
216            #[stable(feature = "rust1", since = "1.0.0")]
217            impl Debug for $ty {
218                #[ferrocene::prevalidated]
219                fn fmt(&self, fmt: &mut Formatter<'_>) -> Result {
220                    float_to_general_debug(fmt, self)
221                }
222            }
223
224            #[stable(feature = "rust1", since = "1.0.0")]
225            impl Display for $ty {
226                #[ferrocene::prevalidated]
227                fn fmt(&self, fmt: &mut Formatter<'_>) -> Result {
228                    float_to_decimal_display(fmt, self)
229                }
230            }
231
232            #[stable(feature = "rust1", since = "1.0.0")]
233            impl LowerExp for $ty {
234                #[ferrocene::prevalidated]
235                fn fmt(&self, fmt: &mut Formatter<'_>) -> Result {
236                    float_to_exponential_common(fmt, self, false)
237                }
238            }
239
240            #[stable(feature = "rust1", since = "1.0.0")]
241            impl UpperExp for $ty {
242                #[ferrocene::prevalidated]
243                fn fmt(&self, fmt: &mut Formatter<'_>) -> Result {
244                    float_to_exponential_common(fmt, self, true)
245                }
246            }
247        )*
248    };
249}
250
251floating! { f32 f64 }
252
253#[cfg(target_has_reliable_f16)]
254floating! { f16 }
255
256// FIXME(f16): A fallback is used when the backend+target does not support f16 well, in order
257// to avoid ICEs.
258
259#[cfg(not(target_has_reliable_f16))]
260#[stable(feature = "rust1", since = "1.0.0")]
261impl Debug for f16 {
262    #[inline]
263    fn fmt(&self, f: &mut Formatter<'_>) -> Result {
264        write!(f, "{:#06x}", self.to_bits())
265    }
266}
267
268#[cfg(not(target_has_reliable_f16))]
269#[stable(feature = "rust1", since = "1.0.0")]
270impl Display for f16 {
271    #[inline]
272    fn fmt(&self, fmt: &mut Formatter<'_>) -> Result {
273        Debug::fmt(self, fmt)
274    }
275}
276
277#[cfg(not(target_has_reliable_f16))]
278#[stable(feature = "rust1", since = "1.0.0")]
279impl LowerExp for f16 {
280    #[inline]
281    fn fmt(&self, fmt: &mut Formatter<'_>) -> Result {
282        Debug::fmt(self, fmt)
283    }
284}
285
286#[cfg(not(target_has_reliable_f16))]
287#[stable(feature = "rust1", since = "1.0.0")]
288impl UpperExp for f16 {
289    #[inline]
290    fn fmt(&self, fmt: &mut Formatter<'_>) -> Result {
291        Debug::fmt(self, fmt)
292    }
293}
294
295#[stable(feature = "rust1", since = "1.0.0")]
296impl Debug for f128 {
297    #[inline]
298    fn fmt(&self, f: &mut Formatter<'_>) -> Result {
299        write!(f, "{:#034x}", self.to_bits())
300    }
301}