]> git.lizzy.rs Git - rust.git/blob - src/libcore/num/flt2dec/strategy/dragon.rs
Auto merge of #28035 - Diggsey:msvc-escaping, r=alexcrichton
[rust.git] / src / libcore / num / flt2dec / strategy / dragon.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 Almost direct (but slightly optimized) Rust translation of Figure 3 of [1].
13
14 [1] Burger, R. G. and Dybvig, R. K. 1996. Printing floating-point numbers
15     quickly and accurately. SIGPLAN Not. 31, 5 (May. 1996), 108-116.
16 */
17
18 use prelude::v1::*;
19
20 use cmp::Ordering;
21
22 use num::flt2dec::{Decoded, MAX_SIG_DIGITS, round_up};
23 use num::flt2dec::estimator::estimate_scaling_factor;
24 use num::flt2dec::bignum::Digit32 as Digit;
25 use num::flt2dec::bignum::Big32x40 as Big;
26
27 static POW10: [Digit; 10] = [1, 10, 100, 1000, 10000, 100000,
28                              1000000, 10000000, 100000000, 1000000000];
29 static TWOPOW10: [Digit; 10] = [2, 20, 200, 2000, 20000, 200000,
30                                 2000000, 20000000, 200000000, 2000000000];
31
32 // precalculated arrays of `Digit`s for 10^(2^n)
33 static POW10TO16: [Digit; 2] = [0x6fc10000, 0x2386f2];
34 static POW10TO32: [Digit; 4] = [0, 0x85acef81, 0x2d6d415b, 0x4ee];
35 static POW10TO64: [Digit; 7] = [0, 0, 0xbf6a1f01, 0x6e38ed64, 0xdaa797ed, 0xe93ff9f4, 0x184f03];
36 static POW10TO128: [Digit; 14] =
37     [0, 0, 0, 0, 0x2e953e01, 0x3df9909, 0xf1538fd, 0x2374e42f, 0xd3cff5ec, 0xc404dc08,
38      0xbccdb0da, 0xa6337f19, 0xe91f2603, 0x24e];
39 static POW10TO256: [Digit; 27] =
40     [0, 0, 0, 0, 0, 0, 0, 0, 0x982e7c01, 0xbed3875b, 0xd8d99f72, 0x12152f87, 0x6bde50c6,
41      0xcf4a6e70, 0xd595d80f, 0x26b2716e, 0xadc666b0, 0x1d153624, 0x3c42d35a, 0x63ff540e,
42      0xcc5573c0, 0x65f9ef17, 0x55bc28f2, 0x80dcc7f7, 0xf46eeddc, 0x5fdcefce, 0x553f7];
43
44 #[doc(hidden)]
45 pub fn mul_pow10(x: &mut Big, n: usize) -> &mut Big {
46     debug_assert!(n < 512);
47     if n &   7 != 0 { x.mul_small(POW10[n & 7]); }
48     if n &   8 != 0 { x.mul_small(POW10[8]); }
49     if n &  16 != 0 { x.mul_digits(&POW10TO16); }
50     if n &  32 != 0 { x.mul_digits(&POW10TO32); }
51     if n &  64 != 0 { x.mul_digits(&POW10TO64); }
52     if n & 128 != 0 { x.mul_digits(&POW10TO128); }
53     if n & 256 != 0 { x.mul_digits(&POW10TO256); }
54     x
55 }
56
57 fn div_2pow10(x: &mut Big, mut n: usize) -> &mut Big {
58     let largest = POW10.len() - 1;
59     while n > largest {
60         x.div_rem_small(POW10[largest]);
61         n -= largest;
62     }
63     x.div_rem_small(TWOPOW10[n]);
64     x
65 }
66
67 // only usable when `x < 16 * scale`; `scaleN` should be `scale.mul_small(N)`
68 fn div_rem_upto_16<'a>(x: &'a mut Big, scale: &Big,
69                        scale2: &Big, scale4: &Big, scale8: &Big) -> (u8, &'a mut Big) {
70     let mut d = 0;
71     if *x >= *scale8 { x.sub(scale8); d += 8; }
72     if *x >= *scale4 { x.sub(scale4); d += 4; }
73     if *x >= *scale2 { x.sub(scale2); d += 2; }
74     if *x >= *scale  { x.sub(scale);  d += 1; }
75     debug_assert!(*x < *scale);
76     (d, x)
77 }
78
79 /// The shortest mode implementation for Dragon.
80 pub fn format_shortest(d: &Decoded, buf: &mut [u8]) -> (/*#digits*/ usize, /*exp*/ i16) {
81     // the number `v` to format is known to be:
82     // - equal to `mant * 2^exp`;
83     // - preceded by `(mant - 2 * minus) * 2^exp` in the original type; and
84     // - followed by `(mant + 2 * plus) * 2^exp` in the original type.
85     //
86     // obviously, `minus` and `plus` cannot be zero. (for infinities, we use out-of-range values.)
87     // also we assume that at least one digit is generated, i.e. `mant` cannot be zero too.
88     //
89     // this also means that any number between `low = (mant - minus) * 2^exp` and
90     // `high = (mant + plus) * 2^exp` will map to this exact floating point number,
91     // with bounds included when the original mantissa was even (i.e. `!mant_was_odd`).
92
93     assert!(d.mant > 0);
94     assert!(d.minus > 0);
95     assert!(d.plus > 0);
96     assert!(d.mant.checked_add(d.plus).is_some());
97     assert!(d.mant.checked_sub(d.minus).is_some());
98     assert!(buf.len() >= MAX_SIG_DIGITS);
99
100     // `a.cmp(&b) < rounding` is `if d.inclusive {a <= b} else {a < b}`
101     let rounding = if d.inclusive {Ordering::Greater} else {Ordering::Equal};
102
103     // estimate `k_0` from original inputs satisfying `10^(k_0-1) < high <= 10^(k_0+1)`.
104     // the tight bound `k` satisfying `10^(k-1) < high <= 10^k` is calculated later.
105     let mut k = estimate_scaling_factor(d.mant + d.plus, d.exp);
106
107     // convert `{mant, plus, minus} * 2^exp` into the fractional form so that:
108     // - `v = mant / scale`
109     // - `low = (mant - minus) / scale`
110     // - `high = (mant + plus) / scale`
111     let mut mant = Big::from_u64(d.mant);
112     let mut minus = Big::from_u64(d.minus);
113     let mut plus = Big::from_u64(d.plus);
114     let mut scale = Big::from_small(1);
115     if d.exp < 0 {
116         scale.mul_pow2(-d.exp as usize);
117     } else {
118         mant.mul_pow2(d.exp as usize);
119         minus.mul_pow2(d.exp as usize);
120         plus.mul_pow2(d.exp as usize);
121     }
122
123     // divide `mant` by `10^k`. now `scale / 10 < mant + plus <= scale * 10`.
124     if k >= 0 {
125         mul_pow10(&mut scale, k as usize);
126     } else {
127         mul_pow10(&mut mant, -k as usize);
128         mul_pow10(&mut minus, -k as usize);
129         mul_pow10(&mut plus, -k as usize);
130     }
131
132     // fixup when `mant + plus > scale` (or `>=`).
133     // we are not actually modifying `scale`, since we can skip the initial multiplication instead.
134     // now `scale < mant + plus <= scale * 10` and we are ready to generate digits.
135     //
136     // note that `d[0]` *can* be zero, when `scale - plus < mant < scale`.
137     // in this case rounding-up condition (`up` below) will be triggered immediately.
138     if scale.cmp(mant.clone().add(&plus)) < rounding {
139         // equivalent to scaling `scale` by 10
140         k += 1;
141     } else {
142         mant.mul_small(10);
143         minus.mul_small(10);
144         plus.mul_small(10);
145     }
146
147     // cache `(2, 4, 8) * scale` for digit generation.
148     let mut scale2 = scale.clone(); scale2.mul_pow2(1);
149     let mut scale4 = scale.clone(); scale4.mul_pow2(2);
150     let mut scale8 = scale.clone(); scale8.mul_pow2(3);
151
152     let mut down;
153     let mut up;
154     let mut i = 0;
155     loop {
156         // invariants, where `d[0..n-1]` are digits generated so far:
157         // - `v = mant / scale * 10^(k-n-1) + d[0..n-1] * 10^(k-n)`
158         // - `v - low = minus / scale * 10^(k-n-1)`
159         // - `high - v = plus / scale * 10^(k-n-1)`
160         // - `(mant + plus) / scale <= 10` (thus `mant / scale < 10`)
161         // where `d[i..j]` is a shorthand for `d[i] * 10^(j-i) + ... + d[j-1] * 10 + d[j]`.
162
163         // generate one digit: `d[n] = floor(mant / scale) < 10`.
164         let (d, _) = div_rem_upto_16(&mut mant, &scale, &scale2, &scale4, &scale8);
165         debug_assert!(d < 10);
166         buf[i] = b'0' + d;
167         i += 1;
168
169         // this is a simplified description of the modified Dragon algorithm.
170         // many intermediate derivations and completeness arguments are omitted for convenience.
171         //
172         // start with modified invariants, as we've updated `n`:
173         // - `v = mant / scale * 10^(k-n) + d[0..n-1] * 10^(k-n)`
174         // - `v - low = minus / scale * 10^(k-n)`
175         // - `high - v = plus / scale * 10^(k-n)`
176         //
177         // assume that `d[0..n-1]` is the shortest representation between `low` and `high`,
178         // i.e. `d[0..n-1]` satisfies both of the following but `d[0..n-2]` doesn't:
179         // - `low < d[0..n-1] * 10^(k-n) < high` (bijectivity: digits round to `v`); and
180         // - `abs(v / 10^(k-n) - d[0..n-1]) <= 1/2` (the last digit is correct).
181         //
182         // the second condition simplifies to `2 * mant <= scale`.
183         // solving invariants in terms of `mant`, `low` and `high` yields
184         // a simpler version of the first condition: `-plus < mant < minus`.
185         // since `-plus < 0 <= mant`, we have the correct shortest representation
186         // when `mant < minus` and `2 * mant <= scale`.
187         // (the former becomes `mant <= minus` when the original mantissa is even.)
188         //
189         // when the second doesn't hold (`2 * mant > scale`), we need to increase the last digit.
190         // this is enough for restoring that condition: we already know that
191         // the digit generation guarantees `0 <= v / 10^(k-n) - d[0..n-1] < 1`.
192         // in this case, the first condition becomes `-plus < mant - scale < minus`.
193         // since `mant < scale` after the generation, we have `scale < mant + plus`.
194         // (again, this becomes `scale <= mant + plus` when the original mantissa is even.)
195         //
196         // in short:
197         // - stop and round `down` (keep digits as is) when `mant < minus` (or `<=`).
198         // - stop and round `up` (increase the last digit) when `scale < mant + plus` (or `<=`).
199         // - keep generating otherwise.
200         down = mant.cmp(&minus) < rounding;
201         up = scale.cmp(mant.clone().add(&plus)) < rounding;
202         if down || up { break; } // we have the shortest representation, proceed to the rounding
203
204         // restore the invariants.
205         // this makes the algorithm always terminating: `minus` and `plus` always increases,
206         // but `mant` is clipped modulo `scale` and `scale` is fixed.
207         mant.mul_small(10);
208         minus.mul_small(10);
209         plus.mul_small(10);
210     }
211
212     // rounding up happens when
213     // i) only the rounding-up condition was triggered, or
214     // ii) both conditions were triggered and tie breaking prefers rounding up.
215     if up && (!down || *mant.mul_pow2(1) >= scale) {
216         // if rounding up changes the length, the exponent should also change.
217         // it seems that this condition is very hard to satisfy (possibly impossible),
218         // but we are just being safe and consistent here.
219         if let Some(c) = round_up(buf, i) {
220             buf[i] = c;
221             i += 1;
222             k += 1;
223         }
224     }
225
226     (i, k)
227 }
228
229 /// The exact and fixed mode implementation for Dragon.
230 pub fn format_exact(d: &Decoded, buf: &mut [u8], limit: i16) -> (/*#digits*/ usize, /*exp*/ i16) {
231     assert!(d.mant > 0);
232     assert!(d.minus > 0);
233     assert!(d.plus > 0);
234     assert!(d.mant.checked_add(d.plus).is_some());
235     assert!(d.mant.checked_sub(d.minus).is_some());
236
237     // estimate `k_0` from original inputs satisfying `10^(k_0-1) < v <= 10^(k_0+1)`.
238     let mut k = estimate_scaling_factor(d.mant, d.exp);
239
240     // `v = mant / scale`.
241     let mut mant = Big::from_u64(d.mant);
242     let mut scale = Big::from_small(1);
243     if d.exp < 0 {
244         scale.mul_pow2(-d.exp as usize);
245     } else {
246         mant.mul_pow2(d.exp as usize);
247     }
248
249     // divide `mant` by `10^k`. now `scale / 10 < mant <= scale * 10`.
250     if k >= 0 {
251         mul_pow10(&mut scale, k as usize);
252     } else {
253         mul_pow10(&mut mant, -k as usize);
254     }
255
256     // fixup when `mant + plus >= scale`, where `plus / scale = 10^-buf.len() / 2`.
257     // in order to keep the fixed-size bignum, we actually use `mant + floor(plus) >= scale`.
258     // we are not actually modifying `scale`, since we can skip the initial multiplication instead.
259     // again with the shortest algorithm, `d[0]` can be zero but will be eventually rounded up.
260     if *div_2pow10(&mut scale.clone(), buf.len()).add(&mant) >= scale {
261         // equivalent to scaling `scale` by 10
262         k += 1;
263     } else {
264         mant.mul_small(10);
265     }
266
267     // if we are working with the last-digit limitation, we need to shorten the buffer
268     // before the actual rendering in order to avoid double rounding.
269     // note that we have to enlarge the buffer again when rounding up happens!
270     let mut len = if k < limit {
271         // oops, we cannot even produce *one* digit.
272         // this is possible when, say, we've got something like 9.5 and it's being rounded to 10.
273         // we return an empty buffer, with an exception of the later rounding-up case
274         // which occurs when `k == limit` and has to produce exactly one digit.
275         0
276     } else if ((k as i32 - limit as i32) as usize) < buf.len() {
277         (k - limit) as usize
278     } else {
279         buf.len()
280     };
281
282     if len > 0 {
283         // cache `(2, 4, 8) * scale` for digit generation.
284         // (this can be expensive, so do not calculate them when the buffer is empty.)
285         let mut scale2 = scale.clone(); scale2.mul_pow2(1);
286         let mut scale4 = scale.clone(); scale4.mul_pow2(2);
287         let mut scale8 = scale.clone(); scale8.mul_pow2(3);
288
289         for i in 0..len {
290             if mant.is_zero() { // following digits are all zeroes, we stop here
291                 // do *not* try to perform rounding! rather, fill remaining digits.
292                 for c in &mut buf[i..len] { *c = b'0'; }
293                 return (len, k);
294             }
295
296             let mut d = 0;
297             if mant >= scale8 { mant.sub(&scale8); d += 8; }
298             if mant >= scale4 { mant.sub(&scale4); d += 4; }
299             if mant >= scale2 { mant.sub(&scale2); d += 2; }
300             if mant >= scale  { mant.sub(&scale);  d += 1; }
301             debug_assert!(mant < scale);
302             debug_assert!(d < 10);
303             buf[i] = b'0' + d;
304             mant.mul_small(10);
305         }
306     }
307
308     // rounding up if we stop in the middle of digits
309     // if the following digits are exactly 5000..., check the prior digit and try to
310     // round to even (i.e. avoid rounding up when the prior digit is even).
311     let order = mant.cmp(scale.mul_small(5));
312     if order == Ordering::Greater || (order == Ordering::Equal &&
313                                       (len == 0 || buf[len-1] & 1 == 1)) {
314         // if rounding up changes the length, the exponent should also change.
315         // but we've been requested a fixed number of digits, so do not alter the buffer...
316         if let Some(c) = round_up(buf, len) {
317             // ...unless we've been requested the fixed precision instead.
318             // we also need to check that, if the original buffer was empty,
319             // the additional digit can only be added when `k == limit` (edge case).
320             k += 1;
321             if k > limit && len < buf.len() {
322                 buf[len] = c;
323                 len += 1;
324             }
325         }
326     }
327
328     (len, k)
329 }