core/num/imp/flt2dec/strategy/dragon.rs
1//! Almost direct (but slightly optimized) Rust translation of Figure 3 of "Printing
2//! Floating-Point Numbers Quickly and Accurately"[^1].
3//!
4//! [^1]: Burger, R. G. and Dybvig, R. K. 1996. Printing floating-point numbers
5//! quickly and accurately. SIGPLAN Not. 31, 5 (May. 1996), 108-116.
6
7use flt2dec::estimator::estimate_scaling_factor;
8use flt2dec::{Decoded, MAX_SIG_DIGITS, round_up};
9
10use crate::cmp::Ordering;
11use crate::mem::MaybeUninit;
12use crate::num::imp::bignum::{Big, Digit};
13use crate::num::imp::flt2dec;
14
15static POW10: [Digit; 10] =
16 [1, 10, 100, 1000, 10000, 100000, 1000000, 10000000, 100000000, 1000000000];
17// precalculated arrays of `Digit`s for 5^(2^n).
18// FIXME(#162879): these tables have u64 and u32 versions, future versions may be generated by macro.
19#[cfg(target_pointer_width = "32")]
20static POW5TO16: [Digit; 2] = [0x86f26fc1, 0x23];
21#[cfg(target_pointer_width = "64")]
22static POW5TO16: [Digit; 1] = [0x2386f26fc1];
23
24#[cfg(target_pointer_width = "32")]
25static POW5TO32: [Digit; 3] = [0x85acef81, 0x2d6d415b, 0x4ee];
26#[cfg(target_pointer_width = "64")]
27static POW5TO32: [Digit; 2] = [0x2d6d415b85acef81, 0x4ee];
28
29#[cfg(target_pointer_width = "32")]
30static POW5TO64: [Digit; 5] = [0xbf6a1f01, 0x6e38ed64, 0xdaa797ed, 0xe93ff9f4, 0x184f03];
31#[cfg(target_pointer_width = "64")]
32static POW5TO64: [Digit; 3] = [0x6e38ed64bf6a1f01, 0xe93ff9f4daa797ed, 0x184f03];
33
34#[cfg(target_pointer_width = "32")]
35static POW5TO128: [Digit; 10] = [
36 0x2e953e01, 0x3df9909, 0xf1538fd, 0x2374e42f, 0xd3cff5ec, 0xc404dc08, 0xbccdb0da, 0xa6337f19,
37 0xe91f2603, 0x24e,
38];
39#[cfg(target_pointer_width = "64")]
40static POW5TO128: [Digit; 5] =
41 [0x3df99092e953e01, 0x2374e42f0f1538fd, 0xc404dc08d3cff5ec, 0xa6337f19bccdb0da, 0x24ee91f2603];
42
43#[cfg(target_pointer_width = "32")]
44static POW5TO256: [Digit; 19] = [
45 0x982e7c01, 0xbed3875b, 0xd8d99f72, 0x12152f87, 0x6bde50c6, 0xcf4a6e70, 0xd595d80f, 0x26b2716e,
46 0xadc666b0, 0x1d153624, 0x3c42d35a, 0x63ff540e, 0xcc5573c0, 0x65f9ef17, 0x55bc28f2, 0x80dcc7f7,
47 0xf46eeddc, 0x5fdcefce, 0x553f7,
48];
49#[cfg(target_pointer_width = "64")]
50static POW5TO256: [Digit; 10] = [
51 0xbed3875b982e7c01,
52 0x12152f87d8d99f72,
53 0xcf4a6e706bde50c6,
54 0x26b2716ed595d80f,
55 0x1d153624adc666b0,
56 0x63ff540e3c42d35a,
57 0x65f9ef17cc5573c0,
58 0x80dcc7f755bc28f2,
59 0x5fdcefcef46eeddc,
60 0x553f7,
61];
62
63#[doc(hidden)]
64pub fn mul_pow10(x: &mut Big, n: usize) -> &mut Big {
65 debug_assert!(n < 512);
66 // Save ourself the left shift for the smallest cases.
67 if n < 8 {
68 return x.mul_small(POW10[n & 7]);
69 }
70 // Multiply by the powers of 5 and shift the 2s in at the end.
71 // This keeps the intermediate products smaller and faster.
72 if n & 7 != 0 {
73 x.mul_small(POW10[n & 7] >> (n & 7));
74 }
75 if n & 8 != 0 {
76 x.mul_small(POW10[8] >> 8);
77 }
78 if n & 16 != 0 {
79 x.mul_digits(&POW5TO16);
80 }
81 if n & 32 != 0 {
82 x.mul_digits(&POW5TO32);
83 }
84 if n & 64 != 0 {
85 x.mul_digits(&POW5TO64);
86 }
87 if n & 128 != 0 {
88 x.mul_digits(&POW5TO128);
89 }
90 if n & 256 != 0 {
91 x.mul_digits(&POW5TO256);
92 }
93 x.mul_pow2(n)
94}
95
96fn div_2pow10(x: &mut Big, mut n: usize) -> &mut Big {
97 let largest = POW10.len() - 1;
98 while n > largest {
99 x.div_rem_small(POW10[largest]);
100 n -= largest;
101 }
102 x.div_rem_small(POW10[n] << 1);
103 x
104}
105
106// only usable when `x < 16 * scale`; `scaleN` should be `scale.mul_small(N)`
107fn div_rem_upto_16<'a>(
108 x: &'a mut Big,
109 scale: &Big,
110 scale2: &Big,
111 scale4: &Big,
112 scale8: &Big,
113) -> (u8, &'a mut Big) {
114 let mut d = 0;
115 if *x >= *scale8 {
116 x.sub(scale8);
117 d += 8;
118 }
119 if *x >= *scale4 {
120 x.sub(scale4);
121 d += 4;
122 }
123 if *x >= *scale2 {
124 x.sub(scale2);
125 d += 2;
126 }
127 if *x >= *scale {
128 x.sub(scale);
129 d += 1;
130 }
131 debug_assert!(*x < *scale);
132 (d, x)
133}
134
135/// The shortest mode implementation for Dragon.
136pub fn format_shortest<'a>(
137 d: &Decoded,
138 buf: &'a mut [MaybeUninit<u8>],
139) -> (/*digits*/ &'a [u8], /*exp*/ i16) {
140 // the number `v` to format is known to be:
141 // - equal to `mant * 2^exp`;
142 // - preceded by `(mant - 2 * minus) * 2^exp` in the original type; and
143 // - followed by `(mant + 2 * plus) * 2^exp` in the original type.
144 //
145 // obviously, `minus` and `plus` cannot be zero. (for infinities, we use out-of-range values.)
146 // also we assume that at least one digit is generated, i.e., `mant` cannot be zero too.
147 //
148 // this also means that any number between `low = (mant - minus) * 2^exp` and
149 // `high = (mant + plus) * 2^exp` will map to this exact floating point number,
150 // with bounds included when the original mantissa was even (i.e., `!mant_was_odd`).
151
152 assert!(d.mant > 0);
153 assert!(d.minus > 0);
154 assert!(d.plus > 0);
155 assert!(d.mant.checked_add(d.plus).is_some());
156 assert!(d.mant.checked_sub(d.minus).is_some());
157 assert!(buf.len() >= MAX_SIG_DIGITS);
158
159 // `a.cmp(&b) < rounding` is `if d.inclusive {a <= b} else {a < b}`
160 let rounding = if d.inclusive { Ordering::Greater } else { Ordering::Equal };
161
162 // estimate `k_0` from original inputs satisfying `10^(k_0-1) < high <= 10^(k_0+1)`.
163 // the tight bound `k` satisfying `10^(k-1) < high <= 10^k` is calculated later.
164 let mut k = estimate_scaling_factor(d.mant + d.plus, d.exp);
165
166 // convert `{mant, plus, minus} * 2^exp` into the fractional form so that:
167 // - `v = mant / scale`
168 // - `low = (mant - minus) / scale`
169 // - `high = (mant + plus) / scale`
170 let mut mant = Big::from_u64(d.mant);
171 let mut minus = Big::from_u64(d.minus);
172 let mut plus = Big::from_u64(d.plus);
173 let mut scale = Big::from_small(1);
174 if d.exp < 0 {
175 scale.mul_pow2(-d.exp as usize);
176 } else {
177 mant.mul_pow2(d.exp as usize);
178 minus.mul_pow2(d.exp as usize);
179 plus.mul_pow2(d.exp as usize);
180 }
181
182 // divide `mant` by `10^k`. now `scale / 10 < mant + plus <= scale * 10`.
183 if k >= 0 {
184 mul_pow10(&mut scale, k as usize);
185 } else {
186 mul_pow10(&mut mant, -k as usize);
187 mul_pow10(&mut minus, -k as usize);
188 mul_pow10(&mut plus, -k as usize);
189 }
190
191 // fixup when `mant + plus > scale` (or `>=`).
192 // we are not actually modifying `scale`, since we can skip the initial multiplication instead.
193 // now `scale < mant + plus <= scale * 10` and we are ready to generate digits.
194 //
195 // note that `d[0]` *can* be zero, when `scale - plus < mant < scale`.
196 // in this case rounding-up condition (`up` below) will be triggered immediately.
197 if scale.cmp(mant.clone().add(&plus)) < rounding {
198 // equivalent to scaling `scale` by 10
199 k += 1;
200 } else {
201 mant.mul_small(10);
202 minus.mul_small(10);
203 plus.mul_small(10);
204 }
205
206 // cache `(2, 4, 8) * scale` for digit generation.
207 let mut scale2 = scale.clone();
208 scale2.mul_pow2(1);
209 let mut scale4 = scale.clone();
210 scale4.mul_pow2(2);
211 let mut scale8 = scale.clone();
212 scale8.mul_pow2(3);
213
214 let mut down;
215 let mut up;
216 let mut i = 0;
217 loop {
218 // invariants, where `d[0..n-1]` are digits generated so far:
219 // - `v = mant / scale * 10^(k-n-1) + d[0..n-1] * 10^(k-n)`
220 // - `v - low = minus / scale * 10^(k-n-1)`
221 // - `high - v = plus / scale * 10^(k-n-1)`
222 // - `(mant + plus) / scale <= 10` (thus `mant / scale < 10`)
223 // where `d[i..j]` is a shorthand for `d[i] * 10^(j-i) + ... + d[j-1] * 10 + d[j]`.
224
225 // generate one digit: `d[n] = floor(mant / scale) < 10`.
226 let (d, _) = div_rem_upto_16(&mut mant, &scale, &scale2, &scale4, &scale8);
227 debug_assert!(d < 10);
228 buf[i] = MaybeUninit::new(b'0' + d);
229 i += 1;
230
231 // this is a simplified description of the modified Dragon algorithm.
232 // many intermediate derivations and completeness arguments are omitted for convenience.
233 //
234 // start with modified invariants, as we've updated `n`:
235 // - `v = mant / scale * 10^(k-n) + d[0..n-1] * 10^(k-n)`
236 // - `v - low = minus / scale * 10^(k-n)`
237 // - `high - v = plus / scale * 10^(k-n)`
238 //
239 // assume that `d[0..n-1]` is the shortest representation between `low` and `high`,
240 // i.e., `d[0..n-1]` satisfies both of the following but `d[0..n-2]` doesn't:
241 // - `low < d[0..n-1] * 10^(k-n) < high` (bijectivity: digits round to `v`); and
242 // - `abs(v / 10^(k-n) - d[0..n-1]) <= 1/2` (the last digit is correct).
243 //
244 // the second condition simplifies to `2 * mant <= scale`.
245 // solving invariants in terms of `mant`, `low` and `high` yields
246 // a simpler version of the first condition: `-plus < mant < minus`.
247 // since `-plus < 0 <= mant`, we have the correct shortest representation
248 // when `mant < minus` and `2 * mant <= scale`.
249 // (the former becomes `mant <= minus` when the original mantissa is even.)
250 //
251 // when the second doesn't hold (`2 * mant > scale`), we need to increase the last digit.
252 // this is enough for restoring that condition: we already know that
253 // the digit generation guarantees `0 <= v / 10^(k-n) - d[0..n-1] < 1`.
254 // in this case, the first condition becomes `-plus < mant - scale < minus`.
255 // since `mant < scale` after the generation, we have `scale < mant + plus`.
256 // (again, this becomes `scale <= mant + plus` when the original mantissa is even.)
257 //
258 // in short:
259 // - stop and round `down` (keep digits as is) when `mant < minus` (or `<=`).
260 // - stop and round `up` (increase the last digit) when `scale < mant + plus` (or `<=`).
261 // - keep generating otherwise.
262 down = mant.cmp(&minus) < rounding;
263 up = scale.cmp(mant.clone().add(&plus)) < rounding;
264 if down || up {
265 break;
266 } // we have the shortest representation, proceed to the rounding
267
268 // restore the invariants.
269 // this makes the algorithm always terminating: `minus` and `plus` always increases,
270 // but `mant` is clipped modulo `scale` and `scale` is fixed.
271 mant.mul_small(10);
272 minus.mul_small(10);
273 plus.mul_small(10);
274 }
275
276 // rounding up happens when
277 // i) only the rounding-up condition was triggered, or
278 // ii) both conditions were triggered and tie breaking prefers rounding up.
279 if up && (!down || *mant.mul_pow2(1) >= scale) {
280 // if rounding up changes the length, the exponent should also change.
281 // it seems that this condition is very hard to satisfy (possibly impossible),
282 // but we are just being safe and consistent here.
283 // SAFETY: we initialized that memory above.
284 if let Some(c) = round_up(unsafe { buf[..i].assume_init_mut() }) {
285 buf[i] = MaybeUninit::new(c);
286 i += 1;
287 k += 1;
288 }
289 }
290
291 // SAFETY: we initialized that memory above.
292 (unsafe { buf[..i].assume_init_ref() }, k)
293}
294
295/// The exact and fixed mode implementation for Dragon.
296pub fn format_exact<'a>(
297 d: &Decoded,
298 buf: &'a mut [MaybeUninit<u8>],
299 limit: i16,
300) -> (/*digits*/ &'a [u8], /*exp*/ i16) {
301 assert!(d.mant > 0);
302 assert!(d.minus > 0);
303 assert!(d.plus > 0);
304 assert!(d.mant.checked_add(d.plus).is_some());
305 assert!(d.mant.checked_sub(d.minus).is_some());
306
307 // estimate `k_0` from original inputs satisfying `10^(k_0-1) < v <= 10^(k_0+1)`.
308 let mut k = estimate_scaling_factor(d.mant, d.exp);
309
310 // `v = mant / scale`.
311 let mut mant = Big::from_u64(d.mant);
312 let mut scale = Big::from_small(1);
313 if d.exp < 0 {
314 scale.mul_pow2(-d.exp as usize);
315 } else {
316 mant.mul_pow2(d.exp as usize);
317 }
318
319 // divide `mant` by `10^k`. now `scale / 10 < mant <= scale * 10`.
320 if k >= 0 {
321 mul_pow10(&mut scale, k as usize);
322 } else {
323 mul_pow10(&mut mant, -k as usize);
324 }
325
326 // fixup when `mant + plus >= scale`, where `plus / scale = 10^-buf.len() / 2`.
327 // in order to keep the fixed-size bignum, we actually use `mant + floor(plus) >= scale`.
328 // we are not actually modifying `scale`, since we can skip the initial multiplication instead.
329 // again with the shortest algorithm, `d[0]` can be zero but will be eventually rounded up.
330 if *div_2pow10(&mut scale.clone(), buf.len()).add(&mant) >= scale {
331 // equivalent to scaling `scale` by 10
332 k += 1;
333 } else {
334 mant.mul_small(10);
335 }
336
337 // if we are working with the last-digit limitation, we need to shorten the buffer
338 // before the actual rendering in order to avoid double rounding.
339 // note that we have to enlarge the buffer again when rounding up happens!
340 let mut len = if k < limit {
341 // oops, we cannot even produce *one* digit.
342 // this is possible when, say, we've got something like 9.5 and it's being rounded to 10.
343 // we return an empty buffer, with an exception of the later rounding-up case
344 // which occurs when `k == limit` and has to produce exactly one digit.
345 0
346 } else if ((k as i32 - limit as i32) as usize) < buf.len() {
347 (k - limit) as usize
348 } else {
349 buf.len()
350 };
351
352 if len > 0 {
353 // cache `(2, 4, 8) * scale` for digit generation.
354 // (this can be expensive, so do not calculate them when the buffer is empty.)
355 let mut scale2 = scale.clone();
356 scale2.mul_pow2(1);
357 let mut scale4 = scale.clone();
358 scale4.mul_pow2(2);
359 let mut scale8 = scale.clone();
360 scale8.mul_pow2(3);
361
362 for i in 0..len {
363 if mant.is_zero() {
364 // following digits are all zeroes, we stop here
365 // do *not* try to perform rounding! rather, fill remaining digits.
366 for c in &mut buf[i..len] {
367 *c = MaybeUninit::new(b'0');
368 }
369 // SAFETY: we initialized that memory above.
370 return (unsafe { buf[..len].assume_init_ref() }, k);
371 }
372
373 let mut d = 0;
374 if mant >= scale8 {
375 mant.sub(&scale8);
376 d += 8;
377 }
378 if mant >= scale4 {
379 mant.sub(&scale4);
380 d += 4;
381 }
382 if mant >= scale2 {
383 mant.sub(&scale2);
384 d += 2;
385 }
386 if mant >= scale {
387 mant.sub(&scale);
388 d += 1;
389 }
390 debug_assert!(mant < scale);
391 debug_assert!(d < 10);
392 buf[i] = MaybeUninit::new(b'0' + d);
393 mant.mul_small(10);
394 }
395 }
396
397 // rounding up if we stop in the middle of digits
398 // if the following digits are exactly 5000..., check the prior digit and try to
399 // round to even (i.e., avoid rounding up when the prior digit is even).
400 let order = mant.cmp(scale.mul_small(5));
401 if order == Ordering::Greater
402 || (order == Ordering::Equal
403 // SAFETY: `buf[len-1]` is initialized.
404 && len > 0 && unsafe { buf[len - 1].assume_init() } & 1 == 1)
405 {
406 // if rounding up changes the length, the exponent should also change.
407 // but we've been requested a fixed number of digits, so do not alter the buffer...
408 // SAFETY: we initialized that memory above.
409 if let Some(c) = round_up(unsafe { buf[..len].assume_init_mut() }) {
410 // ...unless we've been requested the fixed precision instead.
411 // we also need to check that, if the original buffer was empty,
412 // the additional digit can only be added when `k == limit` (edge case).
413 k += 1;
414 if k > limit && len < buf.len() {
415 buf[len] = MaybeUninit::new(c);
416 len += 1;
417 }
418 }
419 }
420
421 // SAFETY: we initialized that memory above.
422 (unsafe { buf[..len].assume_init_ref() }, k)
423}