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        // 1 integral digit + `precision` fractional digits = `precision + 1` total digits
182        float_to_exponential_common_exact(fmt, num, sign, precision + 1, upper)
183    } else {
184        float_to_exponential_common_shortest(fmt, num, sign, upper)
185    }
186}
187
188#[ferrocene::prevalidated]
189fn float_to_general_debug<T>(fmt: &mut Formatter<'_>, num: &T) -> Result
190where
191    T: flt2dec::DecodableFloat + GeneralFormat,
192{
193    let force_sign = fmt.sign_plus();
194    let sign = match force_sign {
195        false => flt2dec::Sign::Minus,
196        true => flt2dec::Sign::MinusPlus,
197    };
198
199    if let Some(precision) = fmt.options.get_precision() {
200        // this behavior of {:.PREC?} predates exponential formatting for {:?}
201        float_to_decimal_common_exact(fmt, num, sign, precision)
202    } else {
203        // since there is no precision, there will be no rounding
204        if num.already_rounded_value_should_use_exponential() {
205            let upper = false;
206            float_to_exponential_common_shortest(fmt, num, sign, upper)
207        } else {
208            let min_precision = 1;
209            float_to_decimal_common_shortest(fmt, num, sign, min_precision)
210        }
211    }
212}
213
214macro_rules! floating {
215    ($($ty:ident)*) => {
216        $(
217            #[stable(feature = "rust1", since = "1.0.0")]
218            impl Debug for $ty {
219                #[ferrocene::prevalidated]
220                fn fmt(&self, fmt: &mut Formatter<'_>) -> Result {
221                    float_to_general_debug(fmt, self)
222                }
223            }
224
225            #[stable(feature = "rust1", since = "1.0.0")]
226            impl Display for $ty {
227                #[ferrocene::prevalidated]
228                fn fmt(&self, fmt: &mut Formatter<'_>) -> Result {
229                    float_to_decimal_display(fmt, self)
230                }
231            }
232
233            #[stable(feature = "rust1", since = "1.0.0")]
234            impl LowerExp for $ty {
235                #[ferrocene::prevalidated]
236                fn fmt(&self, fmt: &mut Formatter<'_>) -> Result {
237                    float_to_exponential_common(fmt, self, false)
238                }
239            }
240
241            #[stable(feature = "rust1", since = "1.0.0")]
242            impl UpperExp for $ty {
243                #[ferrocene::prevalidated]
244                fn fmt(&self, fmt: &mut Formatter<'_>) -> Result {
245                    float_to_exponential_common(fmt, self, true)
246                }
247            }
248        )*
249    };
250}
251
252floating! { f32 f64 }
253
254#[cfg(target_has_reliable_f16)]
255floating! { f16 }
256
257// FIXME(f16): A fallback is used when the backend+target does not support f16 well, in order
258// to avoid ICEs.
259
260#[cfg(not(target_has_reliable_f16))]
261#[stable(feature = "rust1", since = "1.0.0")]
262impl Debug for f16 {
263    #[inline]
264    fn fmt(&self, f: &mut Formatter<'_>) -> Result {
265        write!(f, "{:#06x}", self.to_bits())
266    }
267}
268
269#[cfg(not(target_has_reliable_f16))]
270#[stable(feature = "rust1", since = "1.0.0")]
271impl Display for f16 {
272    #[inline]
273    fn fmt(&self, fmt: &mut Formatter<'_>) -> Result {
274        Debug::fmt(self, fmt)
275    }
276}
277
278#[cfg(not(target_has_reliable_f16))]
279#[stable(feature = "rust1", since = "1.0.0")]
280impl LowerExp for f16 {
281    #[inline]
282    fn fmt(&self, fmt: &mut Formatter<'_>) -> Result {
283        Debug::fmt(self, fmt)
284    }
285}
286
287#[cfg(not(target_has_reliable_f16))]
288#[stable(feature = "rust1", since = "1.0.0")]
289impl UpperExp for f16 {
290    #[inline]
291    fn fmt(&self, fmt: &mut Formatter<'_>) -> Result {
292        Debug::fmt(self, fmt)
293    }
294}
295
296#[stable(feature = "rust1", since = "1.0.0")]
297impl Debug for f128 {
298    #[inline]
299    fn fmt(&self, f: &mut Formatter<'_>) -> Result {
300        write!(f, "{:#034x}", self.to_bits())
301    }
302}