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