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