Coverage Report

Created: 2026-08-13 07:14

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