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