1#![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
22pub trait FullOps: Sized {
24 fn full_mul_add(self, other: Self, other2: Self, carry: Self) -> (Self , Self);
27
28 fn full_div_rem(self, other: Self, borrow: Self)
31 -> (Self , Self );
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 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 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
66const 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 #[ferrocene::prevalidated]
83 pub struct $name {
84 size: usize,
88 base: [$ty; $n],
91 }
92
93 impl $name {
94 #[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 #[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 #[ferrocene::prevalidated]
119 pub fn digits(&self) -> &[$ty] {
120 &self.base[..self.size]
121 }
122
123 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 #[ferrocene::prevalidated]
134 pub fn is_zero(&self) -> bool {
135 self.digits().iter().all(|&v| v == 0)
136 }
137
138 pub fn bit_length(&self) -> usize {
141 let digitbits = <$ty>::BITS as usize;
142 let digits = self.digits();
143 let msd = digits.iter().rposition(|&x| x != 0);
145 match msd {
146 Some(msd) => msd * digitbits + digits[msd].ilog2() as usize + 1,
147 _ => 0,
149 }
150 }
151
152 #[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 #[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 #[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 #[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 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 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 }
259
260 self.size = sz;
261 self
262 }
263
264 pub fn mul_pow5(&mut self, mut e: usize) -> &mut $name {
266 use crate::num::imp::bignum::SMALL_POW5;
267
268 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 while e >= small_e {
276 self.mul_small(small_power);
277 e -= small_e;
278 }
279
280 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 #[ferrocene::prevalidated]
294 pub fn mul_digits<'a>(&'a mut self, other: &[$ty]) -> &'a mut $name {
295 #[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 #[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
405pub type Digit32 = u32;
407
408#[cfg(any(target_pointer_width = "16", target_pointer_width = "32"))]
409define_bignum!(Big32x40: type=Digit32, n=40);
410
411pub 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#[doc(hidden)]
429pub mod tests {
430 define_bignum!(Big8x3: type=u8, n=3);
431}