Skip to main content

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(any(target_pointer_width = "16", target_pointer_width = "32"))]
20static POW5TO16: [Digit; 2] = [0x86f26fc1, 0x23];
21#[cfg(target_pointer_width = "64")]
22static POW5TO16: [Digit; 1] = [0x2386f26fc1];
23
24#[cfg(any(target_pointer_width = "16", 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(any(target_pointer_width = "16", 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(any(target_pointer_width = "16", 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(any(target_pointer_width = "16", 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)]
64#[ferrocene::prevalidated]
65pub fn mul_pow10(x: &mut Big, n: usize) -> &mut Big {
66    debug_assert!(n < 512);
67    // Save ourself the left shift for the smallest cases.
68    if n < 8 {
69        return x.mul_small(POW10[n & 7]);
70    }
71    // Multiply by the powers of 5 and shift the 2s in at the end.
72    // This keeps the intermediate products smaller and faster.
73    if n & 7 != 0 {
74        x.mul_small(POW10[n & 7] >> (n & 7));
75    }
76    if n & 8 != 0 {
77        x.mul_small(POW10[8] >> 8);
78    }
79    if n & 16 != 0 {
80        x.mul_digits(&POW5TO16);
81    }
82    if n & 32 != 0 {
83        x.mul_digits(&POW5TO32);
84    }
85    if n & 64 != 0 {
86        x.mul_digits(&POW5TO64);
87    }
88    if n & 128 != 0 {
89        x.mul_digits(&POW5TO128);
90    }
91    if n & 256 != 0 {
92        x.mul_digits(&POW5TO256);
93    }
94    x.mul_pow2(n)
95}
96
97#[ferrocene::prevalidated]
98fn div_2pow10(x: &mut Big, mut n: usize) -> &mut Big {
99    let largest = POW10.len() - 1;
100    while n > largest {
101        x.div_rem_small(POW10[largest]);
102        n -= largest;
103    }
104    x.div_rem_small(POW10[n] << 1);
105    x
106}
107
108// only usable when `x < 16 * scale`; `scaleN` should be `scale.mul_small(N)`
109#[ferrocene::prevalidated]
110fn div_rem_upto_16<'a>(
111    x: &'a mut Big,
112    scale: &Big,
113    scale2: &Big,
114    scale4: &Big,
115    scale8: &Big,
116) -> (u8, &'a mut Big) {
117    let mut d = 0;
118    if *x >= *scale8 {
119        x.sub(scale8);
120        d += 8;
121    }
122    if *x >= *scale4 {
123        x.sub(scale4);
124        d += 4;
125    }
126    if *x >= *scale2 {
127        x.sub(scale2);
128        d += 2;
129    }
130    if *x >= *scale {
131        x.sub(scale);
132        d += 1;
133    }
134    debug_assert!(*x < *scale);
135    (d, x)
136}
137
138/// The shortest mode implementation for Dragon.
139#[ferrocene::prevalidated]
140pub fn format_shortest<'a>(
141    d: &Decoded,
142    buf: &'a mut [MaybeUninit<u8>],
143) -> (/*digits*/ &'a [u8], /*exp*/ i16) {
144    // the number `v` to format is known to be:
145    // - equal to `mant * 2^exp`;
146    // - preceded by `(mant - 2 * minus) * 2^exp` in the original type; and
147    // - followed by `(mant + 2 * plus) * 2^exp` in the original type.
148    //
149    // obviously, `minus` and `plus` cannot be zero. (for infinities, we use out-of-range values.)
150    // also we assume that at least one digit is generated, i.e., `mant` cannot be zero too.
151    //
152    // this also means that any number between `low = (mant - minus) * 2^exp` and
153    // `high = (mant + plus) * 2^exp` will map to this exact floating point number,
154    // with bounds included when the original mantissa was even (i.e., `!mant_was_odd`).
155
156    assert!(d.mant > 0);
157    assert!(d.minus > 0);
158    assert!(d.plus > 0);
159    assert!(d.mant.checked_add(d.plus).is_some());
160    assert!(d.mant.checked_sub(d.minus).is_some());
161    assert!(buf.len() >= MAX_SIG_DIGITS);
162
163    // `a.cmp(&b) < rounding` is `if d.inclusive {a <= b} else {a < b}`
164    let rounding = if d.inclusive { Ordering::Greater } else { Ordering::Equal };
165
166    // estimate `k_0` from original inputs satisfying `10^(k_0-1) < high <= 10^(k_0+1)`.
167    // the tight bound `k` satisfying `10^(k-1) < high <= 10^k` is calculated later.
168    let mut k = estimate_scaling_factor(d.mant + d.plus, d.exp);
169
170    // convert `{mant, plus, minus} * 2^exp` into the fractional form so that:
171    // - `v = mant / scale`
172    // - `low = (mant - minus) / scale`
173    // - `high = (mant + plus) / scale`
174    let mut mant = Big::from_u64(d.mant);
175    let mut minus = Big::from_u64(d.minus);
176    let mut plus = Big::from_u64(d.plus);
177    let mut scale = Big::from_small(1);
178    if d.exp < 0 {
179        scale.mul_pow2(-d.exp as usize);
180    } else {
181        mant.mul_pow2(d.exp as usize);
182        minus.mul_pow2(d.exp as usize);
183        plus.mul_pow2(d.exp as usize);
184    }
185
186    // divide `mant` by `10^k`. now `scale / 10 < mant + plus <= scale * 10`.
187    if k >= 0 {
188        mul_pow10(&mut scale, k as usize);
189    } else {
190        mul_pow10(&mut mant, -k as usize);
191        mul_pow10(&mut minus, -k as usize);
192        mul_pow10(&mut plus, -k as usize);
193    }
194
195    // fixup when `mant + plus > scale` (or `>=`).
196    // we are not actually modifying `scale`, since we can skip the initial multiplication instead.
197    // now `scale < mant + plus <= scale * 10` and we are ready to generate digits.
198    //
199    // note that `d[0]` *can* be zero, when `scale - plus < mant < scale`.
200    // in this case rounding-up condition (`up` below) will be triggered immediately.
201    if scale.cmp(mant.clone().add(&plus)) < rounding {
202        // equivalent to scaling `scale` by 10
203        k += 1;
204    } else {
205        mant.mul_small(10);
206        minus.mul_small(10);
207        plus.mul_small(10);
208    }
209
210    // cache `(2, 4, 8) * scale` for digit generation.
211    let mut scale2 = scale.clone();
212    scale2.mul_pow2(1);
213    let mut scale4 = scale.clone();
214    scale4.mul_pow2(2);
215    let mut scale8 = scale.clone();
216    scale8.mul_pow2(3);
217
218    let mut down;
219    let mut up;
220    let mut i = 0;
221    loop {
222        // invariants, where `d[0..n-1]` are digits generated so far:
223        // - `v = mant / scale * 10^(k-n-1) + d[0..n-1] * 10^(k-n)`
224        // - `v - low = minus / scale * 10^(k-n-1)`
225        // - `high - v = plus / scale * 10^(k-n-1)`
226        // - `(mant + plus) / scale <= 10` (thus `mant / scale < 10`)
227        // where `d[i..j]` is a shorthand for `d[i] * 10^(j-i) + ... + d[j-1] * 10 + d[j]`.
228
229        // generate one digit: `d[n] = floor(mant / scale) < 10`.
230        let (d, _) = div_rem_upto_16(&mut mant, &scale, &scale2, &scale4, &scale8);
231        debug_assert!(d < 10);
232        buf[i] = MaybeUninit::new(b'0' + d);
233        i += 1;
234
235        // this is a simplified description of the modified Dragon algorithm.
236        // many intermediate derivations and completeness arguments are omitted for convenience.
237        //
238        // start with modified invariants, as we've updated `n`:
239        // - `v = mant / scale * 10^(k-n) + d[0..n-1] * 10^(k-n)`
240        // - `v - low = minus / scale * 10^(k-n)`
241        // - `high - v = plus / scale * 10^(k-n)`
242        //
243        // assume that `d[0..n-1]` is the shortest representation between `low` and `high`,
244        // i.e., `d[0..n-1]` satisfies both of the following but `d[0..n-2]` doesn't:
245        // - `low < d[0..n-1] * 10^(k-n) < high` (bijectivity: digits round to `v`); and
246        // - `abs(v / 10^(k-n) - d[0..n-1]) <= 1/2` (the last digit is correct).
247        //
248        // the second condition simplifies to `2 * mant <= scale`.
249        // solving invariants in terms of `mant`, `low` and `high` yields
250        // a simpler version of the first condition: `-plus < mant < minus`.
251        // since `-plus < 0 <= mant`, we have the correct shortest representation
252        // when `mant < minus` and `2 * mant <= scale`.
253        // (the former becomes `mant <= minus` when the original mantissa is even.)
254        //
255        // when the second doesn't hold (`2 * mant > scale`), we need to increase the last digit.
256        // this is enough for restoring that condition: we already know that
257        // the digit generation guarantees `0 <= v / 10^(k-n) - d[0..n-1] < 1`.
258        // in this case, the first condition becomes `-plus < mant - scale < minus`.
259        // since `mant < scale` after the generation, we have `scale < mant + plus`.
260        // (again, this becomes `scale <= mant + plus` when the original mantissa is even.)
261        //
262        // in short:
263        // - stop and round `down` (keep digits as is) when `mant < minus` (or `<=`).
264        // - stop and round `up` (increase the last digit) when `scale < mant + plus` (or `<=`).
265        // - keep generating otherwise.
266        down = mant.cmp(&minus) < rounding;
267        up = scale.cmp(mant.clone().add(&plus)) < rounding;
268        if down || up {
269            break;
270        } // we have the shortest representation, proceed to the rounding
271
272        // restore the invariants.
273        // this makes the algorithm always terminating: `minus` and `plus` always increases,
274        // but `mant` is clipped modulo `scale` and `scale` is fixed.
275        mant.mul_small(10);
276        minus.mul_small(10);
277        plus.mul_small(10);
278    }
279
280    // rounding up happens when
281    // i) only the rounding-up condition was triggered, or
282    // ii) both conditions were triggered and tie breaking prefers rounding up.
283    if up && (!down || *mant.mul_pow2(1) >= scale) {
284        #[ferrocene::annotation(
285            "If we get here, that means three things:
286                1. Our input `d` is within 1 ULP of `10.pow(k) * .999...` repeating, for some k.
287                2. We chose to round up and represent the string as `1.00000...` repeating, for `i` significant digits.
288                3. Since we are in `format_shortest`, we did something wrong. The correct representation here is `1.0`, not `1.0000...` repeating.
289
290            Therefore correctness is already out the window.
291            If the implementation is correct, this block is unreachable.
292            If it's incorrect, we do a best-effort attempt to avoid panics and memory corruption, but do not make any guarantees about the output (we can't).
293
294            Memory safety: `c` is initialized, and `buf[i]` will panic if `i` is out of bounds.
295            Panics: We statically know that `i` is in-bounds because of the `assert!(buf.len() >= MAX_SIG_DIGITS)` at the top of this function."
296        )]
297        // if rounding up changes the length, the exponent should also change.
298        // it seems that this condition is very hard to satisfy (possibly impossible),
299        // but we are just being safe and consistent here.
300        // SAFETY: we initialized that memory above.
301        if let Some(c) = round_up(unsafe { buf[..i].assume_init_mut() }) {
302            buf[i] = MaybeUninit::new(c);
303            i += 1;
304            k += 1;
305
306            #[cfg(feature = "ferrocene_test")]
307            unreachable!();
308        }
309    }
310
311    // SAFETY: we initialized that memory above.
312    (unsafe { buf[..i].assume_init_ref() }, k)
313}
314
315/// The exact and fixed mode implementation for Dragon.
316#[ferrocene::prevalidated]
317pub fn format_exact<'a>(
318    d: &Decoded,
319    buf: &'a mut [MaybeUninit<u8>],
320    limit: i16,
321) -> (/*digits*/ &'a [u8], /*exp*/ i16) {
322    assert!(d.mant > 0);
323    assert!(d.minus > 0);
324    assert!(d.plus > 0);
325    assert!(d.mant.checked_add(d.plus).is_some());
326    assert!(d.mant.checked_sub(d.minus).is_some());
327
328    // estimate `k_0` from original inputs satisfying `10^(k_0-1) < v <= 10^(k_0+1)`.
329    let mut k = estimate_scaling_factor(d.mant, d.exp);
330
331    // `v = mant / scale`.
332    let mut mant = Big::from_u64(d.mant);
333    let mut scale = Big::from_small(1);
334    if d.exp < 0 {
335        scale.mul_pow2(-d.exp as usize);
336    } else {
337        mant.mul_pow2(d.exp as usize);
338    }
339
340    // divide `mant` by `10^k`. now `scale / 10 < mant <= scale * 10`.
341    if k >= 0 {
342        mul_pow10(&mut scale, k as usize);
343    } else {
344        mul_pow10(&mut mant, -k as usize);
345    }
346
347    // fixup when `mant + plus >= scale`, where `plus / scale = 10^-buf.len() / 2`.
348    // in order to keep the fixed-size bignum, we actually use `mant + floor(plus) >= scale`.
349    // we are not actually modifying `scale`, since we can skip the initial multiplication instead.
350    // again with the shortest algorithm, `d[0]` can be zero but will be eventually rounded up.
351    if *div_2pow10(&mut scale.clone(), buf.len()).add(&mant) >= scale {
352        // equivalent to scaling `scale` by 10
353        k += 1;
354    } else {
355        mant.mul_small(10);
356    }
357
358    // if we are working with the last-digit limitation, we need to shorten the buffer
359    // before the actual rendering in order to avoid double rounding.
360    // note that we have to enlarge the buffer again when rounding up happens!
361    let mut len = if k < limit {
362        // oops, we cannot even produce *one* digit.
363        // this is possible when, say, we've got something like 9.5 and it's being rounded to 10.
364        // we return an empty buffer, with an exception of the later rounding-up case
365        // which occurs when `k == limit` and has to produce exactly one digit.
366        0
367    } else if ((k as i32 - limit as i32) as usize) < buf.len() {
368        (k - limit) as usize
369    } else {
370        buf.len()
371    };
372
373    if len > 0 {
374        // cache `(2, 4, 8) * scale` for digit generation.
375        // (this can be expensive, so do not calculate them when the buffer is empty.)
376        let mut scale2 = scale.clone();
377        scale2.mul_pow2(1);
378        let mut scale4 = scale.clone();
379        scale4.mul_pow2(2);
380        let mut scale8 = scale.clone();
381        scale8.mul_pow2(3);
382
383        for i in 0..len {
384            if mant.is_zero() {
385                // following digits are all zeroes, we stop here
386                // do *not* try to perform rounding! rather, fill remaining digits.
387                for c in &mut buf[i..len] {
388                    *c = MaybeUninit::new(b'0');
389                }
390                // SAFETY: we initialized that memory above.
391                return (unsafe { buf[..len].assume_init_ref() }, k);
392            }
393
394            let mut d = 0;
395            if mant >= scale8 {
396                mant.sub(&scale8);
397                d += 8;
398            }
399            if mant >= scale4 {
400                mant.sub(&scale4);
401                d += 4;
402            }
403            if mant >= scale2 {
404                mant.sub(&scale2);
405                d += 2;
406            }
407            if mant >= scale {
408                mant.sub(&scale);
409                d += 1;
410            }
411            debug_assert!(mant < scale);
412            debug_assert!(d < 10);
413            buf[i] = MaybeUninit::new(b'0' + d);
414            mant.mul_small(10);
415        }
416    }
417
418    // rounding up if we stop in the middle of digits
419    // if the following digits are exactly 5000..., check the prior digit and try to
420    // round to even (i.e., avoid rounding up when the prior digit is even).
421    let order = mant.cmp(scale.mul_small(5));
422    if order == Ordering::Greater
423        || (order == Ordering::Equal
424            // SAFETY: `buf[len-1]` is initialized.
425            && len > 0 && unsafe { buf[len - 1].assume_init() } & 1 == 1)
426    {
427        // if rounding up changes the length, the exponent should also change.
428        // but we've been requested a fixed number of digits, so do not alter the buffer...
429        // SAFETY: we initialized that memory above.
430        if let Some(c) = round_up(unsafe { buf[..len].assume_init_mut() }) {
431            // ...unless we've been requested the fixed precision instead.
432            // we also need to check that, if the original buffer was empty,
433            // the additional digit can only be added when `k == limit` (edge case).
434            k += 1;
435            if k > limit && len < buf.len() {
436                buf[len] = MaybeUninit::new(c);
437                len += 1;
438            }
439        }
440    }
441
442    // SAFETY: we initialized that memory above.
443    (unsafe { buf[..len].assume_init_ref() }, k)
444}