Skip to main content

core/fmt/
float.rs

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