1 use crate::big_digit::{self, BigDigit};
2 use crate::std_alloc::{String, Vec};
3
4 use core::cmp;
5 use core::cmp::Ordering;
6 use core::default::Default;
7 use core::fmt;
8 use core::hash;
9 use core::mem;
10 use core::str;
11 use core::{u32, u64, u8};
12
13 use num_integer::{Integer, Roots};
14 use num_traits::{Num, One, Pow, ToPrimitive, Unsigned, Zero};
15
16 mod addition;
17 mod division;
18 mod multiplication;
19 mod subtraction;
20
21 mod bits;
22 mod convert;
23 mod iter;
24 mod monty;
25 mod power;
26 mod shift;
27
28 #[cfg(any(feature = "quickcheck", feature = "arbitrary"))]
29 mod arbitrary;
30
31 #[cfg(feature = "serde")]
32 mod serde;
33
34 pub(crate) use self::convert::to_str_radix_reversed;
35 pub use self::iter::{U32Digits, U64Digits};
36
37 /// A big unsigned integer type.
38 pub struct BigUint {
39 data: Vec<BigDigit>,
40 }
41
42 // Note: derived `Clone` doesn't specialize `clone_from`,
43 // but we want to keep the allocation in `data`.
44 impl Clone for BigUint {
45 #[inline]
clone(&self) -> Self46 fn clone(&self) -> Self {
47 BigUint {
48 data: self.data.clone(),
49 }
50 }
51
52 #[inline]
clone_from(&mut self, other: &Self)53 fn clone_from(&mut self, other: &Self) {
54 self.data.clone_from(&other.data);
55 }
56 }
57
58 impl hash::Hash for BigUint {
59 #[inline]
hash<H: hash::Hasher>(&self, state: &mut H)60 fn hash<H: hash::Hasher>(&self, state: &mut H) {
61 debug_assert!(self.data.last() != Some(&0));
62 self.data.hash(state);
63 }
64 }
65
66 impl PartialEq for BigUint {
67 #[inline]
eq(&self, other: &BigUint) -> bool68 fn eq(&self, other: &BigUint) -> bool {
69 debug_assert!(self.data.last() != Some(&0));
70 debug_assert!(other.data.last() != Some(&0));
71 self.data == other.data
72 }
73 }
74 impl Eq for BigUint {}
75
76 impl PartialOrd for BigUint {
77 #[inline]
partial_cmp(&self, other: &BigUint) -> Option<Ordering>78 fn partial_cmp(&self, other: &BigUint) -> Option<Ordering> {
79 Some(self.cmp(other))
80 }
81 }
82
83 impl Ord for BigUint {
84 #[inline]
cmp(&self, other: &BigUint) -> Ordering85 fn cmp(&self, other: &BigUint) -> Ordering {
86 cmp_slice(&self.data[..], &other.data[..])
87 }
88 }
89
90 #[inline]
cmp_slice(a: &[BigDigit], b: &[BigDigit]) -> Ordering91 fn cmp_slice(a: &[BigDigit], b: &[BigDigit]) -> Ordering {
92 debug_assert!(a.last() != Some(&0));
93 debug_assert!(b.last() != Some(&0));
94
95 match Ord::cmp(&a.len(), &b.len()) {
96 Ordering::Equal => Iterator::cmp(a.iter().rev(), b.iter().rev()),
97 other => other,
98 }
99 }
100
101 impl Default for BigUint {
102 #[inline]
default() -> BigUint103 fn default() -> BigUint {
104 Zero::zero()
105 }
106 }
107
108 impl fmt::Debug for BigUint {
fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result109 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
110 fmt::Display::fmt(self, f)
111 }
112 }
113
114 impl fmt::Display for BigUint {
fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result115 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
116 f.pad_integral(true, "", &self.to_str_radix(10))
117 }
118 }
119
120 impl fmt::LowerHex for BigUint {
fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result121 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
122 f.pad_integral(true, "0x", &self.to_str_radix(16))
123 }
124 }
125
126 impl fmt::UpperHex for BigUint {
fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result127 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
128 let mut s = self.to_str_radix(16);
129 s.make_ascii_uppercase();
130 f.pad_integral(true, "0x", &s)
131 }
132 }
133
134 impl fmt::Binary for BigUint {
fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result135 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
136 f.pad_integral(true, "0b", &self.to_str_radix(2))
137 }
138 }
139
140 impl fmt::Octal for BigUint {
fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result141 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
142 f.pad_integral(true, "0o", &self.to_str_radix(8))
143 }
144 }
145
146 impl Zero for BigUint {
147 #[inline]
zero() -> BigUint148 fn zero() -> BigUint {
149 BigUint { data: Vec::new() }
150 }
151
152 #[inline]
set_zero(&mut self)153 fn set_zero(&mut self) {
154 self.data.clear();
155 }
156
157 #[inline]
is_zero(&self) -> bool158 fn is_zero(&self) -> bool {
159 self.data.is_empty()
160 }
161 }
162
163 impl One for BigUint {
164 #[inline]
one() -> BigUint165 fn one() -> BigUint {
166 BigUint { data: vec![1] }
167 }
168
169 #[inline]
set_one(&mut self)170 fn set_one(&mut self) {
171 self.data.clear();
172 self.data.push(1);
173 }
174
175 #[inline]
is_one(&self) -> bool176 fn is_one(&self) -> bool {
177 self.data[..] == [1]
178 }
179 }
180
181 impl Unsigned for BigUint {}
182
183 impl Integer for BigUint {
184 #[inline]
div_rem(&self, other: &BigUint) -> (BigUint, BigUint)185 fn div_rem(&self, other: &BigUint) -> (BigUint, BigUint) {
186 division::div_rem_ref(self, other)
187 }
188
189 #[inline]
div_floor(&self, other: &BigUint) -> BigUint190 fn div_floor(&self, other: &BigUint) -> BigUint {
191 let (d, _) = division::div_rem_ref(self, other);
192 d
193 }
194
195 #[inline]
mod_floor(&self, other: &BigUint) -> BigUint196 fn mod_floor(&self, other: &BigUint) -> BigUint {
197 let (_, m) = division::div_rem_ref(self, other);
198 m
199 }
200
201 #[inline]
div_mod_floor(&self, other: &BigUint) -> (BigUint, BigUint)202 fn div_mod_floor(&self, other: &BigUint) -> (BigUint, BigUint) {
203 division::div_rem_ref(self, other)
204 }
205
206 #[inline]
div_ceil(&self, other: &BigUint) -> BigUint207 fn div_ceil(&self, other: &BigUint) -> BigUint {
208 let (d, m) = division::div_rem_ref(self, other);
209 if m.is_zero() {
210 d
211 } else {
212 d + 1u32
213 }
214 }
215
216 /// Calculates the Greatest Common Divisor (GCD) of the number and `other`.
217 ///
218 /// The result is always positive.
219 #[inline]
gcd(&self, other: &Self) -> Self220 fn gcd(&self, other: &Self) -> Self {
221 #[inline]
222 fn twos(x: &BigUint) -> u64 {
223 x.trailing_zeros().unwrap_or(0)
224 }
225
226 // Stein's algorithm
227 if self.is_zero() {
228 return other.clone();
229 }
230 if other.is_zero() {
231 return self.clone();
232 }
233 let mut m = self.clone();
234 let mut n = other.clone();
235
236 // find common factors of 2
237 let shift = cmp::min(twos(&n), twos(&m));
238
239 // divide m and n by 2 until odd
240 // m inside loop
241 n >>= twos(&n);
242
243 while !m.is_zero() {
244 m >>= twos(&m);
245 if n > m {
246 mem::swap(&mut n, &mut m)
247 }
248 m -= &n;
249 }
250
251 n << shift
252 }
253
254 /// Calculates the Lowest Common Multiple (LCM) of the number and `other`.
255 #[inline]
lcm(&self, other: &BigUint) -> BigUint256 fn lcm(&self, other: &BigUint) -> BigUint {
257 if self.is_zero() && other.is_zero() {
258 Self::zero()
259 } else {
260 self / self.gcd(other) * other
261 }
262 }
263
264 /// Calculates the Greatest Common Divisor (GCD) and
265 /// Lowest Common Multiple (LCM) together.
266 #[inline]
gcd_lcm(&self, other: &Self) -> (Self, Self)267 fn gcd_lcm(&self, other: &Self) -> (Self, Self) {
268 let gcd = self.gcd(other);
269 let lcm = if gcd.is_zero() {
270 Self::zero()
271 } else {
272 self / &gcd * other
273 };
274 (gcd, lcm)
275 }
276
277 /// Deprecated, use `is_multiple_of` instead.
278 #[inline]
divides(&self, other: &BigUint) -> bool279 fn divides(&self, other: &BigUint) -> bool {
280 self.is_multiple_of(other)
281 }
282
283 /// Returns `true` if the number is a multiple of `other`.
284 #[inline]
is_multiple_of(&self, other: &BigUint) -> bool285 fn is_multiple_of(&self, other: &BigUint) -> bool {
286 if other.is_zero() {
287 return self.is_zero();
288 }
289 (self % other).is_zero()
290 }
291
292 /// Returns `true` if the number is divisible by `2`.
293 #[inline]
is_even(&self) -> bool294 fn is_even(&self) -> bool {
295 // Considering only the last digit.
296 match self.data.first() {
297 Some(x) => x.is_even(),
298 None => true,
299 }
300 }
301
302 /// Returns `true` if the number is not divisible by `2`.
303 #[inline]
is_odd(&self) -> bool304 fn is_odd(&self) -> bool {
305 !self.is_even()
306 }
307
308 /// Rounds up to nearest multiple of argument.
309 #[inline]
next_multiple_of(&self, other: &Self) -> Self310 fn next_multiple_of(&self, other: &Self) -> Self {
311 let m = self.mod_floor(other);
312 if m.is_zero() {
313 self.clone()
314 } else {
315 self + (other - m)
316 }
317 }
318 /// Rounds down to nearest multiple of argument.
319 #[inline]
prev_multiple_of(&self, other: &Self) -> Self320 fn prev_multiple_of(&self, other: &Self) -> Self {
321 self - self.mod_floor(other)
322 }
323 }
324
325 #[inline]
fixpoint<F>(mut x: BigUint, max_bits: u64, f: F) -> BigUint where F: Fn(&BigUint) -> BigUint,326 fn fixpoint<F>(mut x: BigUint, max_bits: u64, f: F) -> BigUint
327 where
328 F: Fn(&BigUint) -> BigUint,
329 {
330 let mut xn = f(&x);
331
332 // If the value increased, then the initial guess must have been low.
333 // Repeat until we reverse course.
334 while x < xn {
335 // Sometimes an increase will go way too far, especially with large
336 // powers, and then take a long time to walk back. We know an upper
337 // bound based on bit size, so saturate on that.
338 x = if xn.bits() > max_bits {
339 BigUint::one() << max_bits
340 } else {
341 xn
342 };
343 xn = f(&x);
344 }
345
346 // Now keep repeating while the estimate is decreasing.
347 while x > xn {
348 x = xn;
349 xn = f(&x);
350 }
351 x
352 }
353
354 impl Roots for BigUint {
355 // nth_root, sqrt and cbrt use Newton's method to compute
356 // principal root of a given degree for a given integer.
357
358 // Reference:
359 // Brent & Zimmermann, Modern Computer Arithmetic, v0.5.9, Algorithm 1.14
nth_root(&self, n: u32) -> Self360 fn nth_root(&self, n: u32) -> Self {
361 assert!(n > 0, "root degree n must be at least 1");
362
363 if self.is_zero() || self.is_one() {
364 return self.clone();
365 }
366
367 match n {
368 // Optimize for small n
369 1 => return self.clone(),
370 2 => return self.sqrt(),
371 3 => return self.cbrt(),
372 _ => (),
373 }
374
375 // The root of non-zero values less than 2ⁿ can only be 1.
376 let bits = self.bits();
377 let n64 = u64::from(n);
378 if bits <= n64 {
379 return BigUint::one();
380 }
381
382 // If we fit in `u64`, compute the root that way.
383 if let Some(x) = self.to_u64() {
384 return x.nth_root(n).into();
385 }
386
387 let max_bits = bits / n64 + 1;
388
389 #[cfg(feature = "std")]
390 let guess = match self.to_f64() {
391 Some(f) if f.is_finite() => {
392 use num_traits::FromPrimitive;
393
394 // We fit in `f64` (lossy), so get a better initial guess from that.
395 BigUint::from_f64((f.ln() / f64::from(n)).exp()).unwrap()
396 }
397 _ => {
398 // Try to guess by scaling down such that it does fit in `f64`.
399 // With some (x * 2ⁿᵏ), its nth root ≈ (ⁿ√x * 2ᵏ)
400 let extra_bits = bits - (core::f64::MAX_EXP as u64 - 1);
401 let root_scale = Integer::div_ceil(&extra_bits, &n64);
402 let scale = root_scale * n64;
403 if scale < bits && bits - scale > n64 {
404 (self >> scale).nth_root(n) << root_scale
405 } else {
406 BigUint::one() << max_bits
407 }
408 }
409 };
410
411 #[cfg(not(feature = "std"))]
412 let guess = BigUint::one() << max_bits;
413
414 let n_min_1 = n - 1;
415 fixpoint(guess, max_bits, move |s| {
416 let q = self / s.pow(n_min_1);
417 let t = n_min_1 * s + q;
418 t / n
419 })
420 }
421
422 // Reference:
423 // Brent & Zimmermann, Modern Computer Arithmetic, v0.5.9, Algorithm 1.13
sqrt(&self) -> Self424 fn sqrt(&self) -> Self {
425 if self.is_zero() || self.is_one() {
426 return self.clone();
427 }
428
429 // If we fit in `u64`, compute the root that way.
430 if let Some(x) = self.to_u64() {
431 return x.sqrt().into();
432 }
433
434 let bits = self.bits();
435 let max_bits = bits / 2 + 1;
436
437 #[cfg(feature = "std")]
438 let guess = match self.to_f64() {
439 Some(f) if f.is_finite() => {
440 use num_traits::FromPrimitive;
441
442 // We fit in `f64` (lossy), so get a better initial guess from that.
443 BigUint::from_f64(f.sqrt()).unwrap()
444 }
445 _ => {
446 // Try to guess by scaling down such that it does fit in `f64`.
447 // With some (x * 2²ᵏ), its sqrt ≈ (√x * 2ᵏ)
448 let extra_bits = bits - (core::f64::MAX_EXP as u64 - 1);
449 let root_scale = (extra_bits + 1) / 2;
450 let scale = root_scale * 2;
451 (self >> scale).sqrt() << root_scale
452 }
453 };
454
455 #[cfg(not(feature = "std"))]
456 let guess = BigUint::one() << max_bits;
457
458 fixpoint(guess, max_bits, move |s| {
459 let q = self / s;
460 let t = s + q;
461 t >> 1
462 })
463 }
464
cbrt(&self) -> Self465 fn cbrt(&self) -> Self {
466 if self.is_zero() || self.is_one() {
467 return self.clone();
468 }
469
470 // If we fit in `u64`, compute the root that way.
471 if let Some(x) = self.to_u64() {
472 return x.cbrt().into();
473 }
474
475 let bits = self.bits();
476 let max_bits = bits / 3 + 1;
477
478 #[cfg(feature = "std")]
479 let guess = match self.to_f64() {
480 Some(f) if f.is_finite() => {
481 use num_traits::FromPrimitive;
482
483 // We fit in `f64` (lossy), so get a better initial guess from that.
484 BigUint::from_f64(f.cbrt()).unwrap()
485 }
486 _ => {
487 // Try to guess by scaling down such that it does fit in `f64`.
488 // With some (x * 2³ᵏ), its cbrt ≈ (∛x * 2ᵏ)
489 let extra_bits = bits - (core::f64::MAX_EXP as u64 - 1);
490 let root_scale = (extra_bits + 2) / 3;
491 let scale = root_scale * 3;
492 (self >> scale).cbrt() << root_scale
493 }
494 };
495
496 #[cfg(not(feature = "std"))]
497 let guess = BigUint::one() << max_bits;
498
499 fixpoint(guess, max_bits, move |s| {
500 let q = self / (s * s);
501 let t = (s << 1) + q;
502 t / 3u32
503 })
504 }
505 }
506
507 /// A generic trait for converting a value to a [`BigUint`].
508 pub trait ToBigUint {
509 /// Converts the value of `self` to a [`BigUint`].
to_biguint(&self) -> Option<BigUint>510 fn to_biguint(&self) -> Option<BigUint>;
511 }
512
513 /// Creates and initializes a [`BigUint`].
514 ///
515 /// The digits are in little-endian base matching `BigDigit`.
516 #[inline]
biguint_from_vec(digits: Vec<BigDigit>) -> BigUint517 pub(crate) fn biguint_from_vec(digits: Vec<BigDigit>) -> BigUint {
518 BigUint { data: digits }.normalized()
519 }
520
521 impl BigUint {
522 /// Creates and initializes a [`BigUint`].
523 ///
524 /// The base 2<sup>32</sup> digits are ordered least significant digit first.
525 #[inline]
new(digits: Vec<u32>) -> BigUint526 pub fn new(digits: Vec<u32>) -> BigUint {
527 let mut big = BigUint::zero();
528
529 #[cfg(not(u64_digit))]
530 {
531 big.data = digits;
532 big.normalize();
533 }
534
535 #[cfg(u64_digit)]
536 big.assign_from_slice(&digits);
537
538 big
539 }
540
541 /// Creates and initializes a [`BigUint`].
542 ///
543 /// The base 2<sup>32</sup> digits are ordered least significant digit first.
544 #[inline]
from_slice(slice: &[u32]) -> BigUint545 pub fn from_slice(slice: &[u32]) -> BigUint {
546 let mut big = BigUint::zero();
547 big.assign_from_slice(slice);
548 big
549 }
550
551 /// Assign a value to a [`BigUint`].
552 ///
553 /// The base 2<sup>32</sup> digits are ordered least significant digit first.
554 #[inline]
assign_from_slice(&mut self, slice: &[u32])555 pub fn assign_from_slice(&mut self, slice: &[u32]) {
556 self.data.clear();
557
558 #[cfg(not(u64_digit))]
559 self.data.extend_from_slice(slice);
560
561 #[cfg(u64_digit)]
562 self.data.extend(slice.chunks(2).map(u32_chunk_to_u64));
563
564 self.normalize();
565 }
566
567 /// Creates and initializes a [`BigUint`].
568 ///
569 /// The bytes are in big-endian byte order.
570 ///
571 /// # Examples
572 ///
573 /// ```
574 /// use num_bigint::BigUint;
575 ///
576 /// assert_eq!(BigUint::from_bytes_be(b"A"),
577 /// BigUint::parse_bytes(b"65", 10).unwrap());
578 /// assert_eq!(BigUint::from_bytes_be(b"AA"),
579 /// BigUint::parse_bytes(b"16705", 10).unwrap());
580 /// assert_eq!(BigUint::from_bytes_be(b"AB"),
581 /// BigUint::parse_bytes(b"16706", 10).unwrap());
582 /// assert_eq!(BigUint::from_bytes_be(b"Hello world!"),
583 /// BigUint::parse_bytes(b"22405534230753963835153736737", 10).unwrap());
584 /// ```
585 #[inline]
from_bytes_be(bytes: &[u8]) -> BigUint586 pub fn from_bytes_be(bytes: &[u8]) -> BigUint {
587 if bytes.is_empty() {
588 Zero::zero()
589 } else {
590 let mut v = bytes.to_vec();
591 v.reverse();
592 BigUint::from_bytes_le(&v)
593 }
594 }
595
596 /// Creates and initializes a [`BigUint`].
597 ///
598 /// The bytes are in little-endian byte order.
599 #[inline]
from_bytes_le(bytes: &[u8]) -> BigUint600 pub fn from_bytes_le(bytes: &[u8]) -> BigUint {
601 if bytes.is_empty() {
602 Zero::zero()
603 } else {
604 convert::from_bitwise_digits_le(bytes, 8)
605 }
606 }
607
608 /// Creates and initializes a [`BigUint`]. The input slice must contain
609 /// ascii/utf8 characters in [0-9a-zA-Z].
610 /// `radix` must be in the range `2...36`.
611 ///
612 /// The function `from_str_radix` from the `Num` trait provides the same logic
613 /// for `&str` buffers.
614 ///
615 /// # Examples
616 ///
617 /// ```
618 /// use num_bigint::{BigUint, ToBigUint};
619 ///
620 /// assert_eq!(BigUint::parse_bytes(b"1234", 10), ToBigUint::to_biguint(&1234));
621 /// assert_eq!(BigUint::parse_bytes(b"ABCD", 16), ToBigUint::to_biguint(&0xABCD));
622 /// assert_eq!(BigUint::parse_bytes(b"G", 16), None);
623 /// ```
624 #[inline]
parse_bytes(buf: &[u8], radix: u32) -> Option<BigUint>625 pub fn parse_bytes(buf: &[u8], radix: u32) -> Option<BigUint> {
626 let s = str::from_utf8(buf).ok()?;
627 BigUint::from_str_radix(s, radix).ok()
628 }
629
630 /// Creates and initializes a [`BigUint`]. Each `u8` of the input slice is
631 /// interpreted as one digit of the number
632 /// and must therefore be less than `radix`.
633 ///
634 /// The bytes are in big-endian byte order.
635 /// `radix` must be in the range `2...256`.
636 ///
637 /// # Examples
638 ///
639 /// ```
640 /// use num_bigint::{BigUint};
641 ///
642 /// let inbase190 = &[15, 33, 125, 12, 14];
643 /// let a = BigUint::from_radix_be(inbase190, 190).unwrap();
644 /// assert_eq!(a.to_radix_be(190), inbase190);
645 /// ```
from_radix_be(buf: &[u8], radix: u32) -> Option<BigUint>646 pub fn from_radix_be(buf: &[u8], radix: u32) -> Option<BigUint> {
647 convert::from_radix_be(buf, radix)
648 }
649
650 /// Creates and initializes a [`BigUint`]. Each `u8` of the input slice is
651 /// interpreted as one digit of the number
652 /// and must therefore be less than `radix`.
653 ///
654 /// The bytes are in little-endian byte order.
655 /// `radix` must be in the range `2...256`.
656 ///
657 /// # Examples
658 ///
659 /// ```
660 /// use num_bigint::{BigUint};
661 ///
662 /// let inbase190 = &[14, 12, 125, 33, 15];
663 /// let a = BigUint::from_radix_be(inbase190, 190).unwrap();
664 /// assert_eq!(a.to_radix_be(190), inbase190);
665 /// ```
from_radix_le(buf: &[u8], radix: u32) -> Option<BigUint>666 pub fn from_radix_le(buf: &[u8], radix: u32) -> Option<BigUint> {
667 convert::from_radix_le(buf, radix)
668 }
669
670 /// Returns the byte representation of the [`BigUint`] in big-endian byte order.
671 ///
672 /// # Examples
673 ///
674 /// ```
675 /// use num_bigint::BigUint;
676 ///
677 /// let i = BigUint::parse_bytes(b"1125", 10).unwrap();
678 /// assert_eq!(i.to_bytes_be(), vec![4, 101]);
679 /// ```
680 #[inline]
to_bytes_be(&self) -> Vec<u8>681 pub fn to_bytes_be(&self) -> Vec<u8> {
682 let mut v = self.to_bytes_le();
683 v.reverse();
684 v
685 }
686
687 /// Returns the byte representation of the [`BigUint`] in little-endian byte order.
688 ///
689 /// # Examples
690 ///
691 /// ```
692 /// use num_bigint::BigUint;
693 ///
694 /// let i = BigUint::parse_bytes(b"1125", 10).unwrap();
695 /// assert_eq!(i.to_bytes_le(), vec![101, 4]);
696 /// ```
697 #[inline]
to_bytes_le(&self) -> Vec<u8>698 pub fn to_bytes_le(&self) -> Vec<u8> {
699 if self.is_zero() {
700 vec![0]
701 } else {
702 convert::to_bitwise_digits_le(self, 8)
703 }
704 }
705
706 /// Returns the `u32` digits representation of the [`BigUint`] ordered least significant digit
707 /// first.
708 ///
709 /// # Examples
710 ///
711 /// ```
712 /// use num_bigint::BigUint;
713 ///
714 /// assert_eq!(BigUint::from(1125u32).to_u32_digits(), vec![1125]);
715 /// assert_eq!(BigUint::from(4294967295u32).to_u32_digits(), vec![4294967295]);
716 /// assert_eq!(BigUint::from(4294967296u64).to_u32_digits(), vec![0, 1]);
717 /// assert_eq!(BigUint::from(112500000000u64).to_u32_digits(), vec![830850304, 26]);
718 /// ```
719 #[inline]
to_u32_digits(&self) -> Vec<u32>720 pub fn to_u32_digits(&self) -> Vec<u32> {
721 self.iter_u32_digits().collect()
722 }
723
724 /// Returns the `u64` digits representation of the [`BigUint`] ordered least significant digit
725 /// first.
726 ///
727 /// # Examples
728 ///
729 /// ```
730 /// use num_bigint::BigUint;
731 ///
732 /// assert_eq!(BigUint::from(1125u32).to_u64_digits(), vec![1125]);
733 /// assert_eq!(BigUint::from(4294967295u32).to_u64_digits(), vec![4294967295]);
734 /// assert_eq!(BigUint::from(4294967296u64).to_u64_digits(), vec![4294967296]);
735 /// assert_eq!(BigUint::from(112500000000u64).to_u64_digits(), vec![112500000000]);
736 /// assert_eq!(BigUint::from(1u128 << 64).to_u64_digits(), vec![0, 1]);
737 /// ```
738 #[inline]
to_u64_digits(&self) -> Vec<u64>739 pub fn to_u64_digits(&self) -> Vec<u64> {
740 self.iter_u64_digits().collect()
741 }
742
743 /// Returns an iterator of `u32` digits representation of the [`BigUint`] ordered least
744 /// significant digit first.
745 ///
746 /// # Examples
747 ///
748 /// ```
749 /// use num_bigint::BigUint;
750 ///
751 /// assert_eq!(BigUint::from(1125u32).iter_u32_digits().collect::<Vec<u32>>(), vec![1125]);
752 /// assert_eq!(BigUint::from(4294967295u32).iter_u32_digits().collect::<Vec<u32>>(), vec![4294967295]);
753 /// assert_eq!(BigUint::from(4294967296u64).iter_u32_digits().collect::<Vec<u32>>(), vec![0, 1]);
754 /// assert_eq!(BigUint::from(112500000000u64).iter_u32_digits().collect::<Vec<u32>>(), vec![830850304, 26]);
755 /// ```
756 #[inline]
iter_u32_digits(&self) -> U32Digits<'_>757 pub fn iter_u32_digits(&self) -> U32Digits<'_> {
758 U32Digits::new(self.data.as_slice())
759 }
760
761 /// Returns an iterator of `u64` digits representation of the [`BigUint`] ordered least
762 /// significant digit first.
763 ///
764 /// # Examples
765 ///
766 /// ```
767 /// use num_bigint::BigUint;
768 ///
769 /// assert_eq!(BigUint::from(1125u32).iter_u64_digits().collect::<Vec<u64>>(), vec![1125]);
770 /// assert_eq!(BigUint::from(4294967295u32).iter_u64_digits().collect::<Vec<u64>>(), vec![4294967295]);
771 /// assert_eq!(BigUint::from(4294967296u64).iter_u64_digits().collect::<Vec<u64>>(), vec![4294967296]);
772 /// assert_eq!(BigUint::from(112500000000u64).iter_u64_digits().collect::<Vec<u64>>(), vec![112500000000]);
773 /// assert_eq!(BigUint::from(1u128 << 64).iter_u64_digits().collect::<Vec<u64>>(), vec![0, 1]);
774 /// ```
775 #[inline]
iter_u64_digits(&self) -> U64Digits<'_>776 pub fn iter_u64_digits(&self) -> U64Digits<'_> {
777 U64Digits::new(self.data.as_slice())
778 }
779
780 /// Returns the integer formatted as a string in the given radix.
781 /// `radix` must be in the range `2...36`.
782 ///
783 /// # Examples
784 ///
785 /// ```
786 /// use num_bigint::BigUint;
787 ///
788 /// let i = BigUint::parse_bytes(b"ff", 16).unwrap();
789 /// assert_eq!(i.to_str_radix(16), "ff");
790 /// ```
791 #[inline]
to_str_radix(&self, radix: u32) -> String792 pub fn to_str_radix(&self, radix: u32) -> String {
793 let mut v = to_str_radix_reversed(self, radix);
794 v.reverse();
795 unsafe { String::from_utf8_unchecked(v) }
796 }
797
798 /// Returns the integer in the requested base in big-endian digit order.
799 /// The output is not given in a human readable alphabet but as a zero
800 /// based `u8` number.
801 /// `radix` must be in the range `2...256`.
802 ///
803 /// # Examples
804 ///
805 /// ```
806 /// use num_bigint::BigUint;
807 ///
808 /// assert_eq!(BigUint::from(0xFFFFu64).to_radix_be(159),
809 /// vec![2, 94, 27]);
810 /// // 0xFFFF = 65535 = 2*(159^2) + 94*159 + 27
811 /// ```
812 #[inline]
to_radix_be(&self, radix: u32) -> Vec<u8>813 pub fn to_radix_be(&self, radix: u32) -> Vec<u8> {
814 let mut v = convert::to_radix_le(self, radix);
815 v.reverse();
816 v
817 }
818
819 /// Returns the integer in the requested base in little-endian digit order.
820 /// The output is not given in a human readable alphabet but as a zero
821 /// based u8 number.
822 /// `radix` must be in the range `2...256`.
823 ///
824 /// # Examples
825 ///
826 /// ```
827 /// use num_bigint::BigUint;
828 ///
829 /// assert_eq!(BigUint::from(0xFFFFu64).to_radix_le(159),
830 /// vec![27, 94, 2]);
831 /// // 0xFFFF = 65535 = 27 + 94*159 + 2*(159^2)
832 /// ```
833 #[inline]
to_radix_le(&self, radix: u32) -> Vec<u8>834 pub fn to_radix_le(&self, radix: u32) -> Vec<u8> {
835 convert::to_radix_le(self, radix)
836 }
837
838 /// Determines the fewest bits necessary to express the [`BigUint`].
839 #[inline]
bits(&self) -> u64840 pub fn bits(&self) -> u64 {
841 if self.is_zero() {
842 return 0;
843 }
844 let zeros: u64 = self.data.last().unwrap().leading_zeros().into();
845 self.data.len() as u64 * u64::from(big_digit::BITS) - zeros
846 }
847
848 /// Strips off trailing zero bigdigits - comparisons require the last element in the vector to
849 /// be nonzero.
850 #[inline]
normalize(&mut self)851 fn normalize(&mut self) {
852 if let Some(&0) = self.data.last() {
853 let len = self.data.iter().rposition(|&d| d != 0).map_or(0, |i| i + 1);
854 self.data.truncate(len);
855 }
856 if self.data.len() < self.data.capacity() / 4 {
857 self.data.shrink_to_fit();
858 }
859 }
860
861 /// Returns a normalized [`BigUint`].
862 #[inline]
normalized(mut self) -> BigUint863 fn normalized(mut self) -> BigUint {
864 self.normalize();
865 self
866 }
867
868 /// Returns `self ^ exponent`.
pow(&self, exponent: u32) -> Self869 pub fn pow(&self, exponent: u32) -> Self {
870 Pow::pow(self, exponent)
871 }
872
873 /// Returns `(self ^ exponent) % modulus`.
874 ///
875 /// Panics if the modulus is zero.
modpow(&self, exponent: &Self, modulus: &Self) -> Self876 pub fn modpow(&self, exponent: &Self, modulus: &Self) -> Self {
877 power::modpow(self, exponent, modulus)
878 }
879
880 /// Returns the truncated principal square root of `self` --
881 /// see [Roots::sqrt](https://docs.rs/num-integer/0.1/num_integer/trait.Roots.html#method.sqrt)
sqrt(&self) -> Self882 pub fn sqrt(&self) -> Self {
883 Roots::sqrt(self)
884 }
885
886 /// Returns the truncated principal cube root of `self` --
887 /// see [Roots::cbrt](https://docs.rs/num-integer/0.1/num_integer/trait.Roots.html#method.cbrt).
cbrt(&self) -> Self888 pub fn cbrt(&self) -> Self {
889 Roots::cbrt(self)
890 }
891
892 /// Returns the truncated principal `n`th root of `self` --
893 /// see [Roots::nth_root](https://docs.rs/num-integer/0.1/num_integer/trait.Roots.html#tymethod.nth_root).
nth_root(&self, n: u32) -> Self894 pub fn nth_root(&self, n: u32) -> Self {
895 Roots::nth_root(self, n)
896 }
897
898 /// Returns the number of least-significant bits that are zero,
899 /// or `None` if the entire number is zero.
trailing_zeros(&self) -> Option<u64>900 pub fn trailing_zeros(&self) -> Option<u64> {
901 let i = self.data.iter().position(|&digit| digit != 0)?;
902 let zeros: u64 = self.data[i].trailing_zeros().into();
903 Some(i as u64 * u64::from(big_digit::BITS) + zeros)
904 }
905
906 /// Returns the number of least-significant bits that are ones.
trailing_ones(&self) -> u64907 pub fn trailing_ones(&self) -> u64 {
908 if let Some(i) = self.data.iter().position(|&digit| !digit != 0) {
909 // XXX u64::trailing_ones() introduced in Rust 1.46,
910 // but we need to be compatible further back.
911 // Thanks to cuviper for this workaround.
912 let ones: u64 = (!self.data[i]).trailing_zeros().into();
913 i as u64 * u64::from(big_digit::BITS) + ones
914 } else {
915 self.data.len() as u64 * u64::from(big_digit::BITS)
916 }
917 }
918
919 /// Returns the number of one bits.
count_ones(&self) -> u64920 pub fn count_ones(&self) -> u64 {
921 self.data.iter().map(|&d| u64::from(d.count_ones())).sum()
922 }
923
924 /// Returns whether the bit in the given position is set
bit(&self, bit: u64) -> bool925 pub fn bit(&self, bit: u64) -> bool {
926 let bits_per_digit = u64::from(big_digit::BITS);
927 if let Some(digit_index) = (bit / bits_per_digit).to_usize() {
928 if let Some(digit) = self.data.get(digit_index) {
929 let bit_mask = (1 as BigDigit) << (bit % bits_per_digit);
930 return (digit & bit_mask) != 0;
931 }
932 }
933 false
934 }
935
936 /// Sets or clears the bit in the given position
937 ///
938 /// Note that setting a bit greater than the current bit length, a reallocation may be needed
939 /// to store the new digits
set_bit(&mut self, bit: u64, value: bool)940 pub fn set_bit(&mut self, bit: u64, value: bool) {
941 // Note: we're saturating `digit_index` and `new_len` -- any such case is guaranteed to
942 // fail allocation, and that's more consistent than adding our own overflow panics.
943 let bits_per_digit = u64::from(big_digit::BITS);
944 let digit_index = (bit / bits_per_digit)
945 .to_usize()
946 .unwrap_or(core::usize::MAX);
947 let bit_mask = (1 as BigDigit) << (bit % bits_per_digit);
948 if value {
949 if digit_index >= self.data.len() {
950 let new_len = digit_index.saturating_add(1);
951 self.data.resize(new_len, 0);
952 }
953 self.data[digit_index] |= bit_mask;
954 } else if digit_index < self.data.len() {
955 self.data[digit_index] &= !bit_mask;
956 // the top bit may have been cleared, so normalize
957 self.normalize();
958 }
959 }
960 }
961
962 impl num_traits::FromBytes for BigUint {
963 type Bytes = [u8];
964
from_be_bytes(bytes: &Self::Bytes) -> Self965 fn from_be_bytes(bytes: &Self::Bytes) -> Self {
966 Self::from_bytes_be(bytes)
967 }
968
from_le_bytes(bytes: &Self::Bytes) -> Self969 fn from_le_bytes(bytes: &Self::Bytes) -> Self {
970 Self::from_bytes_le(bytes)
971 }
972 }
973
974 impl num_traits::ToBytes for BigUint {
975 type Bytes = Vec<u8>;
976
to_be_bytes(&self) -> Self::Bytes977 fn to_be_bytes(&self) -> Self::Bytes {
978 self.to_bytes_be()
979 }
980
to_le_bytes(&self) -> Self::Bytes981 fn to_le_bytes(&self) -> Self::Bytes {
982 self.to_bytes_le()
983 }
984 }
985
986 pub(crate) trait IntDigits {
digits(&self) -> &[BigDigit]987 fn digits(&self) -> &[BigDigit];
digits_mut(&mut self) -> &mut Vec<BigDigit>988 fn digits_mut(&mut self) -> &mut Vec<BigDigit>;
normalize(&mut self)989 fn normalize(&mut self);
capacity(&self) -> usize990 fn capacity(&self) -> usize;
len(&self) -> usize991 fn len(&self) -> usize;
992 }
993
994 impl IntDigits for BigUint {
995 #[inline]
digits(&self) -> &[BigDigit]996 fn digits(&self) -> &[BigDigit] {
997 &self.data
998 }
999 #[inline]
digits_mut(&mut self) -> &mut Vec<BigDigit>1000 fn digits_mut(&mut self) -> &mut Vec<BigDigit> {
1001 &mut self.data
1002 }
1003 #[inline]
normalize(&mut self)1004 fn normalize(&mut self) {
1005 self.normalize();
1006 }
1007 #[inline]
capacity(&self) -> usize1008 fn capacity(&self) -> usize {
1009 self.data.capacity()
1010 }
1011 #[inline]
len(&self) -> usize1012 fn len(&self) -> usize {
1013 self.data.len()
1014 }
1015 }
1016
1017 /// Convert a `u32` chunk (len is either 1 or 2) to a single `u64` digit
1018 #[inline]
u32_chunk_to_u64(chunk: &[u32]) -> u641019 fn u32_chunk_to_u64(chunk: &[u32]) -> u64 {
1020 // raw could have odd length
1021 let mut digit = chunk[0] as u64;
1022 if let Some(&hi) = chunk.get(1) {
1023 digit |= (hi as u64) << 32;
1024 }
1025 digit
1026 }
1027
1028 /// Combine four `u32`s into a single `u128`.
1029 #[cfg(any(test, not(u64_digit)))]
1030 #[inline]
u32_to_u128(a: u32, b: u32, c: u32, d: u32) -> u1281031 fn u32_to_u128(a: u32, b: u32, c: u32, d: u32) -> u128 {
1032 u128::from(d) | (u128::from(c) << 32) | (u128::from(b) << 64) | (u128::from(a) << 96)
1033 }
1034
1035 /// Split a single `u128` into four `u32`.
1036 #[cfg(any(test, not(u64_digit)))]
1037 #[inline]
u32_from_u128(n: u128) -> (u32, u32, u32, u32)1038 fn u32_from_u128(n: u128) -> (u32, u32, u32, u32) {
1039 (
1040 (n >> 96) as u32,
1041 (n >> 64) as u32,
1042 (n >> 32) as u32,
1043 n as u32,
1044 )
1045 }
1046
1047 #[cfg(not(u64_digit))]
1048 #[test]
test_from_slice()1049 fn test_from_slice() {
1050 fn check(slice: &[u32], data: &[BigDigit]) {
1051 assert_eq!(BigUint::from_slice(slice).data, data);
1052 }
1053 check(&[1], &[1]);
1054 check(&[0, 0, 0], &[]);
1055 check(&[1, 2, 0, 0], &[1, 2]);
1056 check(&[0, 0, 1, 2], &[0, 0, 1, 2]);
1057 check(&[0, 0, 1, 2, 0, 0], &[0, 0, 1, 2]);
1058 check(&[-1i32 as u32], &[-1i32 as BigDigit]);
1059 }
1060
1061 #[cfg(u64_digit)]
1062 #[test]
test_from_slice()1063 fn test_from_slice() {
1064 fn check(slice: &[u32], data: &[BigDigit]) {
1065 assert_eq!(
1066 BigUint::from_slice(slice).data,
1067 data,
1068 "from {:?}, to {:?}",
1069 slice,
1070 data
1071 );
1072 }
1073 check(&[1], &[1]);
1074 check(&[0, 0, 0], &[]);
1075 check(&[1, 2], &[8_589_934_593]);
1076 check(&[1, 2, 0, 0], &[8_589_934_593]);
1077 check(&[0, 0, 1, 2], &[0, 8_589_934_593]);
1078 check(&[0, 0, 1, 2, 0, 0], &[0, 8_589_934_593]);
1079 check(&[-1i32 as u32], &[(-1i32 as u32) as BigDigit]);
1080 }
1081
1082 #[test]
test_u32_u128()1083 fn test_u32_u128() {
1084 assert_eq!(u32_from_u128(0u128), (0, 0, 0, 0));
1085 assert_eq!(
1086 u32_from_u128(u128::max_value()),
1087 (
1088 u32::max_value(),
1089 u32::max_value(),
1090 u32::max_value(),
1091 u32::max_value()
1092 )
1093 );
1094
1095 assert_eq!(
1096 u32_from_u128(u32::max_value() as u128),
1097 (0, 0, 0, u32::max_value())
1098 );
1099
1100 assert_eq!(
1101 u32_from_u128(u64::max_value() as u128),
1102 (0, 0, u32::max_value(), u32::max_value())
1103 );
1104
1105 assert_eq!(
1106 u32_from_u128((u64::max_value() as u128) + u32::max_value() as u128),
1107 (0, 1, 0, u32::max_value() - 1)
1108 );
1109
1110 assert_eq!(u32_from_u128(36_893_488_151_714_070_528), (0, 2, 1, 0));
1111 }
1112
1113 #[test]
test_u128_u32_roundtrip()1114 fn test_u128_u32_roundtrip() {
1115 // roundtrips
1116 let values = vec![
1117 0u128,
1118 1u128,
1119 u64::max_value() as u128 * 3,
1120 u32::max_value() as u128,
1121 u64::max_value() as u128,
1122 (u64::max_value() as u128) + u32::max_value() as u128,
1123 u128::max_value(),
1124 ];
1125
1126 for val in &values {
1127 let (a, b, c, d) = u32_from_u128(*val);
1128 assert_eq!(u32_to_u128(a, b, c, d), *val);
1129 }
1130 }
1131