Skip to main content

core/num/imp/
bignum.rs

1//! Custom arbitrary-precision number (bignum) implementation.
2//!
3//! This is designed to avoid the heap allocation at expense of stack memory.
4//! The most used bignum type, `Big32x40` and  `Big64x20` you can choose, is limited by 32 × 40 = 1,280 bits
5//! and will take at most 160 bytes of stack memory. This is more than enough
6//! for round-tripping all possible finite `f64` values.
7//!
8//! In principle it is possible to have multiple bignum types for different
9//! inputs, but we don't do so to avoid the code bloat. Each bignum is still
10//! tracked for the actual usages, so it normally doesn't matter.
11
12// This module is only for dec2flt and flt2dec, and only public because of coretests.
13// It is not intended to ever be stabilized.
14#![doc(hidden)]
15#![unstable(
16    feature = "core_private_bignum",
17    reason = "internal routines only exposed for testing",
18    issue = "none"
19)]
20#![macro_use]
21
22/// Arithmetic operations required by bignums.
23pub trait FullOps: Sized {
24    /// Returns `(carry', v')` such that `carry' * 2^W + v' = self * other + other2 + carry`,
25    /// where `W` is the number of bits in `Self`.
26    fn full_mul_add(self, other: Self, other2: Self, carry: Self) -> (Self /* carry */, Self);
27
28    /// Returns `(quo, rem)` such that `borrow * 2^W + self = quo * other + rem`
29    /// and `0 <= rem < other`, where `W` is the number of bits in `Self`.
30    fn full_div_rem(self, other: Self, borrow: Self)
31    -> (Self /* quotient */, Self /* remainder */);
32}
33
34macro_rules! impl_full_ops {
35    ($($ty:ty: add($addfn:path), mul/div($bigty:ident);)*) => (
36        $(
37            impl FullOps for $ty {
38                #[ferrocene::prevalidated]
39                fn full_mul_add(self, other: $ty, other2: $ty, carry: $ty) -> ($ty, $ty) {
40                    // This cannot overflow;
41                    // the output is between `0` and `2^nbits * (2^nbits - 1)`.
42                    let (lo, hi) = self.carrying_mul_add(other, other2, carry);
43                    (hi, lo)
44                }
45
46                #[ferrocene::prevalidated]
47                fn full_div_rem(self, other: $ty, borrow: $ty) -> ($ty, $ty) {
48                    debug_assert!(borrow < other);
49                    // This cannot overflow; the output is between `0` and `other * (2^nbits - 1)`.
50                    let lhs = ((borrow as $bigty) << <$ty>::BITS) | (self as $bigty);
51                    let rhs = other as $bigty;
52                    ((lhs / rhs) as $ty, (lhs % rhs) as $ty)
53                }
54            }
55        )*
56    )
57}
58
59impl_full_ops! {
60    u8:  add(intrinsics::u8_add_with_overflow),  mul/div(u16);
61    u16: add(intrinsics::u16_add_with_overflow), mul/div(u32);
62    u32: add(intrinsics::u32_add_with_overflow), mul/div(u64);
63    u64: add(intrinsics::u64_add_with_overflow), mul/div(u128);
64}
65
66/// Table of powers of 5 representable in digits. Specifically, the largest {u8, u16, u32, u64} value
67/// that's a power of five, plus the corresponding exponent. Used in `mul_pow5`.
68const SMALL_POW5: [(u64, usize); 4] =
69    [(125, 3), (15625, 6), (1_220_703_125, 13), (7_450_580_596_923_828_125, 27)];
70
71macro_rules! define_bignum {
72    ($name:ident: type=$ty:ty, n=$n:expr) => {
73        /// Stack-allocated arbitrary-precision (up to certain limit) integer.
74        ///
75        /// This is backed by a fixed-size array of given type ("digit").
76        /// While the array is not very large (normally some hundred bytes),
77        /// copying it recklessly may result in the performance hit.
78        /// Thus this is intentionally not `Copy`.
79        ///
80        /// All operations available to bignums panic in the case of overflows.
81        /// The caller is responsible to use large enough bignum types.
82        #[ferrocene::prevalidated]
83        pub struct $name {
84            /// One plus the offset to the maximum "digit" in use.
85            /// This does not decrease, so be aware of the computation order.
86            /// `base[size..]` should be zero.
87            size: usize,
88            /// Digits. `[a, b, c, ...]` represents `a + b*2^W + c*2^(2W) + ...`
89            /// where `W` is the number of bits in the digit type.
90            base: [$ty; $n],
91        }
92
93        impl $name {
94            /// Makes a bignum from one digit.
95            #[ferrocene::prevalidated]
96            pub fn from_small(v: $ty) -> $name {
97                let mut base = [0; $n];
98                base[0] = v;
99                $name { size: 1, base }
100            }
101
102            /// Makes a bignum from `u64` value.
103            #[ferrocene::prevalidated]
104            pub fn from_u64(mut v: u64) -> $name {
105                let mut base = [0; $n];
106                let mut sz = 0;
107                while v > 0 {
108                    base[sz] = v as $ty;
109                    v = v.unbounded_shr(<$ty>::BITS);
110                    sz += 1;
111                }
112                $name { size: sz, base }
113            }
114
115            /// Returns the internal digits as a slice `[a, b, c, ...]` such that the numeric
116            /// value is `a + b * 2^W + c * 2^(2W) + ...` where `W` is the number of bits in
117            /// the digit type.
118            #[ferrocene::prevalidated]
119            pub fn digits(&self) -> &[$ty] {
120                &self.base[..self.size]
121            }
122
123            /// Returns the `i`-th bit where bit 0 is the least significant one.
124            /// In other words, the bit with weight `2^i`.
125            pub fn get_bit(&self, i: usize) -> u8 {
126                let digitbits = <$ty>::BITS as usize;
127                let d = i / digitbits;
128                let b = i % digitbits;
129                ((self.base[d] >> b) & 1) as u8
130            }
131
132            /// Returns `true` if the bignum is zero.
133            #[ferrocene::prevalidated]
134            pub fn is_zero(&self) -> bool {
135                self.digits().iter().all(|&v| v == 0)
136            }
137
138            /// Returns the number of bits necessary to represent this value. Note that zero
139            /// is considered to need 0 bits.
140            pub fn bit_length(&self) -> usize {
141                let digitbits = <$ty>::BITS as usize;
142                let digits = self.digits();
143                // Find the most significant non-zero digit.
144                let msd = digits.iter().rposition(|&x| x != 0);
145                match msd {
146                    Some(msd) => msd * digitbits + digits[msd].ilog2() as usize + 1,
147                    // There are no non-zero digits, i.e., the number is zero.
148                    _ => 0,
149                }
150            }
151
152            /// Adds `other` to itself and returns its own mutable reference.
153            #[ferrocene::prevalidated]
154            pub fn add<'a>(&'a mut self, other: &$name) -> &'a mut $name {
155                use crate::{cmp, iter};
156
157                let mut sz = cmp::max(self.size, other.size);
158                let mut carry = false;
159                for (a, b) in iter::zip(&mut self.base[..sz], &other.base[..sz]) {
160                    let (v, c) = (*a).carrying_add(*b, carry);
161                    *a = v;
162                    carry = c;
163                }
164                if carry {
165                    self.base[sz] = 1;
166                    sz += 1;
167                }
168                self.size = sz;
169                self
170            }
171
172            pub fn add_small(&mut self, other: $ty) -> &mut $name {
173                let (v, mut carry) = self.base[0].carrying_add(other, false);
174                self.base[0] = v;
175                let mut i = 1;
176                while carry {
177                    let (v, c) = self.base[i].carrying_add(0, carry);
178                    self.base[i] = v;
179                    carry = c;
180                    i += 1;
181                }
182                if i > self.size {
183                    self.size = i;
184                }
185                self
186            }
187
188            /// Subtracts `other` from itself and returns its own mutable reference.
189            #[ferrocene::prevalidated]
190            pub fn sub<'a>(&'a mut self, other: &$name) -> &'a mut $name {
191                use crate::{cmp, iter};
192
193                let sz = cmp::max(self.size, other.size);
194                let mut noborrow = true;
195                for (a, b) in iter::zip(&mut self.base[..sz], &other.base[..sz]) {
196                    let (v, c) = (*a).carrying_add(!*b, noborrow);
197                    *a = v;
198                    noborrow = c;
199                }
200                assert!(noborrow);
201                self.size = sz;
202                self
203            }
204
205            /// Multiplies itself by a digit-sized `other` and returns its own
206            /// mutable reference.
207            #[ferrocene::prevalidated]
208            pub fn mul_small(&mut self, other: $ty) -> &mut $name {
209                let mut sz = self.size;
210                let mut carry = 0;
211                for a in &mut self.base[..sz] {
212                    let (v, c) = (*a).carrying_mul(other, carry);
213                    *a = v;
214                    carry = c;
215                }
216                if carry > 0 {
217                    self.base[sz] = carry;
218                    sz += 1;
219                }
220                self.size = sz;
221                self
222            }
223
224            /// Multiplies itself by `2^bits` and returns its own mutable reference.
225            #[ferrocene::prevalidated]
226            pub fn mul_pow2(&mut self, bits: usize) -> &mut $name {
227                let digitbits = <$ty>::BITS as usize;
228                let digits = bits / digitbits;
229                let bits = bits % digitbits;
230
231                assert!(digits < $n);
232                debug_assert!(self.base[$n - digits..].iter().all(|&v| v == 0));
233                debug_assert!(bits == 0 || (self.base[$n - digits - 1] >> (digitbits - bits)) == 0);
234
235                // shift by `digits * digitbits` bits
236                for i in (0..self.size).rev() {
237                    self.base[i + digits] = self.base[i];
238                }
239                for i in 0..digits {
240                    self.base[i] = 0;
241                }
242
243                // shift by `bits` bits
244                let mut sz = self.size + digits;
245                if bits > 0 {
246                    let last = sz;
247                    let overflow = self.base[last - 1] >> (digitbits - bits);
248                    if overflow > 0 {
249                        self.base[last] = overflow;
250                        sz += 1;
251                    }
252                    for i in (digits + 1..last).rev() {
253                        self.base[i] =
254                            (self.base[i] << bits) | (self.base[i - 1] >> (digitbits - bits));
255                    }
256                    self.base[digits] <<= bits;
257                    // self.base[..digits] is zero, no need to shift
258                }
259
260                self.size = sz;
261                self
262            }
263
264            /// Multiplies itself by `5^e` and returns its own mutable reference.
265            pub fn mul_pow5(&mut self, mut e: usize) -> &mut $name {
266                use crate::num::imp::bignum::SMALL_POW5;
267
268                // There are exactly n trailing zeros on 2^n, and the only relevant digit sizes
269                // are consecutive powers of two, so this is well suited index for the table.
270                let table_index = size_of::<$ty>().trailing_zeros() as usize;
271                let (small_power, small_e) = SMALL_POW5[table_index];
272                let small_power = small_power as $ty;
273
274                // Multiply with the largest single-digit power as long as possible ...
275                while e >= small_e {
276                    self.mul_small(small_power);
277                    e -= small_e;
278                }
279
280                // ... then finish off the remainder.
281                let mut rest_power = 1;
282                for _ in 0..e {
283                    rest_power *= 5;
284                }
285                self.mul_small(rest_power);
286
287                self
288            }
289
290            /// Multiplies itself by a number described by `other[0] + other[1] * 2^W +
291            /// other[2] * 2^(2W) + ...` (where `W` is the number of bits in the digit type)
292            /// and returns its own mutable reference.
293            #[ferrocene::prevalidated]
294            pub fn mul_digits<'a>(&'a mut self, other: &[$ty]) -> &'a mut $name {
295                // the internal routine. works best when aa.len() <= bb.len().
296                #[ferrocene::prevalidated]
297                fn mul_inner(ret: &mut [$ty; $n], aa: &[$ty], bb: &[$ty]) -> usize {
298                    use crate::num::imp::bignum::FullOps;
299
300                    let mut retsz = 0;
301                    for (i, &a) in aa.iter().enumerate() {
302                        if a == 0 {
303                            continue;
304                        }
305                        let mut sz = bb.len();
306                        let mut carry = 0;
307                        for (j, &b) in bb.iter().enumerate() {
308                            let (c, v) = a.full_mul_add(b, ret[i + j], carry);
309                            ret[i + j] = v;
310                            carry = c;
311                        }
312                        if carry > 0 {
313                            ret[i + sz] = carry;
314                            sz += 1;
315                        }
316                        if retsz < i + sz {
317                            retsz = i + sz;
318                        }
319                    }
320                    retsz
321                }
322
323                let mut ret = [0; $n];
324                let retsz = if self.size < other.len() {
325                    mul_inner(&mut ret, &self.digits(), other)
326                } else {
327                    mul_inner(&mut ret, other, &self.digits())
328                };
329                self.base = ret;
330                self.size = retsz;
331                self
332            }
333
334            /// Divides itself by a digit-sized `other` and returns its own
335            /// mutable reference *and* the remainder.
336            #[ferrocene::prevalidated]
337            pub fn div_rem_small(&mut self, other: $ty) -> (&mut $name, $ty) {
338                use crate::num::imp::bignum::FullOps;
339
340                assert!(other > 0);
341
342                let sz = self.size;
343                let mut borrow = 0;
344                for a in self.base[..sz].iter_mut().rev() {
345                    let (q, r) = (*a).full_div_rem(other, borrow);
346                    *a = q;
347                    borrow = r;
348                }
349                (self, borrow)
350            }
351        }
352
353        impl crate::cmp::PartialEq for $name {
354            #[ferrocene::prevalidated]
355            fn eq(&self, other: &$name) -> bool {
356                self.base[..] == other.base[..]
357            }
358        }
359
360        impl crate::cmp::Eq for $name {}
361
362        impl crate::cmp::PartialOrd for $name {
363            #[ferrocene::prevalidated]
364            fn partial_cmp(&self, other: &$name) -> crate::option::Option<crate::cmp::Ordering> {
365                crate::option::Option::Some(self.cmp(other))
366            }
367        }
368
369        impl crate::cmp::Ord for $name {
370            #[ferrocene::prevalidated]
371            fn cmp(&self, other: &$name) -> crate::cmp::Ordering {
372                use crate::cmp::max;
373                let sz = max(self.size, other.size);
374                let lhs = self.base[..sz].iter().cloned().rev();
375                let rhs = other.base[..sz].iter().cloned().rev();
376                lhs.cmp(rhs)
377            }
378        }
379
380        impl crate::clone::Clone for $name {
381            #[ferrocene::prevalidated]
382            fn clone(&self) -> Self {
383                Self { size: self.size, base: self.base }
384            }
385        }
386
387        impl crate::clone::UseCloned for $name {}
388
389        impl crate::fmt::Debug for $name {
390            #[ferrocene::prevalidated]
391            fn fmt(&self, f: &mut crate::fmt::Formatter<'_>) -> crate::fmt::Result {
392                let sz = if self.size < 1 { 1 } else { self.size };
393                let digitlen = <$ty>::BITS as usize / 4;
394
395                write!(f, "{:#x}", self.base[sz - 1])?;
396                for &v in self.base[..sz - 1].iter().rev() {
397                    write!(f, "_{:01$x}", v, digitlen)?;
398                }
399                crate::result::Result::Ok(())
400            }
401        }
402    };
403}
404
405/// the digit type for `Big32x40`
406pub type Digit32 = u32;
407
408#[cfg(any(target_pointer_width = "16", target_pointer_width = "32"))]
409define_bignum!(Big32x40: type=Digit32, n=40);
410
411/// The digit type for `Big64x20`.
412pub type Digit64 = u64;
413
414#[cfg(target_pointer_width = "64")]
415define_bignum!(Big64x20: type=Digit64, n=20);
416
417#[cfg(any(target_pointer_width = "16", target_pointer_width = "32"))]
418pub type Big = Big32x40;
419#[cfg(target_pointer_width = "64")]
420pub type Big = Big64x20;
421
422#[cfg(any(target_pointer_width = "16", target_pointer_width = "32"))]
423pub type Digit = Digit32;
424#[cfg(target_pointer_width = "64")]
425pub type Digit = Digit64;
426
427// this one is used for testing only.
428#[doc(hidden)]
429pub mod tests {
430    define_bignum!(Big8x3: type=u8, n=3);
431}