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