core/num/imp/flt2dec/mod.rs
1/*!
2
3Floating-point number to decimal conversion routines.
4
5# Problem statement
6
7We are given the floating-point number `v = f * 2^e` with an integer `f`,
8and its bounds `minus` and `plus` such that any number between `v - minus` and
9`v + plus` will be rounded to `v`. For the simplicity we assume that
10this range is exclusive. Then we would like to get the unique decimal
11representation `V = 0.d[0..n-1] * 10^k` such that:
12
13- `d[0]` is non-zero.
14
15- It's correctly rounded when parsed back: `v - minus < V < v + plus`.
16 Furthermore it is shortest such one, i.e., there is no representation
17 with less than `n` digits that is correctly rounded.
18
19- It's closest to the original value: `abs(V - v) <= 10^(k-n) / 2`. Note that
20 there might be two representations satisfying this uniqueness requirement,
21 in which case some tie-breaking mechanism is used.
22
23We will call this mode of operation as to the *shortest* mode. This mode is used
24when there is no additional constraint, and can be thought as a "natural" mode
25as it matches the ordinary intuition (it at least prints `0.1f32` as "0.1").
26
27We have two more modes of operation closely related to each other. In these modes
28we are given either the number of significant digits `n` or the last-digit
29limitation `limit` (which determines the actual `n`), and we would like to get
30the representation `V = 0.d[0..n-1] * 10^k` such that:
31
32- `d[0]` is non-zero, unless `n` was zero in which case only `k` is returned.
33
34- It's closest to the original value: `abs(V - v) <= 10^(k-n) / 2`. Again,
35 there might be some tie-breaking mechanism.
36
37When `limit` is given but not `n`, we set `n` such that `k - n = limit`
38so that the last digit `d[n-1]` is scaled by `10^(k-n) = 10^limit`.
39If such `n` is negative, we clip it to zero so that we will only get `k`.
40We are also limited by the supplied buffer. This limitation is used to print
41the number up to given number of fractional digits without knowing
42the correct `k` beforehand.
43
44We will call the mode of operation requiring `n` as to the *exact* mode,
45and one requiring `limit` as to the *fixed* mode. The exact mode is a subset of
46the fixed mode: the sufficiently large last-digit limitation will eventually fill
47the supplied buffer and let the algorithm to return.
48
49# Implementation overview
50
51It is easy to get the floating point printing correct but slow (Russ Cox has
52[demonstrated](https://research.swtch.com/ftoa) how it's easy), or incorrect but
53fast (naïve division and modulo). But it is surprisingly hard to print
54floating point numbers correctly *and* efficiently.
55
56There are two classes of algorithms widely known to be correct.
57
58- The "Dragon" family of algorithm is first described by Guy L. Steele Jr. and
59 Jon L. White. They rely on the fixed-size big integer for their correctness.
60 A slight improvement was found later, which is posthumously described by
61 Robert G. Burger and R. Kent Dybvig. David Gay's `dtoa.c` routine is
62 a popular implementation of this strategy.
63
64- The "Grisu" family of algorithm is first described by Florian Loitsch.
65 They use very cheap integer-only procedure to determine the close-to-correct
66 representation which is at least guaranteed to be shortest. The variant,
67 Grisu3, actively detects if the resulting representation is incorrect.
68
69We implement both algorithms with necessary tweaks to suit our requirements.
70In particular, published literatures are short of the actual implementation
71difficulties like how to avoid arithmetic overflows. Each implementation,
72available in `strategy::dragon` and `strategy::grisu` respectively,
73extensively describes all necessary justifications and many proofs for them.
74(It is still difficult to follow though. You have been warned.)
75
76Both implementations expose two public functions:
77
78- `format_shortest(decoded, buf)`, which always needs at least
79 `MAX_SIG_DIGITS` digits of buffer. Implements the shortest mode.
80
81- `format_exact(decoded, buf, limit)`, which accepts as small as
82 one digit of buffer. Implements exact and fixed modes.
83
84They try to fill the `u8` buffer with digits and returns the number of digits
85written and the exponent `k`. They are total for all finite `f32` and `f64`
86inputs (Grisu internally falls back to Dragon if necessary).
87
88The rendered digits are formatted into the actual string form with
89four functions:
90
91- `to_shortest_str` prints the shortest representation, which can be padded by
92 zeroes to make *at least* given number of fractional digits.
93
94- `to_shortest_exp_str` prints the shortest representation, which can be
95 padded by zeroes when its exponent is in the specified ranges,
96 or can be printed in the exponential form such as `1.23e45`.
97
98- `to_exact_exp_str` prints the exact representation with given number of
99 digits in the exponential form.
100
101- `to_exact_fixed_str` prints the fixed representation with *exactly*
102 given number of fractional digits.
103
104They all return a slice of preallocated `Part` array, which corresponds to
105the individual part of strings: a fixed string, a part of rendered digits,
106a number of zeroes or a small (`u16`) number. The caller is expected to
107provide a large enough buffer and `Part` array, and to assemble the final
108string from resulting `Part`s itself.
109
110All algorithms and formatting functions are accompanied by extensive tests
111in `coretests::num::flt2dec` module. It also shows how to use individual
112functions.
113
114*/
115
116// while this is extensively documented, this is in principle private which is
117// only made public for testing. do not expose us.
118#![doc(hidden)]
119#![unstable(
120 feature = "flt2dec",
121 reason = "internal routines only exposed for testing",
122 issue = "none"
123)]
124
125pub use self::decoder::{DecodableFloat, Decoded, FullDecoded, decode};
126use super::fmt::{Formatted, Part};
127use crate::mem::MaybeUninit;
128
129pub mod decoder;
130pub mod estimator;
131
132/// Digit-generation algorithms.
133pub mod strategy {
134 pub mod dragon;
135 pub mod grisu;
136}
137
138/// The minimum size of buffer necessary for the shortest mode.
139///
140/// It is a bit non-trivial to derive, but this is one plus the maximal number of
141/// significant decimal digits from formatting algorithms with the shortest result.
142/// The exact formula is `ceil(# bits in mantissa * log_10 2 + 1)`.
143pub const MAX_SIG_DIGITS: usize = 17;
144
145/// When `d` contains decimal digits, increase the last digit and propagate carry.
146/// Returns a next digit when it causes the length to change.
147#[doc(hidden)]
148#[ferrocene::prevalidated]
149pub fn round_up(d: &mut [u8]) -> Option<u8> {
150 match d.iter().rposition(|&c| c != b'9') {
151 Some(i) => {
152 // d[i+1..n] is all nines
153 d[i] += 1;
154 d[i + 1..].fill(b'0');
155 None
156 }
157 None if d.is_empty() => {
158 // an empty buffer rounds up (a bit strange but reasonable)
159 Some(b'1')
160 }
161 None => {
162 // 999..999 rounds to 1000..000 with an increased exponent
163 d[0] = b'1';
164 d[1..].fill(b'0');
165 Some(b'0')
166 }
167 }
168}
169
170/// Formats given decimal digits `0.<...buf...> * 10^exp` into the decimal form
171/// with at least given number of fractional digits. The result is stored to
172/// the supplied parts array and a slice of written parts is returned.
173///
174/// `frac_digits` can be less than the number of actual fractional digits in `buf`;
175/// it will be ignored and full digits will be printed. It is only used to print
176/// additional zeroes after rendered digits. Thus `frac_digits` of 0 means that
177/// it will only print given digits and nothing else.
178#[ferrocene::prevalidated]
179fn digits_to_dec_str<'a>(
180 buf: &'a [u8],
181 exp: i16,
182 frac_digits: usize,
183 parts: &'a mut [MaybeUninit<Part<'a>>],
184) -> &'a [Part<'a>] {
185 assert!(!buf.is_empty());
186 assert!(buf[0] > b'0');
187 assert!(parts.len() >= 4);
188
189 // if there is the restriction on the last digit position, `buf` is assumed to be
190 // left-padded with the virtual zeroes. the number of virtual zeroes, `nzeroes`,
191 // equals to `max(0, exp + frac_digits - buf.len())`, so that the position of
192 // the last digit `exp - buf.len() - nzeroes` is no more than `-frac_digits`:
193 //
194 // |<-virtual->|
195 // |<---- buf ---->| zeroes | exp
196 // 0. 1 2 3 4 5 6 7 8 9 _ _ _ _ _ _ x 10
197 // | | |
198 // 10^exp 10^(exp-buf.len()) 10^(exp-buf.len()-nzeroes)
199 //
200 // `nzeroes` is individually calculated for each case in order to avoid overflow.
201
202 if exp <= 0 {
203 // the decimal point is before rendered digits: [0.][000...000][1234][____]
204 let minus_exp = -(exp as i32) as usize;
205 parts[0] = MaybeUninit::new(Part::Copy(b"0."));
206 parts[1] = MaybeUninit::new(Part::Zero(minus_exp));
207 parts[2] = MaybeUninit::new(Part::Copy(buf));
208 if frac_digits > buf.len() && frac_digits - buf.len() > minus_exp {
209 parts[3] = MaybeUninit::new(Part::Zero((frac_digits - buf.len()) - minus_exp));
210 // SAFETY: we just initialized the elements `..4`.
211 unsafe { parts[..4].assume_init_ref() }
212 } else {
213 // SAFETY: we just initialized the elements `..3`.
214 unsafe { parts[..3].assume_init_ref() }
215 }
216 } else {
217 let exp = exp as usize;
218 if exp < buf.len() {
219 // the decimal point is inside rendered digits: [12][.][34][____]
220 parts[0] = MaybeUninit::new(Part::Copy(&buf[..exp]));
221 parts[1] = MaybeUninit::new(Part::Copy(b"."));
222 parts[2] = MaybeUninit::new(Part::Copy(&buf[exp..]));
223 if frac_digits > buf.len() - exp {
224 parts[3] = MaybeUninit::new(Part::Zero(frac_digits - (buf.len() - exp)));
225 // SAFETY: we just initialized the elements `..4`.
226 unsafe { parts[..4].assume_init_ref() }
227 } else {
228 // SAFETY: we just initialized the elements `..3`.
229 unsafe { parts[..3].assume_init_ref() }
230 }
231 } else {
232 // the decimal point is after rendered digits: [1234][____0000] or [1234][__][.][__].
233 parts[0] = MaybeUninit::new(Part::Copy(buf));
234 parts[1] = MaybeUninit::new(Part::Zero(exp - buf.len()));
235 if frac_digits > 0 {
236 parts[2] = MaybeUninit::new(Part::Copy(b"."));
237 parts[3] = MaybeUninit::new(Part::Zero(frac_digits));
238 // SAFETY: we just initialized the elements `..4`.
239 unsafe { parts[..4].assume_init_ref() }
240 } else {
241 // SAFETY: we just initialized the elements `..2`.
242 unsafe { parts[..2].assume_init_ref() }
243 }
244 }
245 }
246}
247
248/// Formats the given decimal digits `0.<...buf...> * 10^exp` into the exponential
249/// form with at least the given number of fractional digits. When `upper` is `true`,
250/// the exponent will be prefixed by `E`; otherwise that's `e`. The result is
251/// stored to the supplied parts array and a slice of written parts is returned.
252///
253/// `frac_digits` can be less than the number of actual fractional digits in `buf`;
254/// it will be ignored and full digits will be printed. It is only used to print
255/// additional zeroes after rendered digits. Thus, `frac_digits == 0` means that
256/// it will only print the given digits and nothing else.
257///
258/// For example, `buf = b"123", exp = 3, frac_digits = 4` yields the parts for
259/// `1.2300e2`.
260#[ferrocene::prevalidated]
261fn digits_to_exp_str<'a>(
262 buf: &'a [u8],
263 exp: i16,
264 frac_digits: usize,
265 upper: bool,
266 parts: &'a mut [MaybeUninit<Part<'a>>],
267) -> &'a [Part<'a>] {
268 assert!(!buf.is_empty());
269 assert!(buf[0] > b'0');
270 assert!(parts.len() >= 6);
271
272 let mut n = 0;
273
274 parts[n] = MaybeUninit::new(Part::Copy(&buf[..1]));
275 n += 1;
276
277 // The first generated digit becomes the integral digit, anything after that is already part of
278 // the fractional portion we can emit verbatim.
279 let actual_frac_digits = buf.len() - 1;
280 if actual_frac_digits > 0 || frac_digits > 0 {
281 // Emit a decimal point either when we already have fractional digits or when the requested
282 // precision needs trailing zeroes after the radix point.
283 parts[n] = MaybeUninit::new(Part::Copy(b"."));
284 n += 1;
285 if actual_frac_digits > 0 {
286 parts[n] = MaybeUninit::new(Part::Copy(&buf[1..]));
287 n += 1;
288 }
289 if frac_digits > actual_frac_digits {
290 // format_exact exhausted the meaningful digits, so extend the fractional part with
291 // zeroes up to the requested precision.
292 parts[n] = MaybeUninit::new(Part::Zero(frac_digits - actual_frac_digits));
293 n += 1;
294 }
295 }
296
297 // 0.1234 x 10^exp = 1.234 x 10^(exp-1)
298 let exp = exp as i32 - 1; // avoid underflow when exp is i16::MIN
299 if exp < 0 {
300 parts[n] = MaybeUninit::new(Part::Copy(if upper { b"E-" } else { b"e-" }));
301 parts[n + 1] = MaybeUninit::new(Part::Num(-exp as u16));
302 } else {
303 parts[n] = MaybeUninit::new(Part::Copy(if upper { b"E" } else { b"e" }));
304 parts[n + 1] = MaybeUninit::new(Part::Num(exp as u16));
305 }
306 // SAFETY: we just initialized the elements `..n + 2`.
307 unsafe { parts[..n + 2].assume_init_ref() }
308}
309
310/// Sign formatting options.
311#[derive(Copy, Clone, PartialEq, Eq, Debug)]
312#[ferrocene::prevalidated]
313pub enum Sign {
314 /// Prints `-` for any negative value.
315 Minus, // -inf -1 -0 0 1 inf nan
316 /// Prints `-` for any negative value, or `+` otherwise.
317 MinusPlus, // -inf -1 -0 +0 +1 +inf nan
318}
319
320/// Returns the static byte string corresponding to the sign to be formatted.
321/// It can be either `""`, `"+"` or `"-"`.
322#[ferrocene::prevalidated]
323fn determine_sign(sign: Sign, decoded: &FullDecoded, negative: bool) -> &'static str {
324 match (*decoded, sign) {
325 (FullDecoded::Nan, _) => "",
326 (_, Sign::Minus) => {
327 if negative {
328 "-"
329 } else {
330 ""
331 }
332 }
333 (_, Sign::MinusPlus) => {
334 if negative {
335 "-"
336 } else {
337 "+"
338 }
339 }
340 }
341}
342
343/// Formats the given floating point number into the decimal form with at least
344/// given number of fractional digits. The result is stored to the supplied parts
345/// array while utilizing given byte buffer as a scratch. `upper` is currently
346/// unused but left for the future decision to change the case of non-finite values,
347/// i.e., `inf` and `nan`. The first part to be rendered is always a `Part::Sign`
348/// (which can be an empty string if no sign is rendered).
349///
350/// `format_shortest` should be the underlying digit-generation function.
351/// It should return the part of the buffer that it initialized.
352/// You probably would want `strategy::grisu::format_shortest` for this.
353///
354/// `frac_digits` can be less than the number of actual fractional digits in `v`;
355/// it will be ignored and full digits will be printed. It is only used to print
356/// additional zeroes after rendered digits. Thus `frac_digits` of 0 means that
357/// it will only print given digits and nothing else.
358///
359/// The byte buffer should be at least `MAX_SIG_DIGITS` bytes long.
360/// There should be at least 4 parts available, due to the worst case like
361/// `[+][0.][0000][2][0000]` with `frac_digits = 10`.
362#[ferrocene::prevalidated]
363pub fn to_shortest_str<'a, T, F>(
364 mut format_shortest: F,
365 v: T,
366 sign: Sign,
367 frac_digits: usize,
368 buf: &'a mut [MaybeUninit<u8>],
369 parts: &'a mut [MaybeUninit<Part<'a>>],
370) -> Formatted<'a>
371where
372 T: DecodableFloat,
373 F: FnMut(&Decoded, &'a mut [MaybeUninit<u8>]) -> (&'a [u8], i16),
374{
375 assert!(parts.len() >= 4);
376 assert!(buf.len() >= MAX_SIG_DIGITS);
377
378 let (negative, full_decoded) = decode(v);
379 let sign = determine_sign(sign, &full_decoded, negative);
380 match full_decoded {
381 FullDecoded::Nan => {
382 parts[0] = MaybeUninit::new(Part::Copy(b"NaN"));
383 // SAFETY: we just initialized the elements `..1`.
384 Formatted { sign, parts: unsafe { parts[..1].assume_init_ref() } }
385 }
386 FullDecoded::Infinite => {
387 parts[0] = MaybeUninit::new(Part::Copy(b"inf"));
388 // SAFETY: we just initialized the elements `..1`.
389 Formatted { sign, parts: unsafe { parts[..1].assume_init_ref() } }
390 }
391 FullDecoded::Zero => {
392 if frac_digits > 0 {
393 // [0.][0000]
394 parts[0] = MaybeUninit::new(Part::Copy(b"0."));
395 parts[1] = MaybeUninit::new(Part::Zero(frac_digits));
396 Formatted {
397 sign,
398 // SAFETY: we just initialized the elements `..2`.
399 parts: unsafe { parts[..2].assume_init_ref() },
400 }
401 } else {
402 parts[0] = MaybeUninit::new(Part::Copy(b"0"));
403 Formatted {
404 sign,
405 // SAFETY: we just initialized the elements `..1`.
406 parts: unsafe { parts[..1].assume_init_ref() },
407 }
408 }
409 }
410 FullDecoded::Finite(ref decoded) => {
411 let (buf, exp) = format_shortest(decoded, buf);
412 Formatted { sign, parts: digits_to_dec_str(buf, exp, frac_digits, parts) }
413 }
414 }
415}
416
417/// Formats the given floating point number into the decimal form or
418/// the exponential form, depending on the resulting exponent. The result is
419/// stored to the supplied parts array while utilizing given byte buffer
420/// as a scratch. `upper` is used to determine the case of non-finite values
421/// (`inf` and `nan`) or the case of the exponent prefix (`e` or `E`).
422/// The first part to be rendered is always a `Part::Sign` (which can be
423/// an empty string if no sign is rendered).
424///
425/// `format_shortest` should be the underlying digit-generation function.
426/// It should return the part of the buffer that it initialized.
427/// You probably would want `strategy::grisu::format_shortest` for this.
428///
429/// The `dec_bounds` is a tuple `(lo, hi)` such that the number is formatted
430/// as decimal only when `10^lo <= V < 10^hi`. Note that this is the *apparent* `V`
431/// instead of the actual `v`! Thus any printed exponent in the exponential form
432/// cannot be in this range, avoiding any confusion.
433///
434/// The byte buffer should be at least `MAX_SIG_DIGITS` bytes long.
435/// There should be at least 6 parts available, due to the worst case like
436/// `[+][1][.][2345][e][-][6]`.
437#[ferrocene::prevalidated]
438pub fn to_shortest_exp_str<'a, T, F>(
439 mut format_shortest: F,
440 v: T,
441 sign: Sign,
442 dec_bounds: (i16, i16),
443 upper: bool,
444 buf: &'a mut [MaybeUninit<u8>],
445 parts: &'a mut [MaybeUninit<Part<'a>>],
446) -> Formatted<'a>
447where
448 T: DecodableFloat,
449 F: FnMut(&Decoded, &'a mut [MaybeUninit<u8>]) -> (&'a [u8], i16),
450{
451 assert!(parts.len() >= 6);
452 assert!(buf.len() >= MAX_SIG_DIGITS);
453 assert!(dec_bounds.0 <= dec_bounds.1);
454
455 let (negative, full_decoded) = decode(v);
456 let sign = determine_sign(sign, &full_decoded, negative);
457 match full_decoded {
458 FullDecoded::Nan => {
459 parts[0] = MaybeUninit::new(Part::Copy(b"NaN"));
460 // SAFETY: we just initialized the elements `..1`.
461 Formatted { sign, parts: unsafe { parts[..1].assume_init_ref() } }
462 }
463 FullDecoded::Infinite => {
464 parts[0] = MaybeUninit::new(Part::Copy(b"inf"));
465 // SAFETY: we just initialized the elements `..1`.
466 Formatted { sign, parts: unsafe { parts[..1].assume_init_ref() } }
467 }
468 FullDecoded::Zero => {
469 parts[0] = if dec_bounds.0 <= 0 && 0 < dec_bounds.1 {
470 MaybeUninit::new(Part::Copy(b"0"))
471 } else {
472 MaybeUninit::new(Part::Copy(if upper { b"0E0" } else { b"0e0" }))
473 };
474 // SAFETY: we just initialized the elements `..1`.
475 Formatted { sign, parts: unsafe { parts[..1].assume_init_ref() } }
476 }
477 FullDecoded::Finite(ref decoded) => {
478 let (buf, exp) = format_shortest(decoded, buf);
479 let vis_exp = exp as i32 - 1;
480 let parts = if dec_bounds.0 as i32 <= vis_exp && vis_exp < dec_bounds.1 as i32 {
481 digits_to_dec_str(buf, exp, 0, parts)
482 } else {
483 digits_to_exp_str(buf, exp, 0, upper, parts)
484 };
485 Formatted { sign, parts }
486 }
487 }
488}
489
490/// Returns a rather crude approximation (upper bound) for the maximum buffer size
491/// calculated from the given decoded exponent.
492///
493/// The exact limit is:
494///
495/// - when `exp < 0`, the maximum length is `ceil(log_10 (5^-exp * (2^64 - 1)))`.
496/// - when `exp >= 0`, the maximum length is `ceil(log_10 (2^exp * (2^64 - 1)))`.
497///
498/// `ceil(log_10 (x^exp * (2^64 - 1)))` is less than `ceil(log_10 (2^64 - 1)) +
499/// ceil(exp * log_10 x)`, which is in turn less than `20 + (1 + exp * log_10 x)`.
500/// We use the facts that `log_10 2 < 5/16` and `log_10 5 < 12/16`, which is
501/// enough for our purposes.
502///
503/// Why do we need this? `format_exact` functions will fill the entire buffer
504/// unless limited by the last digit restriction, but it is possible that
505/// the number of digits requested is ridiculously large (say, 30,000 digits).
506/// The vast majority of buffer will be filled with zeroes, so we don't want to
507/// allocate all the buffer beforehand. Consequently, for any given arguments,
508/// 826 bytes of buffer should be sufficient for `f64`. Compare this with
509/// the actual number for the worst case: 770 bytes (when `exp = -1074`).
510#[ferrocene::prevalidated]
511fn estimate_max_buf_len(exp: i16) -> usize {
512 21 + ((if exp < 0 { -12 } else { 5 } * exp as i32) as usize >> 4)
513}
514
515/// Formats given floating point number into the exponential form with
516/// exactly given number of fractional digits. The result is stored to
517/// the supplied parts array while utilizing given byte buffer as a scratch.
518/// `upper` is used to determine the case of the exponent prefix (`e` or `E`).
519/// The first part to be rendered is always a `Part::Sign` (which can be
520/// an empty string if no sign is rendered).
521///
522/// `format_exact` should be the underlying digit-generation function.
523/// It should return the part of the buffer that it initialized.
524/// You probably would want `strategy::grisu::format_exact` for this.
525///
526/// The returned format is `[sign][digit][.fraction?][zero padding?][e|E][exponent]`.
527///
528/// The byte buffer should be at least `frac_digits + 1` bytes long unless
529/// `frac_digits` is so large that only the fixed number of digits will be ever written.
530/// (The tipping point for `f64` is about 800, so 1000 bytes should be enough.)
531/// There should be at least 6 parts available, due to the worst case like
532/// `[+][1][.][2345][e][-][6]`.
533#[ferrocene::prevalidated]
534pub fn to_exact_exp_str<'a, T, F>(
535 mut format_exact: F,
536 v: T,
537 sign: Sign,
538 frac_digits: usize,
539 upper: bool,
540 buf: &'a mut [MaybeUninit<u8>],
541 parts: &'a mut [MaybeUninit<Part<'a>>],
542) -> Formatted<'a>
543where
544 T: DecodableFloat,
545 F: FnMut(&Decoded, &'a mut [MaybeUninit<u8>], i16) -> (&'a [u8], i16),
546{
547 assert!(parts.len() >= 6);
548
549 let (negative, full_decoded) = decode(v);
550 let sign = determine_sign(sign, &full_decoded, negative);
551 match full_decoded {
552 FullDecoded::Nan => {
553 parts[0] = MaybeUninit::new(Part::Copy(b"NaN"));
554 // SAFETY: we just initialized the elements `..1`.
555 Formatted { sign, parts: unsafe { parts[..1].assume_init_ref() } }
556 }
557 FullDecoded::Infinite => {
558 parts[0] = MaybeUninit::new(Part::Copy(b"inf"));
559 // SAFETY: we just initialized the elements `..1`.
560 Formatted { sign, parts: unsafe { parts[..1].assume_init_ref() } }
561 }
562 FullDecoded::Zero => {
563 if frac_digits > 0 {
564 // [0.][0000][e0]
565 parts[0] = MaybeUninit::new(Part::Copy(b"0."));
566 parts[1] = MaybeUninit::new(Part::Zero(frac_digits));
567 parts[2] = MaybeUninit::new(Part::Copy(if upper { b"E0" } else { b"e0" }));
568 Formatted {
569 sign,
570 // SAFETY: we just initialized the elements `..3`.
571 parts: unsafe { parts[..3].assume_init_ref() },
572 }
573 } else {
574 parts[0] = MaybeUninit::new(Part::Copy(if upper { b"0E0" } else { b"0e0" }));
575 Formatted {
576 sign,
577 // SAFETY: we just initialized the elements `..1`.
578 parts: unsafe { parts[..1].assume_init_ref() },
579 }
580 }
581 }
582 FullDecoded::Finite(ref decoded) => {
583 let maxlen = estimate_max_buf_len(decoded.exp);
584 // Scratch space is only needed for the significant digits that `format_exact` can
585 // actually generate. Any remaining requested fractional precision becomes a trailing
586 // `Part::Zero`.
587 let sig_digits = if frac_digits < maxlen { frac_digits + 1 } else { maxlen };
588 assert!(buf.len() >= sig_digits);
589
590 let (buf, exp) = format_exact(decoded, &mut buf[..sig_digits], i16::MIN);
591 Formatted { sign, parts: digits_to_exp_str(buf, exp, frac_digits, upper, parts) }
592 }
593 }
594}
595
596/// Formats given floating point number into the decimal form with exactly
597/// given number of fractional digits. The result is stored to the supplied parts
598/// array while utilizing given byte buffer as a scratch. `upper` is currently
599/// unused but left for the future decision to change the case of non-finite values,
600/// i.e., `inf` and `nan`. The first part to be rendered is always a `Part::Sign`
601/// (which can be an empty string if no sign is rendered).
602///
603/// `format_exact` should be the underlying digit-generation function.
604/// It should return the part of the buffer that it initialized.
605/// You probably would want `strategy::grisu::format_exact` for this.
606///
607/// The byte buffer should be enough for the output unless `frac_digits` is
608/// so large that only the fixed number of digits will be ever written.
609/// (The tipping point for `f64` is about 800, and 1000 bytes should be enough.)
610/// There should be at least 4 parts available, due to the worst case like
611/// `[+][0.][0000][2][0000]` with `frac_digits = 10`.
612#[ferrocene::prevalidated]
613pub fn to_exact_fixed_str<'a, T, F>(
614 mut format_exact: F,
615 v: T,
616 sign: Sign,
617 frac_digits: usize,
618 buf: &'a mut [MaybeUninit<u8>],
619 parts: &'a mut [MaybeUninit<Part<'a>>],
620) -> Formatted<'a>
621where
622 T: DecodableFloat,
623 F: FnMut(&Decoded, &'a mut [MaybeUninit<u8>], i16) -> (&'a [u8], i16),
624{
625 assert!(parts.len() >= 4);
626
627 let (negative, full_decoded) = decode(v);
628 let sign = determine_sign(sign, &full_decoded, negative);
629 match full_decoded {
630 FullDecoded::Nan => {
631 parts[0] = MaybeUninit::new(Part::Copy(b"NaN"));
632 // SAFETY: we just initialized the elements `..1`.
633 Formatted { sign, parts: unsafe { parts[..1].assume_init_ref() } }
634 }
635 FullDecoded::Infinite => {
636 parts[0] = MaybeUninit::new(Part::Copy(b"inf"));
637 // SAFETY: we just initialized the elements `..1`.
638 Formatted { sign, parts: unsafe { parts[..1].assume_init_ref() } }
639 }
640 FullDecoded::Zero => {
641 if frac_digits > 0 {
642 // [0.][0000]
643 parts[0] = MaybeUninit::new(Part::Copy(b"0."));
644 parts[1] = MaybeUninit::new(Part::Zero(frac_digits));
645 Formatted {
646 sign,
647 // SAFETY: we just initialized the elements `..2`.
648 parts: unsafe { parts[..2].assume_init_ref() },
649 }
650 } else {
651 parts[0] = MaybeUninit::new(Part::Copy(b"0"));
652 Formatted {
653 sign,
654 // SAFETY: we just initialized the elements `..1`.
655 parts: unsafe { parts[..1].assume_init_ref() },
656 }
657 }
658 }
659 FullDecoded::Finite(ref decoded) => {
660 let maxlen = estimate_max_buf_len(decoded.exp);
661 assert!(buf.len() >= maxlen);
662
663 // it *is* possible that `frac_digits` is ridiculously large.
664 // `format_exact` will end rendering digits much earlier in this case,
665 // because we are strictly limited by `maxlen`.
666 let limit = if frac_digits < 0x8000 { -(frac_digits as i16) } else { i16::MIN };
667 let (buf, exp) = format_exact(decoded, &mut buf[..maxlen], limit);
668 if exp <= limit {
669 // the restriction couldn't been met, so this should render like zero no matter
670 // `exp` was. this does not include the case that the restriction has been met
671 // only after the final rounding-up; it's a regular case with `exp = limit + 1`.
672 debug_assert_eq!(buf.len(), 0);
673 if frac_digits > 0 {
674 // [0.][0000]
675 parts[0] = MaybeUninit::new(Part::Copy(b"0."));
676 parts[1] = MaybeUninit::new(Part::Zero(frac_digits));
677 Formatted {
678 sign,
679 // SAFETY: we just initialized the elements `..2`.
680 parts: unsafe { parts[..2].assume_init_ref() },
681 }
682 } else {
683 parts[0] = MaybeUninit::new(Part::Copy(b"0"));
684 Formatted {
685 sign,
686 // SAFETY: we just initialized the elements `..1`.
687 parts: unsafe { parts[..1].assume_init_ref() },
688 }
689 }
690 } else {
691 Formatted { sign, parts: digits_to_dec_str(buf, exp, frac_digits, parts) }
692 }
693 }
694 }
695}