Skip to main content

rug/integer/
big.rs

1// Copyright © 2016–2026 Trevor Spiteri
2
3// This program is free software: you can redistribute it and/or modify it under
4// the terms of the GNU Lesser General Public License as published by the Free
5// Software Foundation, either version 3 of the License, or (at your option) any
6// later version.
7//
8// This program is distributed in the hope that it will be useful, but WITHOUT
9// ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
10// FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
11// details.
12//
13// You should have received a copy of the GNU Lesser General Public License and
14// a copy of the GNU General Public License along with this program. If not, see
15// <https://www.gnu.org/licenses/>.
16
17use crate::ext::xmpz;
18use crate::integer::arith::MulIncomplete;
19use crate::integer::{BorrowInteger, MiniInteger, Order};
20use crate::misc;
21use crate::misc::{StringLike, VecLike};
22use crate::ops::{DivRounding, NegAssign, SubFrom};
23#[cfg(feature = "rand")]
24use crate::rand::MutRandState;
25#[cfg(feature = "rational")]
26use crate::rational::BorrowRational;
27use crate::{Assign, Complete};
28use az::{Az, Cast, CheckedCast, StrictAs, StrictCast, WrappingCast};
29use core::cmp::Ordering;
30use core::error::Error;
31use core::ffi::{c_uint, c_ulong};
32use core::fmt::{Display, Formatter, Result as FmtResult};
33use core::mem;
34use core::mem::{ManuallyDrop, MaybeUninit};
35use core::ops::{Add, AddAssign, Mul, MulAssign, Sub, SubAssign};
36#[cfg(feature = "rational")]
37use core::ptr::NonNull;
38use core::slice;
39use gmp_mpfr_sys::gmp;
40#[cfg(feature = "rational")]
41use gmp_mpfr_sys::gmp::mpq_t;
42use gmp_mpfr_sys::gmp::{bitcnt_t, limb_t, mpz_t};
43
44/**
45An arbitrary-precision integer.
46
47Standard arithmetic operations, bitwise operations and comparisons are
48supported. In standard arithmetic operations such as addition, you can mix
49`Integer` and primitive integer types; the result will be an `Integer`.
50
51Internally the integer is not stored using a two’s-complement representation,
52however, for bitwise operations and shifts, the functionality is the same as if
53the representation was using two’s complement.
54
55# Examples
56
57```rust
58use rug::{Assign, Integer};
59// Create an integer initialized as zero.
60let mut int = Integer::new();
61assert_eq!(int, 0);
62assert_eq!(int.to_u32(), Some(0));
63int.assign(-14);
64assert_eq!(int, -14);
65assert_eq!(int.to_u32(), None);
66assert_eq!(int.to_i32(), Some(-14));
67```
68
69Arithmetic operations with mixed arbitrary and primitive types are allowed. Note
70that in the following example, there is only one allocation. The `Integer`
71instance is moved into the shift operation so that the result can be stored in
72the same instance, then that result is similarly consumed by the addition
73operation.
74
75```rust
76use rug::Integer;
77let mut a = Integer::from(0xc);
78a = (a << 80) + 0xffee;
79assert_eq!(a.to_string_radix(16), "c0000000000000000ffee");
80//                                 ↑   ↑   ↑   ↑   ↑   ↑
81//                                80  64  48  32  16   0
82```
83
84Bitwise operations on `Integer` values behave as if the value uses a
85two’s-complement representation.
86
87```rust
88use rug::Integer;
89
90let mut i = Integer::from(1);
91i = i << 1000;
92// i is now 1000000... (1000 zeros)
93assert_eq!(i.significant_bits(), 1001);
94assert_eq!(i.find_one(0), Some(1000));
95i -= 1;
96// i is now 111111... (1000 ones)
97assert_eq!(i.count_ones(), Some(1000));
98
99let a = Integer::from(0xf00d);
100// -1 is all ones in two’s complement
101let all_ones_xor_a = Integer::from(-1 ^ &a);
102// a is unchanged as we borrowed it
103let complement_a = !a;
104// now a has been moved, so this would cause an error:
105// assert!(a > 0);
106assert_eq!(all_ones_xor_a, complement_a);
107assert_eq!(complement_a, -0xf00e);
108assert_eq!(format!("{:x}", complement_a), "-f00e");
109```
110
111To initialize a large `Integer` that does not fit in a primitive type, you can
112parse a string.
113
114```rust
115use rug::Integer;
116let s1 = "123456789012345678901234567890";
117let i1 = s1.parse::<Integer>().unwrap();
118assert_eq!(i1.significant_bits(), 97);
119let s2 = "ffff0000ffff0000ffff0000ffff0000ffff0000";
120let i2 = Integer::from_str_radix(s2, 16).unwrap();
121assert_eq!(i2.significant_bits(), 160);
122assert_eq!(i2.count_ones(), Some(80));
123```
124
125Operations on two borrowed `Integer` values result in an [incomplete-computation
126value][icv] that has to be assigned to a new `Integer` value.
127
128```rust
129use rug::Integer;
130let a = Integer::from(10);
131let b = Integer::from(3);
132let a_b_ref = &a + &b;
133let a_b = Integer::from(a_b_ref);
134assert_eq!(a_b, 13);
135```
136
137As a special case, when an [incomplete-computation value][icv] is obtained from
138multiplying two `Integer` references, it can be added to or subtracted from
139another `Integer` (or reference). This can be useful for multiply-accumulate
140operations.
141
142```rust
143use rug::Integer;
144let mut acc = Integer::from(100);
145let m1 = Integer::from(3);
146let m2 = Integer::from(7);
147// 100 + 3 × 7 = 121
148acc += &m1 * &m2;
149assert_eq!(acc, 121);
150let other = Integer::from(2000);
151// Do not consume any values here:
152// 2000 - 3 × 7 = 1979
153let sub = Integer::from(&other - &m1 * &m2);
154assert_eq!(sub, 1979);
155```
156
157The `Integer` type supports various functions. Most methods have three versions:
158
159 1. The first method consumes the operand.
160 2. The second method has a “`_mut`” suffix and mutates the operand.
161 3. The third method has a “`_ref`” suffix and borrows the operand. The returned
162    item is an [incomplete-computation value][icv] that can be assigned to an
163    `Integer`.
164
165```rust
166use rug::Integer;
167
168// 1. consume the operand
169let a = Integer::from(-15);
170let abs_a = a.abs();
171assert_eq!(abs_a, 15);
172
173// 2. mutate the operand
174let mut b = Integer::from(-16);
175b.abs_mut();
176assert_eq!(b, 16);
177
178// 3. borrow the operand
179let c = Integer::from(-17);
180let r = c.abs_ref();
181let abs_c = Integer::from(r);
182assert_eq!(abs_c, 17);
183// c was not consumed
184assert_eq!(c, -17);
185```
186
187[icv]: crate#incomplete-computation-values
188*/
189#[repr(transparent)]
190pub struct Integer {
191    inner: mpz_t,
192}
193
194impl Integer {
195    #[inline]
196    pub(crate) const fn inner(&self) -> &mpz_t {
197        &self.inner
198    }
199    #[inline]
200    pub(crate) unsafe fn inner_mut(&mut self) -> &mut mpz_t {
201        &mut self.inner
202    }
203    #[inline]
204    pub(crate) const fn inner_data(&self) -> &[limb_t] {
205        let limbs = self.inner.size.unsigned_abs();
206        let limbs_usize = limbs as usize;
207        if limbs != limbs_usize as c_uint {
208            panic!("overflow");
209        }
210        unsafe { slice::from_raw_parts(self.inner.d.as_ptr(), limbs_usize) }
211    }
212}
213
214static_assert_same_layout!(Integer, mpz_t);
215static_assert_same_layout!(BorrowInteger<'_>, mpz_t);
216
217static_assert_same_size!(Integer, Option<Integer>);
218
219impl Integer {
220    /// Zero.
221    ///
222    /// # Examples
223    ///
224    /// ```rust
225    /// use rug::Integer;
226    /// assert_eq!(Integer::ZERO, 0);
227    /// ```
228    pub const ZERO: Integer = Integer::new();
229
230    /// One.
231    ///
232    /// # Examples
233    ///
234    /// ```rust
235    /// use rug::Integer;
236    /// assert_eq!(*Integer::ONE, 1);
237    /// ```
238    pub const ONE: &'static Integer = {
239        const MINI: MiniInteger = MiniInteger::const_from_bool(true);
240        const BORROW: BorrowInteger = MINI.borrow();
241        BorrowInteger::const_deref(&BORROW)
242    };
243
244    /// Negative one (&minus;1).
245    ///
246    /// # Examples
247    ///
248    /// ```rust
249    /// use rug::Integer;
250    /// assert_eq!(*Integer::NEG_ONE, -1);
251    /// ```
252    pub const NEG_ONE: &'static Integer = {
253        const BORROW: BorrowInteger = Integer::ONE.as_neg();
254        BorrowInteger::const_deref(&BORROW)
255    };
256
257    /// Constructs a new arbitrary-precision [`Integer`] with value 0.
258    ///
259    /// The created [`Integer`] will have no allocated memory yet.
260    ///
261    /// # Examples
262    ///
263    /// ```rust
264    /// use rug::Integer;
265    /// let i = Integer::new();
266    /// assert_eq!(i, 0);
267    /// ```
268    #[inline]
269    pub const fn new() -> Self {
270        Integer {
271            inner: xmpz::owned_init(),
272        }
273    }
274
275    /// Constructs a new arbitrary-precision [`Integer`] with at least the
276    /// specified capacity.
277    ///
278    /// # Examples
279    ///
280    /// ```rust
281    /// use rug::Integer;
282    /// let i = Integer::with_capacity(137);
283    /// assert!(i.capacity() >= 137);
284    /// ```
285    #[inline]
286    pub fn with_capacity(bits: usize) -> Self {
287        unsafe {
288            let mut dst = MaybeUninit::uninit();
289            xmpz::init2(dst.as_mut_ptr(), bits);
290            dst.assume_init()
291        }
292    }
293
294    /// Returns the capacity in bits that can be stored without reallocating.
295    ///
296    /// # Examples
297    ///
298    /// ```rust
299    /// use rug::Integer;
300    /// let i = Integer::with_capacity(137);
301    /// assert!(i.capacity() >= 137);
302    /// ```
303    #[inline]
304    pub fn capacity(&self) -> usize {
305        self.inner
306            .alloc
307            .strict_as::<usize>()
308            .checked_mul(gmp::LIMB_BITS.az::<usize>())
309            .expect("overflow")
310    }
311
312    /// Reserves capacity for at least `additional` more bits in the
313    /// [`Integer`].
314    ///
315    /// If the integer already has enough excess capacity, this function does
316    /// nothing.
317    ///
318    /// # Examples
319    ///
320    /// ```rust
321    /// use rug::Integer;
322    /// // 0x2000_0000 needs 30 bits.
323    /// let mut i = Integer::from(0x2000_0000);
324    /// assert_eq!(i.significant_bits(), 30);
325    /// i.reserve(290);
326    /// let capacity = i.capacity();
327    /// assert!(capacity >= 320);
328    /// i.reserve(0);
329    /// assert_eq!(i.capacity(), capacity);
330    /// i.reserve(291);
331    /// assert!(i.capacity() >= 321);
332    /// ```
333    pub fn reserve(&mut self, additional: usize) {
334        let used_bits = xmpz::significant_bits(self);
335        let req_bits = used_bits.checked_add(additional).expect("overflow");
336        let alloc_bits = (self.inner.alloc.az::<usize>())
337            .checked_mul(gmp::LIMB_BITS.az::<usize>())
338            .expect("overflow");
339        if alloc_bits < req_bits {
340            unsafe {
341                gmp::mpz_realloc2(self.as_raw_mut(), req_bits.strict_cast());
342            }
343        }
344    }
345
346    /// Shrinks the capacity of the [`Integer`] as much as possible.
347    ///
348    /// The capacity can still be larger than the number of significant bits.
349    ///
350    /// # Examples
351    ///
352    /// ```rust
353    /// use rug::Integer;
354    /// // let i be 100 bits wide
355    /// let mut i = Integer::from_str_radix("fffff12345678901234567890", 16)
356    ///     .unwrap();
357    /// assert_eq!(i.significant_bits(), 100);
358    /// assert!(i.capacity() >= 100);
359    /// i >>= 80;
360    /// i.shrink_to_fit();
361    /// assert!(i.capacity() >= 20);
362    /// ```
363    pub fn shrink_to_fit(&mut self) {
364        self.shrink_to(0);
365    }
366
367    /// Shrinks the capacity of the [`Integer`] with a lower bound in bits.
368    ///
369    /// The capacity will remain at least as large as both the current number of
370    /// siginificant bits and the supplied value.
371    ///
372    /// If the current capacity is less than the lower limit, this method has no
373    /// effect.
374    ///
375    /// # Examples
376    ///
377    /// ```rust
378    /// use rug::Integer;
379    /// // let i be 100 bits wide
380    /// let mut i = Integer::from_str_radix("fffff12345678901234567890", 16)
381    ///     .unwrap();
382    /// assert_eq!(i.significant_bits(), 100);
383    /// assert!(i.capacity() >= 100);
384    /// i >>= 80;
385    /// i.shrink_to(50);
386    /// assert!(i.capacity() >= 50);
387    /// i.shrink_to(0);
388    /// assert!(i.capacity() >= 20);
389    /// ```
390    pub fn shrink_to(&mut self, min_capacity: usize) {
391        let min_limbs = DivRounding::div_ceil(min_capacity, gmp::LIMB_BITS.az::<usize>());
392        if min_limbs >= self.inner.alloc.strict_as::<usize>() {
393            return;
394        }
395        let used_limbs = self.inner.size.checked_abs().expect("overflow");
396        if min_limbs > used_limbs.strict_as::<usize>() {
397            // we already know that self.inner.alloc > min_limbs
398            // and that min_limbs > 0
399            unsafe {
400                gmp::_mpz_realloc(self.as_raw_mut(), min_limbs.strict_cast());
401            }
402        } else if self.inner.alloc > used_limbs {
403            if used_limbs == 0 {
404                *self = Integer::ZERO;
405            } else {
406                unsafe {
407                    gmp::_mpz_realloc(self.as_raw_mut(), used_limbs.strict_cast());
408                }
409            }
410        }
411    }
412
413    /// Creates an [`Integer`] from an initialized [GMP integer][mpz_t].
414    ///
415    /// # Safety
416    ///
417    ///   * The function must *not* be used to create a constant [`Integer`],
418    ///     though it can be used to create a static [`Integer`]. This is
419    ///     because constant values are *copied* on use, leading to undefined
420    ///     behavior when they are dropped.
421    ///   * The value must be initialized as a valid [`mpz_t`].
422    ///   * The [`mpz_t`] type can be considered as a kind of pointer, so there
423    ///     can be multiple copies of it. Since this function takes over
424    ///     ownership, no other copies of the passed value should exist.
425    ///
426    /// # Examples
427    ///
428    /// ```rust
429    /// use core::mem::MaybeUninit;
430    /// use gmp_mpfr_sys::gmp;
431    /// use rug::Integer;
432    /// let i = unsafe {
433    ///     let mut z = MaybeUninit::uninit();
434    ///     gmp::mpz_init_set_ui(z.as_mut_ptr(), 15);
435    ///     let z = z.assume_init();
436    ///     // z is initialized and unique
437    ///     Integer::from_raw(z)
438    /// };
439    /// assert_eq!(i, 15);
440    /// // since i is an Integer now, deallocation is automatic
441    /// ```
442    ///
443    /// This can be used to create a static [`Integer`] using
444    /// [`MPZ_ROINIT_N`][gmp::MPZ_ROINIT_N] to initialize the raw value. See the
445    /// [GMP documentation][gmp roinit] for details.
446    ///
447    /// ```rust
448    /// use gmp_mpfr_sys::gmp;
449    /// use gmp_mpfr_sys::gmp::{limb_t, mpz_t};
450    /// use rug::Integer;
451    /// const LIMBS: [limb_t; 2] = [123, 456];
452    /// const MPZ: mpz_t =
453    ///     unsafe { gmp::MPZ_ROINIT_N(LIMBS.as_ptr().cast_mut(), -2) };
454    /// // Must *not* be const, otherwise it would lead to undefined
455    /// // behavior on use, as it would create a copy that is dropped.
456    /// static I: Integer = unsafe { Integer::from_raw(MPZ) };
457    /// let check = -((Integer::from(LIMBS[1]) << gmp::NUMB_BITS) + LIMBS[0]);
458    /// assert_eq!(I, check);
459    /// ```
460    ///
461    /// [gmp roinit]: gmp_mpfr_sys::C::GMP::Integer_Functions#index-MPZ_005fROINIT_005fN
462    #[inline]
463    pub const unsafe fn from_raw(raw: mpz_t) -> Self {
464        Integer { inner: raw }
465    }
466
467    /// Converts an [`Integer`] into a [GMP integer][mpz_t].
468    ///
469    /// The returned object should be freed to avoid memory leaks.
470    ///
471    /// # Examples
472    ///
473    /// ```rust
474    /// use gmp_mpfr_sys::gmp;
475    /// use rug::Integer;
476    /// let i = Integer::from(15);
477    /// let mut z = i.into_raw();
478    /// unsafe {
479    ///     let u = gmp::mpz_get_ui(&z);
480    ///     assert_eq!(u, 15);
481    ///     // free object to prevent memory leak
482    ///     gmp::mpz_clear(&mut z);
483    /// }
484    /// ```
485    #[inline]
486    pub const fn into_raw(self) -> mpz_t {
487        let ret = self.inner;
488        let _ = ManuallyDrop::new(self);
489        ret
490    }
491
492    /// Returns a pointer to the inner [GMP integer][mpz_t].
493    ///
494    /// The returned pointer will be valid for as long as `self` is valid.
495    ///
496    /// # Examples
497    ///
498    /// ```rust
499    /// use gmp_mpfr_sys::gmp;
500    /// use rug::Integer;
501    /// let i = Integer::from(15);
502    /// let z_ptr = i.as_raw();
503    /// unsafe {
504    ///     let u = gmp::mpz_get_ui(z_ptr);
505    ///     assert_eq!(u, 15);
506    /// }
507    /// // i is still valid
508    /// assert_eq!(i, 15);
509    /// ```
510    #[inline]
511    pub const fn as_raw(&self) -> *const mpz_t {
512        &self.inner
513    }
514
515    /// Returns an unsafe mutable pointer to the inner [GMP integer][mpz_t].
516    ///
517    /// The returned pointer will be valid for as long as `self` is valid.
518    ///
519    /// # Examples
520    ///
521    /// ```rust
522    /// use gmp_mpfr_sys::gmp;
523    /// use rug::Integer;
524    /// let mut i = Integer::from(15);
525    /// let z_ptr = i.as_raw_mut();
526    /// unsafe {
527    ///     gmp::mpz_add_ui(z_ptr, z_ptr, 20);
528    /// }
529    /// assert_eq!(i, 35);
530    /// ```
531    #[inline]
532    pub fn as_raw_mut(&mut self) -> *mut mpz_t {
533        &mut self.inner
534    }
535
536    /// Creates an [`Integer`] from a [slice] of digits of type `T`, where `T`
537    /// can be any [unsigned integer primitive type][UnsignedPrimitive].
538    ///
539    /// The resulting value cannot be negative.
540    ///
541    /// # Examples
542    ///
543    /// ```rust
544    /// use rug::integer::Order;
545    /// use rug::Integer;
546    /// let digits = [0x5678u16, 0x1234u16];
547    /// let i = Integer::from_digits(&digits, Order::Lsf);
548    /// assert_eq!(i, 0x1234_5678);
549    /// ```
550    ///
551    /// [slice]: prim@slice
552    pub fn from_digits<T: UnsignedPrimitive>(digits: &[T], order: Order) -> Self {
553        let capacity = digits.len().checked_mul(T::PRIVATE.bits).expect("overflow");
554        let mut i = Integer::with_capacity(capacity);
555        i.assign_digits(digits, order);
556        i
557    }
558
559    /// Assigns from a [slice] of digits of type `T`, where `T` can be any
560    /// [unsigned integer primitive type][UnsignedPrimitive].
561    ///
562    /// The resulting value cannot be negative.
563    ///
564    /// # Examples
565    ///
566    /// ```rust
567    /// use rug::integer::Order;
568    /// use rug::Integer;
569    /// let digits = [0x5678u16, 0x1234u16];
570    /// let mut i = Integer::new();
571    /// i.assign_digits(&digits, Order::Lsf);
572    /// assert_eq!(i, 0x1234_5678);
573    /// ```
574    ///
575    /// [slice]: prim@slice
576    pub fn assign_digits<T: UnsignedPrimitive>(&mut self, digits: &[T], order: Order) {
577        // Safety: it is valid to read digits.len() digits from digits.as_mut_ptr().
578        unsafe {
579            self.assign_digits_unaligned(digits.as_ptr(), digits.len(), order);
580        }
581    }
582
583    /// Assigns from digits of type `T` in a memory area, where `T` can be any
584    /// [unsigned integer primitive type][UnsignedPrimitive].
585    ///
586    /// The memory area is addressed using a pointer and a length. The `len`
587    /// parameter is the number of digits, *not* the number of bytes.
588    ///
589    /// There are no data alignment restrictions on `src`, any address is
590    /// allowed.
591    ///
592    /// The resulting value cannot be negative.
593    ///
594    /// # Safety
595    ///
596    /// To avoid undefined behavior, `src` must be [valid] for reading `len`
597    /// digits, that is `len` × `size_of::<T>()` bytes.
598    ///
599    /// # Examples
600    ///
601    /// ```rust
602    /// use rug::integer::Order;
603    /// use rug::Integer;
604    /// // hex bytes: [ fe dc ba 98 87 87 87 87 76 54 32 10 ]
605    /// let digits = [
606    ///     0xfedc_ba98u32.to_be(),
607    ///     0x8787_8787u32.to_be(),
608    ///     0x7654_3210u32.to_be(),
609    /// ];
610    /// let ptr = digits.as_ptr();
611    /// let mut i = Integer::new();
612    /// unsafe {
613    ///     let unaligned = (ptr.cast::<u8>()).offset(2).cast::<u32>();
614    ///     i.assign_digits_unaligned(unaligned, 2, Order::MsfBe);
615    /// }
616    /// assert_eq!(i, 0xba98_8787_8787_7654u64);
617    /// ```
618    ///
619    /// [valid]: core::ptr#safety
620    pub unsafe fn assign_digits_unaligned<T: UnsignedPrimitive>(
621        &mut self,
622        src: *const T,
623        len: usize,
624        order: Order,
625    ) {
626        let bytes = mem::size_of::<T>();
627        let nails = 8 * bytes - T::PRIVATE.bits;
628        let raw = self.as_raw_mut();
629        let (order, endian) = (order.order(), order.endian());
630        let src = src.cast();
631        unsafe {
632            gmp::mpz_import(raw, len, order, bytes, endian, nails, src);
633        }
634    }
635
636    /// Returns the number of digits of type `T` required to represent the
637    /// absolute value.
638    ///
639    /// `T` can be any [unsigned integer primitive type][UnsignedPrimitive].
640    ///
641    /// # Examples
642    ///
643    /// ```rust
644    /// use rug::Integer;
645    ///
646    /// let i: Integer = Integer::from(1) << 256;
647    /// assert_eq!(i.significant_digits::<bool>(), 257);
648    /// assert_eq!(i.significant_digits::<u8>(), 33);
649    /// assert_eq!(i.significant_digits::<u16>(), 17);
650    /// assert_eq!(i.significant_digits::<u32>(), 9);
651    /// assert_eq!(i.significant_digits::<u64>(), 5);
652    /// ```
653    #[inline]
654    pub fn significant_digits<T: UnsignedPrimitive>(&self) -> usize {
655        DivRounding::div_ceil(xmpz::significant_bits(self), T::PRIVATE.bits)
656    }
657
658    /// Converts the absolute value to a [`Vec`] of digits of type `T`, where
659    /// `T` can be any [unsigned integer primitive type][UnsignedPrimitive].
660    ///
661    /// The [`Integer`] type also has the [`as_limbs`][Integer::as_limbs]
662    /// method, which can be used to borrow the digits without copying them.
663    /// This does come with some more constraints compared to `to_digits`:
664    ///
665    ///  1. The digit width is not optional and depends on the implementation:
666    ///     [`limb_t`] is typically [`u64`] on 64-bit systems and [`u32`] on
667    ///     32-bit systems.
668    ///  2. The order is not optional and is least significant digit first, with
669    ///     each digit in the target’s endianness, equivalent to
670    ///     <code>[Order]::[Lsf][Order::Lsf]</code>.
671    ///
672    /// # Examples
673    ///
674    /// ```rust
675    /// use rug::integer::Order;
676    /// use rug::Integer;
677    /// let i = Integer::from(0x1234_5678_9abc_def0u64);
678    /// let digits = i.to_digits::<u32>(Order::MsfBe);
679    /// assert_eq!(digits, [0x1234_5678u32.to_be(), 0x9abc_def0u32.to_be()]);
680    ///
681    /// let zero = Integer::new();
682    /// let digits_zero = zero.to_digits::<u32>(Order::MsfBe);
683    /// assert!(digits_zero.is_empty());
684    /// ```
685    #[cfg(feature = "std")]
686    pub fn to_digits<T: UnsignedPrimitive>(&self, order: Order) -> Vec<T> {
687        let digit_count = self.significant_digits::<T>();
688        let mut v = Vec::<T>::with_capacity(digit_count);
689        unsafe {
690            let digits_ptr = v.as_mut_ptr();
691            let mut count = MaybeUninit::uninit();
692            gmp::mpz_export(
693                digits_ptr.cast(),
694                count.as_mut_ptr(),
695                order.order(),
696                T::PRIVATE.bytes,
697                order.endian(),
698                T::PRIVATE.nails,
699                self.as_raw(),
700            );
701            assert_eq!(count.assume_init(), digit_count);
702            v.set_len(digit_count);
703        }
704        v
705    }
706
707    /// Writes the absolute value into a [slice] of digits of type `T`, where
708    /// `T` can be any [unsigned integer primitive type][UnsignedPrimitive].
709    ///
710    /// The slice must be large enough to hold the digits; the minimum size can
711    /// be obtained using the [`significant_digits`] method.
712    ///
713    /// # Panics
714    ///
715    /// Panics if the slice does not have sufficient capacity.
716    ///
717    /// # Examples
718    ///
719    /// ```rust
720    /// use rug::integer::Order;
721    /// use rug::Integer;
722    /// let i = Integer::from(0x1234_5678_9abc_def0u64);
723    /// let mut digits = [0xffff_ffffu32; 4];
724    /// i.write_digits(&mut digits, Order::MsfBe);
725    /// let word0 = 0x9abc_def0u32;
726    /// let word1 = 0x1234_5678u32;
727    /// assert_eq!(digits, [0, 0, word1.to_be(), word0.to_be()]);
728    /// ```
729    ///
730    /// [`significant_digits`]: `Integer::significant_digits`
731    /// [slice]: prim@slice
732    pub fn write_digits<T: UnsignedPrimitive>(&self, digits: &mut [T], order: Order) {
733        // Safety: it is valid to write digits.len() digits into digits.as_mut_ptr().
734        unsafe {
735            self.write_digits_unaligned(digits.as_mut_ptr(), digits.len(), order);
736        }
737    }
738
739    /// Writes the absolute value into a memory area of digits of type `T`,
740    /// where `T` can be any [unsigned integer primitive
741    /// type][UnsignedPrimitive].
742    ///
743    /// The memory area is addressed using a pointer and a length. The `len`
744    /// parameter is the number of digits, *not* the number of bytes.
745    ///
746    /// The length must be large enough to hold the digits; the minimum length
747    /// can be obtained using the [`significant_digits`] method.
748    ///
749    /// There are no data alignment restrictions on `dst`, any address is
750    /// allowed.
751    ///
752    /// The memory locations can be uninitialized before this method is called;
753    /// this method sets all `len` elements, padding with zeros if the length is
754    /// larger than required.
755    ///
756    /// # Safety
757    ///
758    /// To avoid undefined behavior, `dst` must be [valid] for writing `len`
759    /// digits, that is `len` × `size_of::<T>()` bytes.
760    ///
761    /// # Panics
762    ///
763    /// Panics if the length is less than the number of digits.
764    ///
765    /// # Examples
766    ///
767    /// ```rust
768    /// use rug::integer::Order;
769    /// use rug::Integer;
770    /// let i = Integer::from(0xfedc_ba98_7654_3210u64);
771    /// let mut digits = [0xffff_ffffu32; 4];
772    /// let ptr = digits.as_mut_ptr();
773    /// unsafe {
774    ///     let unaligned = (ptr.cast::<u8>()).offset(2).cast::<u32>();
775    ///     i.write_digits_unaligned(unaligned, 3, Order::MsfBe);
776    /// }
777    /// assert_eq!(
778    ///     digits,
779    ///     [
780    ///         0xffff_0000u32.to_be(),
781    ///         0x0000_fedcu32.to_be(),
782    ///         0xba98_7654u32.to_be(),
783    ///         0x3210_ffffu32.to_be(),
784    ///     ]
785    /// );
786    /// ```
787    ///
788    /// The following example shows how to write into uninitialized memory. In
789    /// practice, the following code could be replaced by a call to the safe
790    /// method [`to_digits`].
791    ///
792    /// ```rust
793    /// use rug::integer::Order;
794    /// use rug::Integer;
795    /// let i = Integer::from(0x1234_5678_9abc_def0u64);
796    /// let len = i.significant_digits::<u32>();
797    /// assert_eq!(len, 2);
798    ///
799    /// // The following code is equivalent to:
800    /// //     let digits = i.to_digits::<u32>(Order::MsfBe);
801    /// let mut digits = Vec::<u32>::with_capacity(len);
802    /// let ptr = digits.as_mut_ptr();
803    /// unsafe {
804    ///     i.write_digits_unaligned(ptr, len, Order::MsfBe);
805    ///     digits.set_len(len);
806    /// }
807    ///
808    /// assert_eq!(digits, [0x1234_5678u32.to_be(), 0x9abc_def0u32.to_be()]);
809    /// ```
810    ///
811    /// [`significant_digits`]: `Integer::significant_digits`
812    /// [`to_digits`]: `Integer::to_digits`
813    /// [valid]: `core::ptr`#safety
814    pub unsafe fn write_digits_unaligned<T: UnsignedPrimitive>(
815        &self,
816        dst: *mut T,
817        len: usize,
818        order: Order,
819    ) {
820        let digit_count = self.significant_digits::<T>();
821        let zero_count = len.checked_sub(digit_count).expect("not enough capacity");
822        let zero_bytes = zero_count * T::PRIVATE.bytes;
823        let (zeros, digits) = if order.order() < 0 {
824            let offset = digit_count.strict_cast();
825            (unsafe { dst.offset(offset) }, dst)
826        } else {
827            let offset = zero_count.strict_cast();
828            (dst, unsafe { dst.offset(offset) })
829        };
830        unsafe {
831            // use *mut u8 to allow for unaligned pointers
832            (zeros.cast::<u8>()).write_bytes(0, zero_bytes);
833        }
834        let mut count = MaybeUninit::uninit();
835        let digits = digits.cast();
836        let count_ptr = count.as_mut_ptr();
837        let (order, endian) = (order.order(), order.endian());
838        let raw = self.as_raw();
839        unsafe {
840            gmp::mpz_export(
841                digits,
842                count_ptr,
843                order,
844                T::PRIVATE.bytes,
845                endian,
846                T::PRIVATE.nails,
847                raw,
848            );
849        }
850        assert_eq!(unsafe { count.assume_init() }, digit_count);
851    }
852
853    /// Extracts a [slice] of [limbs][limb_t] used to store the value.
854    ///
855    /// The [slice] contains the absolute value of `self`, with the least
856    /// significant limb first.
857    ///
858    /// The [`Integer`] type also implements
859    /// <code>[AsRef]\<[\[][slice][limb_t][][\]][slice]></code>, which is
860    /// equivalent to this method.
861    ///
862    /// # Examples
863    ///
864    /// ```rust
865    /// use rug::Integer;
866    /// assert!(Integer::new().as_limbs().is_empty());
867    /// assert_eq!(Integer::from(13).as_limbs(), &[13]);
868    /// assert_eq!(Integer::from(-23).as_limbs(), &[23]);
869    /// ```
870    ///
871    /// `int.as_limbs()` is like a borrowing non-copy version of
872    /// <code>int.[to\_digits][Integer::to_digits]::\<[limb\_t]>([Order]::[Lsf][Order::Lsf])</code>.
873    ///
874    /// ```rust
875    /// use gmp_mpfr_sys::gmp::limb_t;
876    /// use rug::integer::Order;
877    /// use rug::Integer;
878    /// let int = Integer::from(0x1234_5678_9abc_def0u64);
879    /// // no copying for int_slice, which is borrowing int
880    /// let int_slice = int.as_limbs();
881    /// // digits is a copy and does not borrow int
882    /// let digits = int.to_digits::<limb_t>(Order::Lsf);
883    /// // no copying for digits_slice, which is borrowing digits
884    /// let digits_slice = &digits[..];
885    /// assert_eq!(int_slice, digits_slice);
886    /// ```
887    ///
888    /// [slice]: prim@slice
889    pub const fn as_limbs(&self) -> &[limb_t] {
890        self.inner_data()
891    }
892
893    /// Creates an [`Integer`] from an [`f32`] if it is
894    /// [finite][f32::is_finite], rounding towards zero.
895    ///
896    /// This conversion can also be performed using
897    /// <code>value.[checked\_as]::\<[Integer]>()</code>.
898    ///
899    /// # Examples
900    ///
901    /// ```rust
902    /// use rug::Integer;
903    /// let i = Integer::from_f32(-5.6).unwrap();
904    /// assert_eq!(i, -5);
905    /// let neg_inf = Integer::from_f32(f32::NEG_INFINITY);
906    /// assert!(neg_inf.is_none());
907    /// ```
908    ///
909    /// [checked\_as]: az::CheckedAs::checked_as
910    #[inline]
911    pub fn from_f32(value: f32) -> Option<Self> {
912        value.checked_cast()
913    }
914
915    /// Creates an [`Integer`] from an [`f64`] if it is
916    /// [finite][f64::is_finite], rounding towards zero.
917    ///
918    /// This conversion can also be performed using
919    /// <code>value.[checked\_as]::\<[Integer]>()</code>.
920    ///
921    /// # Examples
922    ///
923    /// ```rust
924    /// use rug::Integer;
925    /// let i = Integer::from_f64(1e20).unwrap();
926    /// assert_eq!(i, "100000000000000000000".parse::<Integer>().unwrap());
927    /// let inf = Integer::from_f64(f64::INFINITY);
928    /// assert!(inf.is_none());
929    /// ```
930    ///
931    /// [checked\_as]: az::CheckedAs::checked_as
932    #[inline]
933    pub fn from_f64(value: f64) -> Option<Self> {
934        value.checked_cast()
935    }
936
937    /// Parses an [`Integer`] using the given radix.
938    ///
939    /// # Panics
940    ///
941    /// Panics if `radix` is less than 2 or greater than 36.
942    ///
943    /// # Examples
944    ///
945    /// ```rust
946    /// use rug::Integer;
947    /// let i = Integer::from_str_radix("-ff", 16).unwrap();
948    /// assert_eq!(i, -0xff);
949    /// ```
950    #[inline]
951    pub fn from_str_radix(src: &str, radix: i32) -> Result<Self, ParseIntegerError> {
952        Ok(Integer::from(Integer::parse_radix(src, radix)?))
953    }
954
955    /// Parses a decimal string slice (<code>\&[str]</code>) or byte slice
956    /// (<code>[\&\[][slice][u8][][\]][slice]</code>) into an [`Integer`].
957    ///
958    /// The following are implemented with the unwrapped returned
959    /// [incomplete-computation value][icv] as `Src`:
960    ///   * <code>[Assign]\<Src> for [Integer]</code>
961    ///   * <code>[From]\<Src> for [Integer]</code>
962    ///   * <code>[Complete]\<[Completed][Complete::Completed] = [Integer]> for Src</code>
963    ///
964    /// The string can start with an optional minus or plus sign. ASCII
965    /// whitespace is ignored everywhere in the string. Underscores anywhere
966    /// except before the first digit are ignored as well.
967    ///
968    /// # Examples
969    ///
970    /// ```rust
971    /// use rug::{Complete, Integer};
972    ///
973    /// assert_eq!(Integer::parse("1223").unwrap().complete(), 1223);
974    /// assert_eq!(Integer::parse("123 456 789").unwrap().complete(), 123_456_789);
975    ///
976    /// let invalid = Integer::parse("789a");
977    /// assert!(invalid.is_err());
978    /// ```
979    ///
980    /// [icv]: crate#incomplete-computation-values
981    /// [slice]: prim@slice
982    #[inline]
983    pub fn parse<S: AsRef<[u8]>>(src: S) -> Result<ParseIncomplete, ParseIntegerError> {
984        parse(src.as_ref(), 10)
985    }
986
987    /// Parses a string slice (<code>\&[str]</code>) or byte slice
988    /// (<code>[\&\[][slice][u8][][\]][slice]</code>) into an
989    /// [`Integer`].
990    ///
991    /// The following are implemented with the unwrapped returned
992    /// [incomplete-computation value][icv] as `Src`:
993    ///   * <code>[Assign]\<Src> for [Integer]</code>
994    ///   * <code>[From]\<Src> for [Integer]</code>
995    ///   * <code>[Complete]\<[Completed][Complete::Completed] = [Integer]> for Src</code>
996    ///
997    /// The string can start with an optional minus or plus sign. ASCII
998    /// whitespace is ignored everywhere in the string. Underscores anywhere
999    /// except before the first digit are ignored as well.
1000    ///
1001    /// See also [`assign_bytes_radix_unchecked`], which is an unsafe low-level
1002    /// method that can be used if parsing is already done by an external
1003    /// function.
1004    ///
1005    /// # Panics
1006    ///
1007    /// Panics if `radix` is less than 2 or greater than 36.
1008    ///
1009    /// # Examples
1010    ///
1011    /// ```rust
1012    /// use rug::{Complete, Integer};
1013    ///
1014    /// let valid1 = Integer::parse_radix("1223", 4);
1015    /// assert_eq!(valid1.unwrap().complete(), 3 + 4 * (2 + 4 * (2 + 4 * 1)));
1016    /// let valid2 = Integer::parse_radix("1234 abcd", 16);
1017    /// assert_eq!(valid2.unwrap().complete(), 0x1234_abcd);
1018    ///
1019    /// let invalid = Integer::parse_radix("123", 3);
1020    /// assert!(invalid.is_err());
1021    /// ```
1022    ///
1023    /// [`assign_bytes_radix_unchecked`]: Self::assign_bytes_radix_unchecked
1024    /// [icv]: crate#incomplete-computation-values
1025    /// [slice]: prim@slice
1026    #[inline]
1027    pub fn parse_radix<S: AsRef<[u8]>>(
1028        src: S,
1029        radix: i32,
1030    ) -> Result<ParseIncomplete, ParseIntegerError> {
1031        parse(src.as_ref(), radix)
1032    }
1033
1034    /// Assigns from bytes in the given radix.
1035    ///
1036    /// The radix must be between 2 and 256 inclusive.
1037    ///
1038    /// Each byte must be a value from 0 to `radix - 1`, not an ASCII character.
1039    /// The bytes must be ordered most-significant byte first.
1040    ///
1041    /// If `is_negative` is [`true`], the returned value is negative (unless it is 0).
1042    ///
1043    /// # Safety
1044    ///
1045    /// The caller must ensure that
1046    ///
1047    ///   * 2&nbsp;≤&nbsp;`radix`&nbsp;≤&nbsp;256
1048    ///   * all bytes are in the range 0&nbsp;≤&nbsp;<i>x</i>&nbsp;<&nbsp;`radix`
1049    ///
1050    /// # Examples
1051    ///
1052    /// ```rust
1053    /// use rug::Integer;
1054    /// let bytes = &[0, 3, 9, 2];
1055    /// let radix = 10;
1056    /// let neg = true;
1057    /// let mut i = Integer::new();
1058    /// // SAFETY: radix and bytes are in the required ranges
1059    /// unsafe {
1060    ///     i.assign_bytes_radix_unchecked(bytes, radix, neg);
1061    /// }
1062    /// assert_eq!(i, -392);
1063    /// ```
1064    pub unsafe fn assign_bytes_radix_unchecked(
1065        &mut self,
1066        bytes: &[u8],
1067        radix: i32,
1068        is_negative: bool,
1069    ) {
1070        if bytes.is_empty() {
1071            xmpz::set_0(self);
1072            return;
1073        }
1074        xmpz::realloc_for_mpn_set_str(self, bytes.len(), radix);
1075        unsafe {
1076            let size = gmp::mpn_set_str(self.inner.d.as_ptr(), bytes.as_ptr(), bytes.len(), radix);
1077            self.inner.size = (if is_negative { -size } else { size }).strict_cast();
1078        }
1079    }
1080
1081    /// Converts to an [`i8`] if the value fits.
1082    ///
1083    /// This conversion can also be performed using
1084    ///   * <code>[i8]::[try\_from]\(\&integer)</code>
1085    ///   * <code>[i8]::[try\_from]\(integer)</code>
1086    ///   * <code>(\&integer).[checked\_as]::\<[i8]>()</code>
1087    ///   * <code>integer.[borrow]\().[checked\_as]::\<[i8]>()</code>
1088    ///   * <code>integer.[checked\_as]::\<[i8]>()</code>
1089    ///
1090    /// # Examples
1091    ///
1092    /// ```rust
1093    /// use rug::Integer;
1094    /// let fits = Integer::from(-100);
1095    /// assert_eq!(fits.to_i8(), Some(-100));
1096    /// let small = Integer::from(-200);
1097    /// assert_eq!(small.to_i8(), None);
1098    /// let large = Integer::from(200);
1099    /// assert_eq!(large.to_i8(), None);
1100    /// ```
1101    ///
1102    /// [borrow]: core::borrow::Borrow::borrow
1103    /// [checked\_as]: az::CheckedAs::checked_as
1104    /// [try\_from]: core::convert::TryFrom::try_from
1105    #[inline]
1106    pub fn to_i8(&self) -> Option<i8> {
1107        self.checked_cast()
1108    }
1109
1110    /// Converts to an [`i16`] if the value fits.
1111    ///
1112    /// This conversion can also be performed using
1113    ///   * <code>[i16]::[try\_from]\(\&integer)</code>
1114    ///   * <code>[i16]::[try\_from]\(integer)</code>
1115    ///   * <code>(\&integer).[checked\_as]::\<[i16]>()</code>
1116    ///   * <code>integer.[borrow]\().[checked\_as]::\<[i16]>()</code>
1117    ///   * <code>integer.[checked\_as]::\<[i16]>()</code>
1118    ///
1119    /// # Examples
1120    ///
1121    /// ```rust
1122    /// use rug::Integer;
1123    /// let fits = Integer::from(-30_000);
1124    /// assert_eq!(fits.to_i16(), Some(-30_000));
1125    /// let small = Integer::from(-40_000);
1126    /// assert_eq!(small.to_i16(), None);
1127    /// let large = Integer::from(40_000);
1128    /// assert_eq!(large.to_i16(), None);
1129    /// ```
1130    ///
1131    /// [borrow]: core::borrow::Borrow::borrow
1132    /// [checked\_as]: az::CheckedAs::checked_as
1133    /// [try\_from]: core::convert::TryFrom::try_from
1134    #[inline]
1135    pub fn to_i16(&self) -> Option<i16> {
1136        self.checked_cast()
1137    }
1138
1139    /// Converts to an [`i32`] if the value fits.
1140    ///
1141    /// This conversion can also be performed using
1142    ///   * <code>[i32]::[try\_from]\(\&integer)</code>
1143    ///   * <code>[i32]::[try\_from]\(integer)</code>
1144    ///   * <code>(\&integer).[checked\_as]::\<[i32]>()</code>
1145    ///   * <code>integer.[borrow]\().[checked\_as]::\<[i32]>()</code>
1146    ///   * <code>integer.[checked\_as]::\<[i32]>()</code>
1147    ///
1148    /// # Examples
1149    ///
1150    /// ```rust
1151    /// use rug::Integer;
1152    /// let fits = Integer::from(-50);
1153    /// assert_eq!(fits.to_i32(), Some(-50));
1154    /// let small = Integer::from(-123456789012345_i64);
1155    /// assert_eq!(small.to_i32(), None);
1156    /// let large = Integer::from(123456789012345_i64);
1157    /// assert_eq!(large.to_i32(), None);
1158    /// ```
1159    ///
1160    /// [borrow]: core::borrow::Borrow::borrow
1161    /// [checked\_as]: az::CheckedAs::checked_as
1162    /// [try\_from]: core::convert::TryFrom::try_from
1163    #[inline]
1164    pub fn to_i32(&self) -> Option<i32> {
1165        self.checked_cast()
1166    }
1167
1168    /// Converts to an [`i64`] if the value fits.
1169    ///
1170    /// This conversion can also be performed using
1171    ///   * <code>[i64]::[try\_from]\(\&integer)</code>
1172    ///   * <code>[i64]::[try\_from]\(integer)</code>
1173    ///   * <code>(\&integer).[checked\_as]::\<[i64]>()</code>
1174    ///   * <code>integer.[borrow]\().[checked\_as]::\<[i64]>()</code>
1175    ///   * <code>integer.[checked\_as]::\<[i64]>()</code>
1176    ///
1177    /// # Examples
1178    ///
1179    /// ```rust
1180    /// use rug::Integer;
1181    /// let fits = Integer::from(-50);
1182    /// assert_eq!(fits.to_i64(), Some(-50));
1183    /// let small = Integer::from_str_radix("-fedcba9876543210", 16).unwrap();
1184    /// assert_eq!(small.to_i64(), None);
1185    /// let large = Integer::from_str_radix("fedcba9876543210", 16).unwrap();
1186    /// assert_eq!(large.to_i64(), None);
1187    /// ```
1188    ///
1189    /// [borrow]: core::borrow::Borrow::borrow
1190    /// [checked\_as]: az::CheckedAs::checked_as
1191    /// [try\_from]: core::convert::TryFrom::try_from
1192    #[inline]
1193    pub fn to_i64(&self) -> Option<i64> {
1194        self.checked_cast()
1195    }
1196
1197    /// Converts to an [`i128`] if the value fits.
1198    ///
1199    /// This conversion can also be performed using
1200    ///   * <code>[i128]::[try\_from]\(\&integer)</code>
1201    ///   * <code>[i128]::[try\_from]\(integer)</code>
1202    ///   * <code>(\&integer).[checked\_as]::\<[i128]>()</code>
1203    ///   * <code>integer.[borrow]\().[checked\_as]::\<[i128]>()</code>
1204    ///   * <code>integer.[checked\_as]::\<[i128]>()</code>
1205    ///
1206    /// # Examples
1207    ///
1208    /// ```rust
1209    /// use rug::Integer;
1210    /// let fits = Integer::from(-50);
1211    /// assert_eq!(fits.to_i128(), Some(-50));
1212    /// let small: Integer = Integer::from(-1) << 130;
1213    /// assert_eq!(small.to_i128(), None);
1214    /// let large: Integer = Integer::from(1) << 130;
1215    /// assert_eq!(large.to_i128(), None);
1216    /// ```
1217    ///
1218    /// [borrow]: core::borrow::Borrow::borrow
1219    /// [checked\_as]: az::CheckedAs::checked_as
1220    /// [try\_from]: core::convert::TryFrom::try_from
1221    #[inline]
1222    pub fn to_i128(&self) -> Option<i128> {
1223        self.checked_cast()
1224    }
1225
1226    /// Converts to an [`isize`] if the value fits.
1227    ///
1228    /// This conversion can also be performed using
1229    ///   * <code>[isize]::[try\_from]\(\&integer)</code>
1230    ///   * <code>[isize]::[try\_from]\(integer)</code>
1231    ///   * <code>(\&integer).[checked\_as]::\<[isize]>()</code>
1232    ///   * <code>integer.[borrow]\().[checked\_as]::\<[isize]>()</code>
1233    ///   * <code>integer.[checked\_as]::\<[isize]>()</code>
1234    ///
1235    /// # Examples
1236    ///
1237    /// ```rust
1238    /// use rug::Integer;
1239    /// let fits = Integer::from(0x1000);
1240    /// assert_eq!(fits.to_isize(), Some(0x1000));
1241    /// let large: Integer = Integer::from(0x1000) << 128;
1242    /// assert_eq!(large.to_isize(), None);
1243    /// ```
1244    ///
1245    /// [borrow]: core::borrow::Borrow::borrow
1246    /// [checked\_as]: az::CheckedAs::checked_as
1247    /// [try\_from]: core::convert::TryFrom::try_from
1248    #[inline]
1249    pub fn to_isize(&self) -> Option<isize> {
1250        self.checked_cast()
1251    }
1252
1253    /// Converts to an [`u8`] if the value fits.
1254    ///
1255    /// This conversion can also be performed using
1256    ///   * <code>[u8]::[try\_from]\(\&integer)</code>
1257    ///   * <code>[u8]::[try\_from]\(integer)</code>
1258    ///   * <code>(\&integer).[checked\_as]::\<[u8]>()</code>
1259    ///   * <code>integer.[borrow]\().[checked\_as]::\<[u8]>()</code>
1260    ///   * <code>integer.[checked\_as]::\<[u8]>()</code>
1261    ///
1262    /// # Examples
1263    ///
1264    /// ```rust
1265    /// use rug::Integer;
1266    /// let fits = Integer::from(200);
1267    /// assert_eq!(fits.to_u8(), Some(200));
1268    /// let neg = Integer::from(-1);
1269    /// assert_eq!(neg.to_u8(), None);
1270    /// let large = Integer::from(300);
1271    /// assert_eq!(large.to_u8(), None);
1272    /// ```
1273    ///
1274    /// [borrow]: core::borrow::Borrow::borrow
1275    /// [checked\_as]: az::CheckedAs::checked_as
1276    /// [try\_from]: core::convert::TryFrom::try_from
1277    #[inline]
1278    pub fn to_u8(&self) -> Option<u8> {
1279        self.checked_cast()
1280    }
1281
1282    /// Converts to an [`u16`] if the value fits.
1283    ///
1284    /// This conversion can also be performed using
1285    ///   * <code>[u16]::[try\_from]\(\&integer)</code>
1286    ///   * <code>[u16]::[try\_from]\(integer)</code>
1287    ///   * <code>(\&integer).[checked\_as]::\<[u16]>()</code>
1288    ///   * <code>integer.[borrow]\().[checked\_as]::\<[u16]>()</code>
1289    ///   * <code>integer.[checked\_as]::\<[u16]>()</code>
1290    ///
1291    /// # Examples
1292    ///
1293    /// ```rust
1294    /// use rug::Integer;
1295    /// let fits = Integer::from(60_000);
1296    /// assert_eq!(fits.to_u16(), Some(60_000));
1297    /// let neg = Integer::from(-1);
1298    /// assert_eq!(neg.to_u16(), None);
1299    /// let large = Integer::from(70_000);
1300    /// assert_eq!(large.to_u16(), None);
1301    /// ```
1302    ///
1303    /// [borrow]: core::borrow::Borrow::borrow
1304    /// [checked\_as]: az::CheckedAs::checked_as
1305    /// [try\_from]: core::convert::TryFrom::try_from
1306    #[inline]
1307    pub fn to_u16(&self) -> Option<u16> {
1308        self.checked_cast()
1309    }
1310
1311    /// Converts to an [`u32`] if the value fits.
1312    ///
1313    /// This conversion can also be performed using
1314    ///   * <code>[u32]::[try\_from]\(\&integer)</code>
1315    ///   * <code>[u32]::[try\_from]\(integer)</code>
1316    ///   * <code>(\&integer).[checked\_as]::\<[u32]>()</code>
1317    ///   * <code>integer.[borrow]\().[checked\_as]::\<[u32]>()</code>
1318    ///   * <code>integer.[checked\_as]::\<[u32]>()</code>
1319    ///
1320    /// # Examples
1321    ///
1322    /// ```rust
1323    /// use rug::Integer;
1324    /// let fits = Integer::from(1234567890);
1325    /// assert_eq!(fits.to_u32(), Some(1234567890));
1326    /// let neg = Integer::from(-1);
1327    /// assert_eq!(neg.to_u32(), None);
1328    /// let large = Integer::from(123456789012345_u64);
1329    /// assert_eq!(large.to_u32(), None);
1330    /// ```
1331    ///
1332    /// [borrow]: core::borrow::Borrow::borrow
1333    /// [checked\_as]: az::CheckedAs::checked_as
1334    /// [try\_from]: core::convert::TryFrom::try_from
1335    #[inline]
1336    pub fn to_u32(&self) -> Option<u32> {
1337        self.checked_cast()
1338    }
1339
1340    /// Converts to an [`u64`] if the value fits.
1341    ///
1342    /// This conversion can also be performed using
1343    ///   * <code>[u64]::[try\_from]\(\&integer)</code>
1344    ///   * <code>[u64]::[try\_from]\(integer)</code>
1345    ///   * <code>(\&integer).[checked\_as]::\<[u64]>()</code>
1346    ///   * <code>integer.[borrow]\().[checked\_as]::\<[u64]>()</code>
1347    ///   * <code>integer.[checked\_as]::\<[u64]>()</code>
1348    ///
1349    /// # Examples
1350    ///
1351    /// ```rust
1352    /// use rug::Integer;
1353    /// let fits = Integer::from(123456789012345_u64);
1354    /// assert_eq!(fits.to_u64(), Some(123456789012345));
1355    /// let neg = Integer::from(-1);
1356    /// assert_eq!(neg.to_u64(), None);
1357    /// let large = "1234567890123456789012345".parse::<Integer>().unwrap();
1358    /// assert_eq!(large.to_u64(), None);
1359    /// ```
1360    ///
1361    /// [borrow]: core::borrow::Borrow::borrow
1362    /// [checked\_as]: az::CheckedAs::checked_as
1363    /// [try\_from]: core::convert::TryFrom::try_from
1364    #[inline]
1365    pub fn to_u64(&self) -> Option<u64> {
1366        self.checked_cast()
1367    }
1368
1369    /// Converts to an [`u128`] if the value fits.
1370    ///
1371    /// This conversion can also be performed using
1372    ///   * <code>[u128]::[try\_from]\(\&integer)</code>
1373    ///   * <code>[u128]::[try\_from]\(integer)</code>
1374    ///   * <code>(\&integer).[checked\_as]::\<[u128]>()</code>
1375    ///   * <code>integer.[borrow]\().[checked\_as]::\<[u128]>()</code>
1376    ///   * <code>integer.[checked\_as]::\<[u128]>()</code>
1377    ///
1378    /// # Examples
1379    ///
1380    /// ```rust
1381    /// use rug::Integer;
1382    /// let fits = Integer::from(12345678901234567890_u128);
1383    /// assert_eq!(fits.to_u128(), Some(12345678901234567890));
1384    /// let neg = Integer::from(-1);
1385    /// assert_eq!(neg.to_u128(), None);
1386    /// let large = "1234567890123456789012345678901234567890"
1387    ///     .parse::<Integer>()
1388    ///     .unwrap();
1389    /// assert_eq!(large.to_u128(), None);
1390    /// ```
1391    ///
1392    /// [borrow]: core::borrow::Borrow::borrow
1393    /// [checked\_as]: az::CheckedAs::checked_as
1394    /// [try\_from]: core::convert::TryFrom::try_from
1395    #[inline]
1396    pub fn to_u128(&self) -> Option<u128> {
1397        self.checked_cast()
1398    }
1399
1400    /// Converts to an [`usize`] if the value fits.
1401    ///
1402    /// This conversion can also be performed using
1403    ///   * <code>[usize]::[try\_from]\(\&integer)</code>
1404    ///   * <code>[usize]::[try\_from]\(integer)</code>
1405    ///   * <code>(\&integer).[checked\_as]::\<[usize]>()</code>
1406    ///   * <code>integer.[borrow]\().[checked\_as]::\<[usize]>()</code>
1407    ///   * <code>integer.[checked\_as]::\<[usize]>()</code>
1408    ///
1409    /// # Examples
1410    ///
1411    /// ```rust
1412    /// use rug::Integer;
1413    /// let fits = Integer::from(0x1000);
1414    /// assert_eq!(fits.to_usize(), Some(0x1000));
1415    /// let neg = Integer::from(-1);
1416    /// assert_eq!(neg.to_usize(), None);
1417    /// let large: Integer = Integer::from(0x1000) << 128;
1418    /// assert_eq!(large.to_usize(), None);
1419    /// ```
1420    ///
1421    /// [borrow]: core::borrow::Borrow::borrow
1422    /// [checked\_as]: az::CheckedAs::checked_as
1423    /// [try\_from]: core::convert::TryFrom::try_from
1424    #[inline]
1425    pub fn to_usize(&self) -> Option<usize> {
1426        self.checked_cast()
1427    }
1428
1429    /// Converts to an [`i8`], wrapping if the value does not fit.
1430    ///
1431    /// This conversion can also be performed using
1432    ///   * <code>(\&integer).[wrapping\_as]::\<[i8]>()</code>
1433    ///   * <code>integer.[borrow]\().[wrapping\_as]::\<[i8]>()</code>
1434    ///   * <code>integer.[wrapping\_as]::\<[i8]>()</code>
1435    ///
1436    /// # Examples
1437    ///
1438    /// ```rust
1439    /// use rug::Integer;
1440    /// let large = Integer::from(0x1234);
1441    /// assert_eq!(large.to_i8_wrapping(), 0x34);
1442    /// ```
1443    ///
1444    /// [borrow]: core::borrow::Borrow::borrow
1445    /// [wrapping\_as]: az::WrappingAs::wrapping_as
1446    #[inline]
1447    pub fn to_i8_wrapping(&self) -> i8 {
1448        self.wrapping_cast()
1449    }
1450
1451    /// Converts to an [`i16`], wrapping if the value does not fit.
1452    ///
1453    /// This conversion can also be performed using
1454    ///   * <code>(\&integer).[wrapping\_as]::\<[i16]>()</code>
1455    ///   * <code>integer.[borrow]\().[wrapping\_as]::\<[i16]>()</code>
1456    ///   * <code>integer.[wrapping\_as]::\<[i16]>()</code>
1457    ///
1458    /// # Examples
1459    ///
1460    /// ```rust
1461    /// use rug::Integer;
1462    /// let large = Integer::from(0x1234_5678);
1463    /// assert_eq!(large.to_i16_wrapping(), 0x5678);
1464    /// ```
1465    ///
1466    /// [borrow]: core::borrow::Borrow::borrow
1467    /// [wrapping\_as]: az::WrappingAs::wrapping_as
1468    #[inline]
1469    pub fn to_i16_wrapping(&self) -> i16 {
1470        self.wrapping_cast()
1471    }
1472
1473    /// Converts to an [`i32`], wrapping if the value does not fit.
1474    ///
1475    /// This conversion can also be performed using
1476    ///   * <code>(\&integer).[wrapping\_as]::\<[i32]>()</code>
1477    ///   * <code>integer.[borrow]\().[wrapping\_as]::\<[i32]>()</code>
1478    ///   * <code>integer.[wrapping\_as]::\<[i32]>()</code>
1479    ///
1480    /// # Examples
1481    ///
1482    /// ```rust
1483    /// use rug::Integer;
1484    /// let large = Integer::from(0x1234_5678_9abc_def0_u64);
1485    /// assert_eq!(large.to_i32_wrapping(), 0x9abc_def0_u32 as i32);
1486    /// ```
1487    ///
1488    /// [borrow]: core::borrow::Borrow::borrow
1489    /// [wrapping\_as]: az::WrappingAs::wrapping_as
1490    #[inline]
1491    pub fn to_i32_wrapping(&self) -> i32 {
1492        self.wrapping_cast()
1493    }
1494
1495    /// Converts to an [`i64`], wrapping if the value does not fit.
1496    ///
1497    /// This conversion can also be performed using
1498    ///   * <code>(\&integer).[wrapping\_as]::\<[i64]>()</code>
1499    ///   * <code>integer.[borrow]\().[wrapping\_as]::\<[i64]>()</code>
1500    ///   * <code>integer.[wrapping\_as]::\<[i64]>()</code>
1501    ///
1502    /// # Examples
1503    ///
1504    /// ```rust
1505    /// use rug::Integer;
1506    /// let large = Integer::from_str_radix("f123456789abcdef0", 16).unwrap();
1507    /// assert_eq!(large.to_i64_wrapping(), 0x1234_5678_9abc_def0);
1508    /// ```
1509    ///
1510    /// [borrow]: core::borrow::Borrow::borrow
1511    /// [wrapping\_as]: az::WrappingAs::wrapping_as
1512    #[inline]
1513    pub fn to_i64_wrapping(&self) -> i64 {
1514        self.wrapping_cast()
1515    }
1516
1517    /// Converts to an [`i128`], wrapping if the value does not fit.
1518    ///
1519    /// This conversion can also be performed using
1520    ///   * <code>(\&integer).[wrapping\_as]::\<[i128]>()</code>
1521    ///   * <code>integer.[borrow]\().[wrapping\_as]::\<[i128]>()</code>
1522    ///   * <code>integer.[wrapping\_as]::\<[i128]>()</code>
1523    ///
1524    /// # Examples
1525    ///
1526    /// ```rust
1527    /// use rug::Integer;
1528    /// let s = "f123456789abcdef0123456789abcdef0";
1529    /// let large = Integer::from_str_radix(s, 16).unwrap();
1530    /// assert_eq!(
1531    ///     large.to_i128_wrapping(),
1532    ///     0x1234_5678_9abc_def0_1234_5678_9abc_def0
1533    /// );
1534    /// ```
1535    ///
1536    /// [borrow]: core::borrow::Borrow::borrow
1537    /// [wrapping\_as]: az::WrappingAs::wrapping_as
1538    #[inline]
1539    pub fn to_i128_wrapping(&self) -> i128 {
1540        self.wrapping_cast()
1541    }
1542
1543    /// Converts to an [`isize`], wrapping if the value does not fit.
1544    ///
1545    /// This conversion can also be performed using
1546    ///   * <code>(\&integer).[wrapping\_as]::\<[isize]>()</code>
1547    ///   * <code>integer.[borrow]\().[wrapping\_as]::\<[isize]>()</code>
1548    ///   * <code>integer.[wrapping\_as]::\<[isize]>()</code>
1549    ///
1550    /// # Examples
1551    ///
1552    /// ```rust
1553    /// use rug::Integer;
1554    /// let large: Integer = (Integer::from(0x1000) << 128) | 0x1234;
1555    /// assert_eq!(large.to_isize_wrapping(), 0x1234);
1556    /// ```
1557    ///
1558    /// [borrow]: core::borrow::Borrow::borrow
1559    /// [wrapping\_as]: az::WrappingAs::wrapping_as
1560    #[inline]
1561    pub fn to_isize_wrapping(&self) -> isize {
1562        self.wrapping_cast()
1563    }
1564
1565    /// Converts to a [`u8`], wrapping if the value does not fit.
1566    ///
1567    /// This conversion can also be performed using
1568    ///   * <code>(\&integer).[wrapping\_as]::\<[u8]>()</code>
1569    ///   * <code>integer.[borrow]\().[wrapping\_as]::\<[u8]>()</code>
1570    ///   * <code>integer.[wrapping\_as]::\<[u8]>()</code>
1571    ///
1572    /// # Examples
1573    ///
1574    /// ```rust
1575    /// use rug::Integer;
1576    /// let neg = Integer::from(-1);
1577    /// assert_eq!(neg.to_u8_wrapping(), 0xff);
1578    /// let large = Integer::from(0x1234);
1579    /// assert_eq!(large.to_u8_wrapping(), 0x34);
1580    /// ```
1581    ///
1582    /// [borrow]: core::borrow::Borrow::borrow
1583    /// [wrapping\_as]: az::WrappingAs::wrapping_as
1584    #[inline]
1585    pub fn to_u8_wrapping(&self) -> u8 {
1586        self.wrapping_cast()
1587    }
1588
1589    /// Converts to a [`u16`], wrapping if the value does not fit.
1590    ///
1591    /// This conversion can also be performed using
1592    ///   * <code>(\&integer).[wrapping\_as]::\<[u16]>()</code>
1593    ///   * <code>integer.[borrow]\().[wrapping\_as]::\<[u16]>()</code>
1594    ///   * <code>integer.[wrapping\_as]::\<[u16]>()</code>
1595    ///
1596    /// # Examples
1597    ///
1598    /// ```rust
1599    /// use rug::Integer;
1600    /// let neg = Integer::from(-1);
1601    /// assert_eq!(neg.to_u16_wrapping(), 0xffff);
1602    /// let large = Integer::from(0x1234_5678);
1603    /// assert_eq!(large.to_u16_wrapping(), 0x5678);
1604    /// ```
1605    ///
1606    /// [borrow]: core::borrow::Borrow::borrow
1607    /// [wrapping\_as]: az::WrappingAs::wrapping_as
1608    #[inline]
1609    pub fn to_u16_wrapping(&self) -> u16 {
1610        self.wrapping_cast()
1611    }
1612
1613    /// Converts to a [`u32`], wrapping if the value does not fit.
1614    ///
1615    /// This conversion can also be performed using
1616    ///   * <code>(\&integer).[wrapping\_as]::\<[u32]>()</code>
1617    ///   * <code>integer.[borrow]\().[wrapping\_as]::\<[u32]>()</code>
1618    ///   * <code>integer.[wrapping\_as]::\<[u32]>()</code>
1619    ///
1620    /// # Examples
1621    ///
1622    /// ```rust
1623    /// use rug::Integer;
1624    /// let neg = Integer::from(-1);
1625    /// assert_eq!(neg.to_u32_wrapping(), 0xffff_ffff);
1626    /// let large = Integer::from(0x1234_5678_9abc_def0_u64);
1627    /// assert_eq!(large.to_u32_wrapping(), 0x9abc_def0);
1628    /// ```
1629    ///
1630    /// [borrow]: core::borrow::Borrow::borrow
1631    /// [wrapping\_as]: az::WrappingAs::wrapping_as
1632    #[inline]
1633    pub fn to_u32_wrapping(&self) -> u32 {
1634        self.wrapping_cast()
1635    }
1636
1637    /// Converts to a [`u64`], wrapping if the value does not fit.
1638    ///
1639    /// This conversion can also be performed using
1640    ///   * <code>(\&integer).[wrapping\_as]::\<[u64]>()</code>
1641    ///   * <code>integer.[borrow]\().[wrapping\_as]::\<[u64]>()</code>
1642    ///   * <code>integer.[wrapping\_as]::\<[u64]>()</code>
1643    ///
1644    /// # Examples
1645    ///
1646    /// ```rust
1647    /// use rug::Integer;
1648    /// let neg = Integer::from(-1);
1649    /// assert_eq!(neg.to_u64_wrapping(), 0xffff_ffff_ffff_ffff);
1650    /// let large = Integer::from_str_radix("f123456789abcdef0", 16).unwrap();
1651    /// assert_eq!(large.to_u64_wrapping(), 0x1234_5678_9abc_def0);
1652    /// ```
1653    ///
1654    /// [borrow]: core::borrow::Borrow::borrow
1655    /// [wrapping\_as]: az::WrappingAs::wrapping_as
1656    #[inline]
1657    pub fn to_u64_wrapping(&self) -> u64 {
1658        self.wrapping_cast()
1659    }
1660
1661    /// Converts to a [`u128`], wrapping if the value does not fit.
1662    ///
1663    /// This conversion can also be performed using
1664    ///   * <code>(\&integer).[wrapping\_as]::\<[u128]>()</code>
1665    ///   * <code>integer.[borrow]\().[wrapping\_as]::\<[u128]>()</code>
1666    ///   * <code>integer.[wrapping\_as]::\<[u128]>()</code>
1667    ///
1668    /// # Examples
1669    ///
1670    /// ```rust
1671    /// use rug::Integer;
1672    /// let neg = Integer::from(-1);
1673    /// assert_eq!(
1674    ///     neg.to_u128_wrapping(),
1675    ///     0xffff_ffff_ffff_ffff_ffff_ffff_ffff_ffff
1676    /// );
1677    /// let s = "f123456789abcdef0123456789abcdef0";
1678    /// let large = Integer::from_str_radix(s, 16).unwrap();
1679    /// assert_eq!(
1680    ///     large.to_u128_wrapping(),
1681    ///     0x1234_5678_9abc_def0_1234_5678_9abc_def0
1682    /// );
1683    /// ```
1684    ///
1685    /// [borrow]: core::borrow::Borrow::borrow
1686    /// [wrapping\_as]: az::WrappingAs::wrapping_as
1687    #[inline]
1688    pub fn to_u128_wrapping(&self) -> u128 {
1689        self.wrapping_cast()
1690    }
1691
1692    /// Converts to a [`usize`], wrapping if the value does not fit.
1693    ///
1694    /// This conversion can also be performed using
1695    ///   * <code>(\&integer).[wrapping\_as]::\<[usize]>()</code>
1696    ///   * <code>integer.[borrow]\().[wrapping\_as]::\<[usize]>()</code>
1697    ///   * <code>integer.[wrapping\_as]::\<[usize]>()</code>
1698    ///
1699    /// # Examples
1700    ///
1701    /// ```rust
1702    /// use rug::Integer;
1703    /// let large: Integer = (Integer::from(0x1000) << 128) | 0x1234;
1704    /// assert_eq!(large.to_usize_wrapping(), 0x1234);
1705    /// ```
1706    ///
1707    /// [borrow]: core::borrow::Borrow::borrow
1708    /// [wrapping\_as]: az::WrappingAs::wrapping_as
1709    #[inline]
1710    pub fn to_usize_wrapping(&self) -> usize {
1711        self.wrapping_cast()
1712    }
1713
1714    /// Converts to an [`f32`], rounding towards zero.
1715    ///
1716    /// This conversion can also be performed using
1717    ///   * <code>(\&integer).[az]::\<[f32]>()</code>
1718    ///   * <code>integer.[borrow]\().[az]::\<[f32]>()</code>
1719    ///   * <code>integer.[az]::\<[f32]>()</code>
1720    ///
1721    /// # Examples
1722    ///
1723    /// ```rust
1724    /// use rug::Integer;
1725    /// let min = Integer::from_f32(f32::MIN).unwrap();
1726    /// let min_minus_one = min - 1u32;
1727    /// // min_minus_one is truncated to f32::MIN
1728    /// assert_eq!(min_minus_one.to_f32(), f32::MIN);
1729    /// let times_two = min_minus_one * 2u32;
1730    /// // times_two is too small
1731    /// assert_eq!(times_two.to_f32(), f32::NEG_INFINITY);
1732    /// ```
1733    ///
1734    /// [az]: az::Az::az
1735    /// [borrow]: core::borrow::Borrow::borrow
1736    #[inline]
1737    pub fn to_f32(&self) -> f32 {
1738        self.cast()
1739    }
1740
1741    /// Converts to an [`f64`], rounding towards zero.
1742    ///
1743    /// This conversion can also be performed using
1744    ///   * <code>(\&integer).[az]::\<[f64]>()</code>
1745    ///   * <code>integer.[borrow]\().[az]::\<[f64]>()</code>
1746    ///   * <code>integer.[az]::\<[f64]>()</code>
1747    ///
1748    /// # Examples
1749    ///
1750    /// ```rust
1751    /// use rug::Integer;
1752    ///
1753    /// // An `f64` has 53 bits of precision.
1754    /// let exact = 0x1f_ffff_ffff_ffff_u64;
1755    /// let i = Integer::from(exact);
1756    /// assert_eq!(i.to_f64(), exact as f64);
1757    ///
1758    /// // large has 56 ones
1759    /// let large = 0xff_ffff_ffff_ffff_u64;
1760    /// // trunc has 53 ones followed by 3 zeros
1761    /// let trunc = 0xff_ffff_ffff_fff8_u64;
1762    /// let j = Integer::from(large);
1763    /// assert_eq!(j.to_f64() as u64, trunc);
1764    ///
1765    /// let max = Integer::from_f64(f64::MAX).unwrap();
1766    /// let max_plus_one = max + 1u32;
1767    /// // max_plus_one is truncated to f64::MAX
1768    /// assert_eq!(max_plus_one.to_f64(), f64::MAX);
1769    /// let times_two = max_plus_one * 2u32;
1770    /// // times_two is too large
1771    /// assert_eq!(times_two.to_f64(), f64::INFINITY);
1772    /// ```
1773    ///
1774    /// [az]: az::Az::az
1775    /// [borrow]: core::borrow::Borrow::borrow
1776    #[inline]
1777    pub fn to_f64(&self) -> f64 {
1778        self.cast()
1779    }
1780
1781    /// Converts to an [`f32`] and an exponent, rounding towards zero.
1782    ///
1783    /// The returned [`f32`] is in the range
1784    /// 0.5&nbsp;≤&nbsp;<i>x</i>&nbsp;<&nbsp;1. If the value is zero, `(0.0, 0)`
1785    /// is returned.
1786    ///
1787    /// # Examples
1788    ///
1789    /// ```rust
1790    /// use rug::Integer;
1791    /// let zero = Integer::new();
1792    /// let (d0, exp0) = zero.to_f32_exp();
1793    /// assert_eq!((d0, exp0), (0.0, 0));
1794    /// let fifteen = Integer::from(15);
1795    /// let (d15, exp15) = fifteen.to_f32_exp();
1796    /// assert_eq!((d15, exp15), (15.0 / 16.0, 4));
1797    /// ```
1798    #[inline]
1799    pub fn to_f32_exp(&self) -> (f32, u32) {
1800        let (f, exp) = self.to_f64_exp();
1801        let trunc_f = misc::trunc_f64_to_f32(f);
1802        (trunc_f, exp)
1803    }
1804
1805    /// Converts to an [`f64`] and an exponent, rounding towards zero.
1806    ///
1807    /// The returned [`f64`] is in the range
1808    /// 0.5&nbsp;≤&nbsp;<i>x</i>&nbsp;<&nbsp;1. If the value is zero, `(0.0, 0)`
1809    /// is returned.
1810    ///
1811    /// # Examples
1812    ///
1813    /// ```rust
1814    /// use rug::Integer;
1815    /// let zero = Integer::new();
1816    /// let (d0, exp0) = zero.to_f64_exp();
1817    /// assert_eq!((d0, exp0), (0.0, 0));
1818    /// let fifteen = Integer::from(15);
1819    /// let (d15, exp15) = fifteen.to_f64_exp();
1820    /// assert_eq!((d15, exp15), (15.0 / 16.0, 4));
1821    /// ```
1822    #[inline]
1823    pub fn to_f64_exp(&self) -> (f64, u32) {
1824        let (f, exp) = xmpz::get_f64_2exp(self);
1825        (f, exp.strict_cast())
1826    }
1827
1828    /// Returns a string representation of the number for the specified `radix`.
1829    ///
1830    /// # Panics
1831    ///
1832    /// Panics if `radix` is less than 2 or greater than 36.
1833    ///
1834    /// # Examples
1835    ///
1836    /// ```rust
1837    /// use rug::{Assign, Integer};
1838    /// let mut i = Integer::new();
1839    /// assert_eq!(i.to_string_radix(10), "0");
1840    /// i.assign(-10);
1841    /// assert_eq!(i.to_string_radix(16), "-a");
1842    /// i.assign(0x1234cdef);
1843    /// assert_eq!(i.to_string_radix(4), "102031030313233");
1844    /// i.assign(Integer::parse_radix("123456789aAbBcCdDeEfF", 16).unwrap());
1845    /// assert_eq!(i.to_string_radix(16), "123456789aabbccddeeff");
1846    /// ```
1847    #[cfg(feature = "std")]
1848    #[inline]
1849    pub fn to_string_radix(&self, radix: i32) -> String {
1850        let mut s = StringLike::new_string();
1851        append_to_string(&mut s, self, radix, false);
1852        s.unwrap_string()
1853    }
1854
1855    /// Assigns from an [`f32`] if it is [finite][f32::is_finite], rounding
1856    /// towards zero.
1857    ///
1858    /// # Examples
1859    ///
1860    /// ```rust
1861    /// use rug::Integer;
1862    /// let mut i = Integer::new();
1863    /// let ret = i.assign_f64(-12.7);
1864    /// assert!(ret.is_ok());
1865    /// assert_eq!(i, -12);
1866    /// let ret = i.assign_f32(f32::NAN);
1867    /// assert!(ret.is_err());
1868    /// assert_eq!(i, -12);
1869    /// ```
1870    #[inline]
1871    #[allow(clippy::result_unit_err)]
1872    pub fn assign_f32(&mut self, val: f32) -> Result<(), ()> {
1873        self.assign_f64(val.into())
1874    }
1875
1876    /// Assigns from an [`f64`] if it is [finite][f64::is_finite],
1877    /// rounding towards zero.
1878    ///
1879    /// # Examples
1880    ///
1881    /// ```rust
1882    /// use rug::Integer;
1883    /// let mut i = Integer::new();
1884    /// let ret = i.assign_f64(12.7);
1885    /// assert!(ret.is_ok());
1886    /// assert_eq!(i, 12);
1887    /// let ret = i.assign_f64(1.0 / 0.0);
1888    /// assert!(ret.is_err());
1889    /// assert_eq!(i, 12);
1890    /// ```
1891    #[inline]
1892    #[allow(clippy::result_unit_err)]
1893    pub fn assign_f64(&mut self, val: f64) -> Result<(), ()> {
1894        xmpz::set_f64(self, val)
1895    }
1896
1897    /// Borrows a negated copy of the [`Integer`].
1898    ///
1899    /// The returned object implements <code>[Deref]\<[Target][Deref::Target] = [Integer]></code>.
1900    ///
1901    /// This method performs a shallow copy and negates it, and negation does
1902    /// not change the allocated data.
1903    ///
1904    /// # Examples
1905    ///
1906    /// ```rust
1907    /// use rug::Integer;
1908    /// let i = Integer::from(42);
1909    /// let neg_i = i.as_neg();
1910    /// assert_eq!(*neg_i, -42);
1911    /// // methods taking &self can be used on the returned object
1912    /// let reneg_i = neg_i.as_neg();
1913    /// assert_eq!(*reneg_i, 42);
1914    /// assert_eq!(*reneg_i, i);
1915    /// ```
1916    ///
1917    /// [Deref::Target]: core::ops::Deref::Target
1918    /// [Deref]: core::ops::Deref
1919    pub const fn as_neg(&self) -> BorrowInteger<'_> {
1920        let mut raw = self.inner;
1921        raw.size = match raw.size.checked_neg() {
1922            Some(s) => s,
1923            None => panic!("overflow"),
1924        };
1925        // Safety: the lifetime of the return type is equal to the lifetime of self.
1926        unsafe { BorrowInteger::from_raw(raw) }
1927    }
1928
1929    /// Borrows an absolute copy of the [`Integer`].
1930    ///
1931    /// The returned object implements <code>[Deref]\<[Target][Deref::Target] = [Integer]></code>.
1932    ///
1933    /// This method performs a shallow copy and possibly negates it, and
1934    /// negation does not change the allocated data.
1935    ///
1936    /// # Examples
1937    ///
1938    /// ```rust
1939    /// use rug::Integer;
1940    /// let i = Integer::from(-42);
1941    /// let abs_i = i.as_abs();
1942    /// assert_eq!(*abs_i, 42);
1943    /// // methods taking &self can be used on the returned object
1944    /// let reabs_i = abs_i.as_abs();
1945    /// assert_eq!(*reabs_i, 42);
1946    /// assert_eq!(*reabs_i, *abs_i);
1947    /// ```
1948    ///
1949    /// [Deref::Target]: core::ops::Deref::Target
1950    /// [Deref]: core::ops::Deref
1951    pub const fn as_abs(&self) -> BorrowInteger<'_> {
1952        let mut raw = self.inner;
1953        raw.size = match raw.size.checked_abs() {
1954            Some(s) => s,
1955            None => panic!("overflow"),
1956        };
1957        // Safety: the lifetime of the return type is equal to the lifetime of self.
1958        unsafe { BorrowInteger::from_raw(raw) }
1959    }
1960
1961    #[cfg(feature = "rational")]
1962    /// Borrows a copy of the [`Integer`] as a [`Rational`][Rational] number.
1963    ///
1964    /// The returned object implements
1965    /// <code>[Deref]\<[Target][Deref::Target] = [Rational]></code>.
1966    ///
1967    /// # Examples
1968    ///
1969    /// ```rust
1970    /// use rug::Integer;
1971    /// let i = Integer::from(4);
1972    /// let r = i.as_rational();
1973    /// assert_eq!(*r, 4);
1974    /// // methods taking &self can be used on the returned object
1975    /// let recip_r = r.as_recip();
1976    /// assert_eq!(*recip_r, 0.25);
1977    /// ```
1978    ///
1979    /// [Deref::Target]: core::ops::Deref::Target
1980    /// [Deref]: core::ops::Deref
1981    /// [Rational]: crate::Rational
1982    pub const fn as_rational(&self) -> BorrowRational<'_> {
1983        const ONE: limb_t = 1;
1984        // use NonNull::new_unchecked because NonNull::from is not usable in const
1985        let raw_rational = mpq_t {
1986            num: self.inner,
1987            den: mpz_t {
1988                alloc: 1,
1989                size: 1,
1990                d: unsafe { NonNull::new_unchecked((&ONE as *const limb_t).cast_mut()) },
1991            },
1992        };
1993        // Safety: the lifetime of the return type is equal to the lifetime of self.
1994        // Safety: the number is in canonical form as the denominator is 1.
1995        unsafe { BorrowRational::from_raw(raw_rational) }
1996    }
1997
1998    /// Returns [`true`] if the number is zero.
1999    ///
2000    /// # Examples
2001    ///
2002    /// ```rust
2003    /// use rug::Integer;
2004    /// assert!(Integer::from(0).is_zero());
2005    /// assert!(!(Integer::from(1).is_zero()));
2006    /// ```
2007    #[inline]
2008    pub const fn is_zero(&self) -> bool {
2009        matches!(self.cmp0(), Ordering::Equal)
2010    }
2011
2012    /// Returns [`true`] if the number is positive and [`false`] if the number
2013    /// is zero or negative.
2014    ///
2015    /// # Examples
2016    ///
2017    /// ```rust
2018    /// use rug::Integer;
2019    /// assert!(Integer::from(10).is_positive());
2020    /// assert!(!(Integer::from(-10).is_positive()));
2021    /// ```
2022    #[inline]
2023    pub const fn is_positive(&self) -> bool {
2024        matches!(self.cmp0(), Ordering::Greater)
2025    }
2026
2027    /// Returns [`true`] if the number is negative and [`false`] if the number
2028    /// is zero or positive.
2029    ///
2030    /// # Examples
2031    ///
2032    /// ```rust
2033    /// use rug::Integer;
2034    /// assert!(Integer::from(-10).is_negative());
2035    /// assert!(!(Integer::from(10).is_negative()));
2036    /// ```
2037    #[inline]
2038    pub const fn is_negative(&self) -> bool {
2039        matches!(self.cmp0(), Ordering::Less)
2040    }
2041
2042    /// Returns [`true`] if the number is even.
2043    ///
2044    /// # Examples
2045    ///
2046    /// ```rust
2047    /// use rug::Integer;
2048    /// assert!(!(Integer::from(13).is_even()));
2049    /// assert!(Integer::from(-14).is_even());
2050    /// ```
2051    #[inline]
2052    pub const fn is_even(&self) -> bool {
2053        xmpz::even_p(self)
2054    }
2055
2056    /// Returns [`true`] if the number is odd.
2057    ///
2058    /// # Examples
2059    ///
2060    /// ```rust
2061    /// use rug::Integer;
2062    /// assert!(Integer::from(13).is_odd());
2063    /// assert!(!Integer::from(-14).is_odd());
2064    /// ```
2065    #[inline]
2066    pub const fn is_odd(&self) -> bool {
2067        xmpz::odd_p(self)
2068    }
2069
2070    /// Returns [`true`] if the number is divisible by `divisor`. Unlike other
2071    /// division functions, `divisor` can be zero.
2072    ///
2073    /// # Examples
2074    ///
2075    /// ```rust
2076    /// use rug::Integer;
2077    /// let i = Integer::from(230);
2078    /// assert!(i.is_divisible(&Integer::from(10)));
2079    /// assert!(!i.is_divisible(&Integer::from(100)));
2080    /// assert!(!i.is_divisible(&Integer::new()));
2081    /// ```
2082    #[inline]
2083    pub fn is_divisible(&self, divisor: &Self) -> bool {
2084        xmpz::divisible_p(self, divisor)
2085    }
2086
2087    /// Returns [`true`] if the number is divisible by `divisor`. Unlike other
2088    /// division functions, `divisor` can be zero.
2089    ///
2090    /// # Examples
2091    ///
2092    /// ```rust
2093    /// use rug::Integer;
2094    /// let i = Integer::from(230);
2095    /// assert!(i.is_divisible_u(23));
2096    /// assert!(!i.is_divisible_u(100));
2097    /// assert!(!i.is_divisible_u(0));
2098    /// ```
2099    #[inline]
2100    pub fn is_divisible_u(&self, divisor: u32) -> bool {
2101        xmpz::divisible_ui_p(self, divisor.into())
2102    }
2103
2104    /// Returns [`true`] if the number is divisible by 2<sup><i>b</i></sup>.
2105    ///
2106    /// # Examples
2107    ///
2108    /// ```rust
2109    /// use rug::Integer;
2110    /// let i = Integer::from(15 << 17);
2111    /// assert!(i.is_divisible_2pow(16));
2112    /// assert!(i.is_divisible_2pow(17));
2113    /// assert!(!i.is_divisible_2pow(18));
2114    /// ```
2115    #[inline]
2116    pub fn is_divisible_2pow(&self, b: u32) -> bool {
2117        xmpz::divisible_2exp_p(self, b.into())
2118    }
2119
2120    /// Returns [`true`] if the number is congruent to <i>c</i> mod
2121    /// <i>divisor</i>, that is, if there exists a <i>q</i> such that `self` =
2122    /// <i>c</i> + <i>q</i> × <i>divisor</i>. Unlike other division functions,
2123    /// `divisor` can be zero.
2124    ///
2125    /// # Examples
2126    ///
2127    /// ```rust
2128    /// use rug::Integer;
2129    /// let n = Integer::from(105);
2130    /// let divisor = Integer::from(10);
2131    /// assert!(n.is_congruent(&Integer::from(5), &divisor));
2132    /// assert!(n.is_congruent(&Integer::from(25), &divisor));
2133    /// assert!(!n.is_congruent(&Integer::from(7), &divisor));
2134    /// // n is congruent to itself if divisor is 0
2135    /// assert!(n.is_congruent(&n, &Integer::from(0)));
2136    /// ```
2137    #[inline]
2138    pub fn is_congruent(&self, c: &Self, divisor: &Self) -> bool {
2139        xmpz::congruent_p(self, c, divisor)
2140    }
2141
2142    /// Returns [`true`] if the number is congruent to <i>c</i> mod
2143    /// <i>divisor</i>, that is, if there exists a <i>q</i> such that `self` =
2144    /// <i>c</i> + <i>q</i> × <i>divisor</i>. Unlike other division functions,
2145    /// `divisor` can be zero.
2146    ///
2147    /// # Examples
2148    ///
2149    /// ```rust
2150    /// use rug::Integer;
2151    /// let n = Integer::from(105);
2152    /// assert!(n.is_congruent_u(3335, 10));
2153    /// assert!(!n.is_congruent_u(107, 10));
2154    /// // n is congruent to itself if divisor is 0
2155    /// assert!(n.is_congruent_u(105, 0));
2156    /// ```
2157    #[inline]
2158    pub fn is_congruent_u(&self, c: u32, divisor: u32) -> bool {
2159        xmpz::congruent_ui_p(self, c.into(), divisor.into())
2160    }
2161
2162    /// Returns [`true`] if the number is congruent to <i>c</i> mod
2163    /// 2<sup><i>b</i></sup>, that is, if there exists a <i>q</i> such that
2164    /// `self` = <i>c</i> + <i>q</i> × 2<sup><i>b</i></sup>.
2165    ///
2166    /// # Examples
2167    ///
2168    /// ```rust
2169    /// use rug::Integer;
2170    /// let n = Integer::from(13 << 17 | 21);
2171    /// assert!(n.is_congruent_2pow(&Integer::from(7 << 17 | 21), 17));
2172    /// assert!(!n.is_congruent_2pow(&Integer::from(13 << 17 | 22), 17));
2173    /// ```
2174    #[inline]
2175    pub fn is_congruent_2pow(&self, c: &Self, b: u32) -> bool {
2176        xmpz::congruent_2exp_p(self, c, b.into())
2177    }
2178
2179    /// Returns [`true`] if the number is a perfect power.
2180    ///
2181    /// # Examples
2182    ///
2183    /// ```rust
2184    /// use rug::Integer;
2185    /// // 0 is 0 to the power of anything
2186    /// assert!(Integer::from(0).is_perfect_power());
2187    /// // 25 is 5 to the power of 2
2188    /// assert!(Integer::from(25).is_perfect_power());
2189    /// // -243 is -3 to the power of 5
2190    /// assert!(Integer::from(243).is_perfect_power());
2191    ///
2192    /// assert!(!Integer::from(24).is_perfect_power());
2193    /// assert!(!Integer::from(-100).is_perfect_power());
2194    /// ```
2195    #[inline]
2196    pub fn is_perfect_power(&self) -> bool {
2197        xmpz::perfect_power_p(self)
2198    }
2199
2200    /// Returns [`true`] if the number is a perfect square.
2201    ///
2202    /// # Examples
2203    ///
2204    /// ```rust
2205    /// use rug::Integer;
2206    /// assert!(Integer::from(0).is_perfect_square());
2207    /// assert!(Integer::from(1).is_perfect_square());
2208    /// assert!(Integer::from(4).is_perfect_square());
2209    /// assert!(Integer::from(9).is_perfect_square());
2210    ///
2211    /// assert!(!Integer::from(15).is_perfect_square());
2212    /// assert!(!Integer::from(-9).is_perfect_square());
2213    /// ```
2214    #[inline]
2215    pub fn is_perfect_square(&self) -> bool {
2216        xmpz::perfect_square_p(self)
2217    }
2218
2219    /// Returns [`true`] if the number is a power of two.
2220    ///
2221    /// # Examples
2222    ///
2223    /// ```rust
2224    /// use rug::Integer;
2225    /// assert!(Integer::from(1).is_power_of_two());
2226    /// assert!(Integer::from(4).is_power_of_two());
2227    /// assert!(Integer::from(1 << 30).is_power_of_two());
2228    ///
2229    /// assert!(!Integer::from(7).is_power_of_two());
2230    /// assert!(!Integer::from(0).is_power_of_two());
2231    /// assert!(!Integer::from(-1).is_power_of_two());
2232    /// ```
2233    #[inline]
2234    pub fn is_power_of_two(&self) -> bool {
2235        xmpz::power_of_two_p(self)
2236    }
2237
2238    /// Returns the same result as
2239    /// <code>self.[cmp][Ord::cmp]\(\&0.[into][Into::into]\())</code>, but is
2240    /// faster.
2241    ///
2242    /// # Examples
2243    ///
2244    /// ```rust
2245    /// use core::cmp::Ordering;
2246    /// use rug::Integer;
2247    /// assert_eq!(Integer::from(-5).cmp0(), Ordering::Less);
2248    /// assert_eq!(Integer::from(0).cmp0(), Ordering::Equal);
2249    /// assert_eq!(Integer::from(5).cmp0(), Ordering::Greater);
2250    /// ```
2251    #[inline]
2252    pub const fn cmp0(&self) -> Ordering {
2253        xmpz::sgn(self)
2254    }
2255
2256    /// Compares the absolute values.
2257    ///
2258    /// # Examples
2259    ///
2260    /// ```rust
2261    /// use core::cmp::Ordering;
2262    /// use rug::Integer;
2263    /// let a = Integer::from(-10);
2264    /// let b = Integer::from(4);
2265    /// assert_eq!(a.cmp(&b), Ordering::Less);
2266    /// assert_eq!(a.cmp_abs(&b), Ordering::Greater);
2267    /// ```
2268    #[inline]
2269    pub fn cmp_abs(&self, other: &Self) -> Ordering {
2270        xmpz::cmpabs(self, other)
2271    }
2272
2273    /// Returns the number of bits required to represent the absolute value.
2274    ///
2275    /// # Examples
2276    ///
2277    /// ```rust
2278    /// use rug::Integer;
2279    ///
2280    /// assert_eq!(Integer::from(0).significant_bits(), 0);  //    “”
2281    /// assert_eq!(Integer::from(1).significant_bits(), 1);  //   “1”
2282    /// assert_eq!(Integer::from(4).significant_bits(), 3);  // “100”
2283    /// assert_eq!(Integer::from(7).significant_bits(), 3);  // “111”
2284    /// assert_eq!(Integer::from(-1).significant_bits(), 1); //   “1”
2285    /// assert_eq!(Integer::from(-4).significant_bits(), 3); // “100”
2286    /// assert_eq!(Integer::from(-7).significant_bits(), 3); // “111”
2287    /// ```
2288    #[inline]
2289    pub fn significant_bits(&self) -> u32 {
2290        xmpz::significant_bits(self).strict_cast()
2291    }
2292
2293    /// Returns the number of bits required to represent the value using a
2294    /// two’s-complement representation.
2295    ///
2296    /// For non-negative numbers, this method returns one more than
2297    /// the [`significant_bits`] method, since an extra zero is needed
2298    /// before the most significant bit.
2299    ///
2300    /// # Examples
2301    ///
2302    /// ```rust
2303    /// use rug::Integer;
2304    ///
2305    /// assert_eq!(Integer::from(-5).signed_bits(), 4); // “1011”
2306    /// assert_eq!(Integer::from(-4).signed_bits(), 3); //  “100”
2307    /// assert_eq!(Integer::from(-3).signed_bits(), 3); //  “101”
2308    /// assert_eq!(Integer::from(-2).signed_bits(), 2); //   “10”
2309    /// assert_eq!(Integer::from(-1).signed_bits(), 1); //    “1”
2310    /// assert_eq!(Integer::from(0).signed_bits(), 1);  //    “0”
2311    /// assert_eq!(Integer::from(1).signed_bits(), 2);  //   “01”
2312    /// assert_eq!(Integer::from(2).signed_bits(), 3);  //  “010”
2313    /// assert_eq!(Integer::from(3).signed_bits(), 3);  //  “011”
2314    /// assert_eq!(Integer::from(4).signed_bits(), 4);  // “0100”
2315    /// ```
2316    ///
2317    /// [`significant_bits`]: Integer::significant_bits
2318    #[inline]
2319    pub fn signed_bits(&self) -> u32 {
2320        xmpz::signed_bits(self).strict_cast()
2321    }
2322
2323    /// Returns the number of one bits if the value ≥ 0.
2324    ///
2325    /// # Examples
2326    ///
2327    /// ```rust
2328    /// use rug::Integer;
2329    /// assert_eq!(Integer::from(0).count_ones(), Some(0));
2330    /// assert_eq!(Integer::from(15).count_ones(), Some(4));
2331    /// assert_eq!(Integer::from(-1).count_ones(), None);
2332    /// ```
2333    #[inline]
2334    pub fn count_ones(&self) -> Option<u32> {
2335        xmpz::popcount(self).map(StrictCast::strict_cast)
2336    }
2337
2338    /// Returns the number of zero bits if the value < 0.
2339    ///
2340    /// # Examples
2341    ///
2342    /// ```rust
2343    /// use rug::Integer;
2344    /// assert_eq!(Integer::from(0).count_zeros(), None);
2345    /// assert_eq!(Integer::from(1).count_zeros(), None);
2346    /// assert_eq!(Integer::from(-1).count_zeros(), Some(0));
2347    /// assert_eq!(Integer::from(-2).count_zeros(), Some(1));
2348    /// assert_eq!(Integer::from(-7).count_zeros(), Some(2));
2349    /// assert_eq!(Integer::from(-8).count_zeros(), Some(3));
2350    /// ```
2351    #[inline]
2352    pub fn count_zeros(&self) -> Option<u32> {
2353        xmpz::zerocount(self).map(StrictCast::strict_cast)
2354    }
2355
2356    /// Returns the location of the first zero, starting at `start`. If the bit
2357    /// at location `start` is zero, returns `start`.
2358    ///
2359    /// # Examples
2360    ///
2361    /// ```rust
2362    /// use rug::Integer;
2363    /// // -2 is ...11111110
2364    /// assert_eq!(Integer::from(-2).find_zero(0), Some(0));
2365    /// assert_eq!(Integer::from(-2).find_zero(1), None);
2366    /// // 15 is ...00001111
2367    /// assert_eq!(Integer::from(15).find_zero(0), Some(4));
2368    /// assert_eq!(Integer::from(15).find_zero(20), Some(20));
2369    /// ```
2370    #[inline]
2371    #[doc(alias = "trailing_ones")]
2372    pub fn find_zero(&self, start: u32) -> Option<u32> {
2373        xmpz::scan0(self, start.into()).map(StrictCast::strict_cast)
2374    }
2375
2376    /// Returns the location of the first one, starting at `start`. If the bit
2377    /// at location `start` is one, returns `start`.
2378    ///
2379    /// # Examples
2380    ///
2381    /// ```rust
2382    /// use rug::Integer;
2383    /// // 1 is ...00000001
2384    /// assert_eq!(Integer::from(1).find_one(0), Some(0));
2385    /// assert_eq!(Integer::from(1).find_one(1), None);
2386    /// // -16 is ...11110000
2387    /// assert_eq!(Integer::from(-16).find_one(0), Some(4));
2388    /// assert_eq!(Integer::from(-16).find_one(20), Some(20));
2389    /// ```
2390    #[inline]
2391    #[doc(alias = "trailing_zeros")]
2392    pub fn find_one(&self, start: u32) -> Option<u32> {
2393        xmpz::scan1(self, start.into()).map(StrictCast::strict_cast)
2394    }
2395
2396    /// Sets the bit at location `index` to 1 if `val` is [`true`] or 0 if `val`
2397    /// is [`false`].
2398    ///
2399    /// # Examples
2400    ///
2401    /// ```rust
2402    /// use rug::{Assign, Integer};
2403    /// let mut i = Integer::from(-1);
2404    /// assert_eq!(*i.set_bit(0, false), -2);
2405    /// i.assign(0xff);
2406    /// assert_eq!(*i.set_bit(11, true), 0x8ff);
2407    /// ```
2408    #[inline]
2409    pub fn set_bit(&mut self, index: u32, val: bool) -> &mut Self {
2410        if val {
2411            xmpz::setbit(self, index.into());
2412        } else {
2413            xmpz::clrbit(self, index.into());
2414        }
2415        self
2416    }
2417
2418    /// Returns [`true`] if the bit at location `index` is 1 or [`false`] if the
2419    /// bit is 0.
2420    ///
2421    /// # Examples
2422    ///
2423    /// ```rust
2424    /// use rug::Integer;
2425    /// let i = Integer::from(0b100101);
2426    /// assert!(i.get_bit(0));
2427    /// assert!(!i.get_bit(1));
2428    /// assert!(i.get_bit(5));
2429    /// let neg = Integer::from(-1);
2430    /// assert!(neg.get_bit(1000));
2431    /// ```
2432    #[inline]
2433    pub fn get_bit(&self, index: u32) -> bool {
2434        xmpz::tstbit(self, index.into())
2435    }
2436
2437    /// Toggles the bit at location `index`.
2438    ///
2439    /// # Examples
2440    ///
2441    /// ```rust
2442    /// use rug::Integer;
2443    /// let mut i = Integer::from(0b100101);
2444    /// i.toggle_bit(5);
2445    /// assert_eq!(i, 0b101);
2446    /// ```
2447    #[inline]
2448    pub fn toggle_bit(&mut self, index: u32) -> &mut Self {
2449        xmpz::combit(self, index.into());
2450        self
2451    }
2452
2453    /// Retuns the Hamming distance if the two numbers have the same sign.
2454    ///
2455    /// The Hamming distance is the number of different bits.
2456    ///
2457    /// # Examples
2458    ///
2459    /// ```rust
2460    /// use rug::Integer;
2461    /// let i = Integer::from(-1);
2462    /// assert_eq!(Integer::from(0).hamming_dist(&i), None);
2463    /// assert_eq!(Integer::from(-1).hamming_dist(&i), Some(0));
2464    /// // -1 is ...11111111 and -13 is ...11110011
2465    /// assert_eq!(Integer::from(-13).hamming_dist(&i), Some(2));
2466    /// ```
2467    #[inline]
2468    pub fn hamming_dist(&self, other: &Self) -> Option<u32> {
2469        xmpz::hamdist(self, other).map(StrictCast::strict_cast)
2470    }
2471
2472    /// Adds a list of [`Integer`] values.
2473    ///
2474    /// The following are implemented with the returned [incomplete-computation
2475    /// value][icv] as `Src`:
2476    ///   * <code>[Assign]\<Src> for [Integer]</code>
2477    ///   * <code>[From]\<Src> for [Integer]</code>
2478    ///   * <code>[Complete]\<[Completed][Complete::Completed] = [Integer]> for Src</code>
2479    ///   * <code>[AddAssign]\<Src> for [Integer]</code>
2480    ///   * <code>[Add]\<Src> for [Integer]</code>,
2481    ///     <code>[Add]\<[Integer]> for Src</code>
2482    ///   * <code>[SubAssign]\<Src> for [Integer]</code>,
2483    ///     <code>[SubFrom]\<Src> for [Integer]</code>
2484    ///   * <code>[Sub]\<Src> for [Integer]</code>,
2485    ///     <code>[Sub]\<[Integer]> for Src</code>
2486    ///
2487    /// # Examples
2488    ///
2489    /// ```rust
2490    /// use rug::{Complete, Integer};
2491    ///
2492    /// let values = [
2493    ///     Integer::from(5),
2494    ///     Integer::from(1024),
2495    ///     Integer::from(-100_000),
2496    ///     Integer::from(-4),
2497    /// ];
2498    ///
2499    /// let sum = Integer::sum(values.iter()).complete();
2500    /// let expected = 5 + 1024 - 100_000 - 4;
2501    /// assert_eq!(sum, expected);
2502    /// ```
2503    ///
2504    /// [icv]: crate#incomplete-computation-values
2505    #[inline]
2506    pub fn sum<'a, I>(values: I) -> SumIncomplete<'a, I>
2507    where
2508        I: Iterator<Item = &'a Self>,
2509    {
2510        SumIncomplete { values }
2511    }
2512
2513    /// Finds the dot product of a list of [`Integer`] value pairs.
2514    ///
2515    /// The following are implemented with the returned [incomplete-computation
2516    /// value][icv] as `Src`:
2517    ///   * <code>[Assign]\<Src> for [Integer]</code>
2518    ///   * <code>[From]\<Src> for [Integer]</code>
2519    ///   * <code>[Complete]\<[Completed][Complete::Completed] = [Integer]> for Src</code>
2520    ///   * <code>[AddAssign]\<Src> for [Integer]</code>
2521    ///   * <code>[Add]\<Src> for [Integer]</code>,
2522    ///     <code>[Add]\<[Integer]> for Src</code>
2523    ///   * <code>[SubAssign]\<Src> for [Integer]</code>,
2524    ///     <code>[SubFrom]\<Src> for [Integer]</code>
2525    ///   * <code>[Sub]\<Src> for [Integer]</code>,
2526    ///     <code>[Sub]\<[Integer]> for Src</code>
2527    ///
2528    /// # Examples
2529    ///
2530    /// ```rust
2531    /// use rug::{Complete, Integer};
2532    ///
2533    /// let a = [Integer::from(270), Integer::from(-11)];
2534    /// let b = [Integer::from(100), Integer::from(5)];
2535    ///
2536    /// let dot = Integer::dot(a.iter().zip(b.iter())).complete();
2537    /// let expected = 270 * 100 - 11 * 5;
2538    /// assert_eq!(dot, expected);
2539    /// ```
2540    ///
2541    /// [icv]: crate#incomplete-computation-values
2542    #[inline]
2543    pub fn dot<'a, I>(values: I) -> DotIncomplete<'a, I>
2544    where
2545        I: Iterator<Item = (&'a Self, &'a Self)>,
2546    {
2547        DotIncomplete { values }
2548    }
2549
2550    /// Multiplies a list of [`Integer`] values.
2551    ///
2552    /// The following are implemented with the returned [incomplete-computation
2553    /// value][icv] as `Src`:
2554    ///   * <code>[Assign]\<Src> for [Integer]</code>
2555    ///   * <code>[From]\<Src> for [Integer]</code>
2556    ///   * <code>[Complete]\<[Completed][Complete::Completed] = [Integer]> for Src</code>
2557    ///   * <code>[MulAssign]\<Src> for [Integer]</code>
2558    ///   * <code>[Mul]\<Src> for [Integer]</code>,
2559    ///     <code>[Mul]\<[Integer]> for Src</code>
2560    ///
2561    /// # Examples
2562    ///
2563    /// ```rust
2564    /// use rug::{Complete, Integer};
2565    ///
2566    /// let values = [
2567    ///     Integer::from(5),
2568    ///     Integer::from(1024),
2569    ///     Integer::from(-100_000),
2570    ///     Integer::from(-4),
2571    /// ];
2572    ///
2573    /// let product = Integer::product(values.iter()).complete();
2574    /// let expected = 5 * 1024 * -100_000 * -4;
2575    /// assert_eq!(product, expected);
2576    /// ```
2577    ///
2578    /// [icv]: crate#incomplete-computation-values
2579    #[inline]
2580    pub fn product<'a, I>(values: I) -> ProductIncomplete<'a, I>
2581    where
2582        I: Iterator<Item = &'a Self>,
2583    {
2584        ProductIncomplete { values }
2585    }
2586
2587    /// Computes the absolute value.
2588    ///
2589    /// # Examples
2590    ///
2591    /// ```rust
2592    /// use rug::Integer;
2593    /// let i = Integer::from(-100);
2594    /// let abs = i.abs();
2595    /// assert_eq!(abs, 100);
2596    /// ```
2597    #[inline]
2598    #[must_use]
2599    pub fn abs(mut self) -> Self {
2600        self.abs_mut();
2601        self
2602    }
2603
2604    /// Computes the absolute value.
2605    ///
2606    /// # Examples
2607    ///
2608    /// ```rust
2609    /// use rug::Integer;
2610    /// let mut i = Integer::from(-100);
2611    /// i.abs_mut();
2612    /// assert_eq!(i, 100);
2613    /// ```
2614    #[inline]
2615    pub fn abs_mut(&mut self) {
2616        xmpz::abs(self, ());
2617    }
2618
2619    /// Computes the absolute value.
2620    ///
2621    /// The following are implemented with the returned [incomplete-computation
2622    /// value][icv] as `Src`:
2623    ///   * <code>[Assign]\<Src> for [Integer]</code>
2624    ///   * <code>[From]\<Src> for [Integer]</code>
2625    ///   * <code>[Complete]\<[Completed][Complete::Completed] = [Integer]> for Src</code>
2626    ///
2627    /// # Examples
2628    ///
2629    /// ```rust
2630    /// use rug::Integer;
2631    /// let i = Integer::from(-100);
2632    /// let r = i.abs_ref();
2633    /// let abs = Integer::from(r);
2634    /// assert_eq!(abs, 100);
2635    /// assert_eq!(i, -100);
2636    /// ```
2637    ///
2638    /// [icv]: crate#incomplete-computation-values
2639    #[inline]
2640    pub fn abs_ref(&self) -> AbsIncomplete<'_> {
2641        AbsIncomplete { ref_self: self }
2642    }
2643
2644    /// Computes the signum.
2645    ///
2646    ///   * 0 if the value is zero
2647    ///   * 1 if the value is positive
2648    ///   * &minus;1 if the value is negative
2649    ///
2650    /// # Examples
2651    ///
2652    /// ```rust
2653    /// use rug::Integer;
2654    /// assert_eq!(Integer::from(-100).signum(), -1);
2655    /// assert_eq!(Integer::from(0).signum(), 0);
2656    /// assert_eq!(Integer::from(100).signum(), 1);
2657    /// ```
2658    #[inline]
2659    #[must_use]
2660    pub fn signum(mut self) -> Self {
2661        self.signum_mut();
2662        self
2663    }
2664
2665    /// Computes the signum.
2666    ///
2667    ///   * 0 if the value is zero
2668    ///   * 1 if the value is positive
2669    ///   * &minus;1 if the value is negative
2670    ///
2671    /// # Examples
2672    ///
2673    /// ```rust
2674    /// use rug::Integer;
2675    /// let mut i = Integer::from(-100);
2676    /// i.signum_mut();
2677    /// assert_eq!(i, -1);
2678    /// ```
2679    #[inline]
2680    pub fn signum_mut(&mut self) {
2681        xmpz::signum(self, ());
2682    }
2683
2684    /// Computes the signum.
2685    ///
2686    ///   * 0 if the value is zero
2687    ///   * 1 if the value is positive
2688    ///   * &minus;1 if the value is negative
2689    ///
2690    /// The following are implemented with the returned [incomplete-computation
2691    /// value][icv] as `Src`:
2692    ///   * <code>[Assign]\<Src> for [Integer]</code>
2693    ///   * <code>[From]\<Src> for [Integer]</code>
2694    ///   * <code>[Complete]\<[Completed][Complete::Completed] = [Integer]> for Src</code>
2695    ///
2696    /// # Examples
2697    ///
2698    /// ```rust
2699    /// use rug::Integer;
2700    /// let i = Integer::from(-100);
2701    /// let r = i.signum_ref();
2702    /// let signum = Integer::from(r);
2703    /// assert_eq!(signum, -1);
2704    /// assert_eq!(i, -100);
2705    /// ```
2706    ///
2707    /// [icv]: crate#incomplete-computation-values
2708    #[inline]
2709    pub fn signum_ref(&self) -> SignumIncomplete<'_> {
2710        SignumIncomplete { ref_self: self }
2711    }
2712
2713    /// Clamps the value within the specified bounds.
2714    ///
2715    /// # Panics
2716    ///
2717    /// Panics if the maximum value is less than the minimum value.
2718    ///
2719    /// # Examples
2720    ///
2721    /// ```rust
2722    /// use rug::Integer;
2723    /// let min = -10;
2724    /// let max = 10;
2725    /// let too_small = Integer::from(-100);
2726    /// let clamped1 = too_small.clamp(&min, &max);
2727    /// assert_eq!(clamped1, -10);
2728    /// let in_range = Integer::from(3);
2729    /// let clamped2 = in_range.clamp(&min, &max);
2730    /// assert_eq!(clamped2, 3);
2731    /// ```
2732    #[inline]
2733    #[must_use]
2734    pub fn clamp<Min, Max>(mut self, min: &Min, max: &Max) -> Self
2735    where
2736        Self: PartialOrd<Min> + PartialOrd<Max> + for<'a> Assign<&'a Min> + for<'a> Assign<&'a Max>,
2737    {
2738        self.clamp_mut(min, max);
2739        self
2740    }
2741
2742    /// Clamps the value within the specified bounds.
2743    ///
2744    /// # Panics
2745    ///
2746    /// Panics if the maximum value is less than the minimum value.
2747    ///
2748    /// # Examples
2749    ///
2750    /// ```rust
2751    /// use rug::Integer;
2752    /// let min = -10;
2753    /// let max = 10;
2754    /// let mut too_small = Integer::from(-100);
2755    /// too_small.clamp_mut(&min, &max);
2756    /// assert_eq!(too_small, -10);
2757    /// let mut in_range = Integer::from(3);
2758    /// in_range.clamp_mut(&min, &max);
2759    /// assert_eq!(in_range, 3);
2760    /// ```
2761    pub fn clamp_mut<Min, Max>(&mut self, min: &Min, max: &Max)
2762    where
2763        Self: PartialOrd<Min> + PartialOrd<Max> + for<'a> Assign<&'a Min> + for<'a> Assign<&'a Max>,
2764    {
2765        if (*self).lt(min) {
2766            self.assign(min);
2767            assert!(!(*self).gt(max), "minimum larger than maximum");
2768        } else if (*self).gt(max) {
2769            self.assign(max);
2770            assert!(!(*self).lt(min), "minimum larger than maximum");
2771        }
2772    }
2773
2774    /// Clamps the value within the specified bounds.
2775    ///
2776    /// The following are implemented with the returned [incomplete-computation
2777    /// value][icv] as `Src`:
2778    ///   * <code>[Assign]\<Src> for [Integer]</code>
2779    ///   * <code>[From]\<Src> for [Integer]</code>
2780    ///   * <code>[Complete]\<[Completed][Complete::Completed] = [Integer]> for Src</code>
2781    ///
2782    /// # Panics
2783    ///
2784    /// Panics if the maximum value is less than the minimum value.
2785    ///
2786    /// # Examples
2787    ///
2788    /// ```rust
2789    /// use rug::Integer;
2790    /// let min = -10;
2791    /// let max = 10;
2792    /// let too_small = Integer::from(-100);
2793    /// let r1 = too_small.clamp_ref(&min, &max);
2794    /// let clamped1 = Integer::from(r1);
2795    /// assert_eq!(clamped1, -10);
2796    /// let in_range = Integer::from(3);
2797    /// let r2 = in_range.clamp_ref(&min, &max);
2798    /// let clamped2 = Integer::from(r2);
2799    /// assert_eq!(clamped2, 3);
2800    /// ```
2801    ///
2802    /// [icv]: crate#incomplete-computation-values
2803    #[inline]
2804    pub fn clamp_ref<'min, 'max, Min, Max>(
2805        &self,
2806        min: &'min Min,
2807        max: &'max Max,
2808    ) -> ClampIncomplete<'_, 'min, 'max, Min, Max>
2809    where
2810        Self: PartialOrd<Min> + PartialOrd<Max> + for<'a> Assign<&'a Min> + for<'a> Assign<&'a Max>,
2811    {
2812        ClampIncomplete {
2813            ref_self: self,
2814            min,
2815            max,
2816        }
2817    }
2818
2819    /// Keeps the <i>n</i> least significant bits only, producing a result that
2820    /// is greater or equal to 0.
2821    ///
2822    /// # Examples
2823    ///
2824    /// ```rust
2825    /// use rug::Integer;
2826    /// let i = Integer::from(-1);
2827    /// let keep_8 = i.keep_bits(8);
2828    /// assert_eq!(keep_8, 0xff);
2829    /// ```
2830    #[inline]
2831    #[must_use]
2832    pub fn keep_bits(mut self, n: u32) -> Self {
2833        self.keep_bits_mut(n);
2834        self
2835    }
2836
2837    /// Keeps the <i>n</i> least significant bits only, producing a result that
2838    /// is greater or equal to 0.
2839    ///
2840    /// # Examples
2841    ///
2842    /// ```rust
2843    /// use rug::Integer;
2844    /// let mut i = Integer::from(-1);
2845    /// i.keep_bits_mut(8);
2846    /// assert_eq!(i, 0xff);
2847    /// ```
2848    #[inline]
2849    pub fn keep_bits_mut(&mut self, n: u32) {
2850        xmpz::fdiv_r_2exp(self, (), n.into());
2851    }
2852
2853    /// Keeps the <i>n</i> least significant bits only, producing a result that
2854    /// is greater or equal to 0.
2855    ///
2856    /// The following are implemented with the returned [incomplete-computation
2857    /// value][icv] as `Src`:
2858    ///   * <code>[Assign]\<Src> for [Integer]</code>
2859    ///   * <code>[From]\<Src> for [Integer]</code>
2860    ///   * <code>[Complete]\<[Completed][Complete::Completed] = [Integer]> for Src</code>
2861    ///
2862    /// # Examples
2863    ///
2864    /// ```rust
2865    /// use rug::Integer;
2866    /// let i = Integer::from(-1);
2867    /// let r = i.keep_bits_ref(8);
2868    /// let eight_bits = Integer::from(r);
2869    /// assert_eq!(eight_bits, 0xff);
2870    /// ```
2871    ///
2872    /// [icv]: crate#incomplete-computation-values
2873    #[inline]
2874    pub fn keep_bits_ref(&self, n: u32) -> KeepBitsIncomplete<'_> {
2875        let n = n.into();
2876        KeepBitsIncomplete { ref_self: self, n }
2877    }
2878
2879    /// Keeps the <i>n</i> least significant bits only, producing a negative
2880    /// result if the <i>n</i>th least significant bit is one.
2881    ///
2882    /// # Examples
2883    ///
2884    /// ```rust
2885    /// use rug::Integer;
2886    /// let i = Integer::from(-1);
2887    /// let i_keep_8 = i.keep_signed_bits(8);
2888    /// assert_eq!(i_keep_8, -1);
2889    /// let j = Integer::from(15 << 8 | 15);
2890    /// let j_keep_8 = j.keep_signed_bits(8);
2891    /// assert_eq!(j_keep_8, 15);
2892    /// ```
2893    #[inline]
2894    #[must_use]
2895    pub fn keep_signed_bits(mut self, n: u32) -> Self {
2896        self.keep_signed_bits_mut(n);
2897        self
2898    }
2899
2900    /// Keeps the <i>n</i> least significant bits only, producing a negative
2901    /// result if the <i>n</i>th least significant bit is one.
2902    ///
2903    /// # Examples
2904    ///
2905    /// ```rust
2906    /// use rug::Integer;
2907    /// let mut i = Integer::from(-1);
2908    /// i.keep_signed_bits_mut(8);
2909    /// assert_eq!(i, -1);
2910    /// let mut j = Integer::from(15 << 8 | 15);
2911    /// j.keep_signed_bits_mut(8);
2912    /// assert_eq!(j, 15);
2913    /// ```
2914    #[inline]
2915    pub fn keep_signed_bits_mut(&mut self, n: u32) {
2916        xmpz::keep_signed_bits(self, (), n.into());
2917    }
2918
2919    /// Keeps the <i>n</i> least significant bits only, producing a negative
2920    /// result if the <i>n</i>th least significant bit is one.
2921    ///
2922    /// The following are implemented with the returned
2923    /// [incomplete-computation value][icv] as `Src`:
2924    ///   * <code>[Assign]\<Src> for [Integer]</code>
2925    ///   * <code>[From]\<Src> for [Integer]</code>
2926    ///   * <code>[Complete]\<[Completed][Complete::Completed] = [Integer]> for Src</code>
2927    ///
2928    /// # Examples
2929    ///
2930    /// ```rust
2931    /// use rug::Integer;
2932    /// let i = Integer::from(-1);
2933    /// let r = i.keep_signed_bits_ref(8);
2934    /// let eight_bits = Integer::from(r);
2935    /// assert_eq!(eight_bits, -1);
2936    /// ```
2937    ///
2938    /// [icv]: crate#incomplete-computation-values
2939    #[inline]
2940    pub fn keep_signed_bits_ref(&self, n: u32) -> KeepSignedBitsIncomplete<'_> {
2941        let n = n.into();
2942        KeepSignedBitsIncomplete { ref_self: self, n }
2943    }
2944
2945    /// Finds the next power of two, or 1 if the number ≤ 0.
2946    ///
2947    /// # Examples
2948    ///
2949    /// ```rust
2950    /// use rug::Integer;
2951    /// let i = Integer::from(-3).next_power_of_two();
2952    /// assert_eq!(i, 1);
2953    /// let i = Integer::from(4).next_power_of_two();
2954    /// assert_eq!(i, 4);
2955    /// let i = Integer::from(7).next_power_of_two();
2956    /// assert_eq!(i, 8);
2957    /// ```
2958    #[inline]
2959    #[must_use]
2960    pub fn next_power_of_two(mut self) -> Self {
2961        self.next_power_of_two_mut();
2962        self
2963    }
2964
2965    /// Finds the next power of two, or 1 if the number ≤ 0.
2966    ///
2967    /// # Examples
2968    ///
2969    /// ```rust
2970    /// use rug::Integer;
2971    /// let mut i = Integer::from(53);
2972    /// i.next_power_of_two_mut();
2973    /// assert_eq!(i, 64);
2974    /// ```
2975    #[inline]
2976    pub fn next_power_of_two_mut(&mut self) {
2977        xmpz::next_pow_of_two(self, ());
2978    }
2979
2980    /// Finds the next power of two, or 1 if the number ≤ 0.
2981    ///
2982    /// The following are implemented with the returned [incomplete-computation
2983    /// value][icv] as `Src`:
2984    ///   * <code>[Assign]\<Src> for [Integer]</code>
2985    ///   * <code>[From]\<Src> for [Integer]</code>
2986    ///   * <code>[Complete]\<[Completed][Complete::Completed] = [Integer]> for Src</code>
2987    ///
2988    /// # Examples
2989    ///
2990    /// ```rust
2991    /// use rug::Integer;
2992    /// let i = Integer::from(53);
2993    /// let r = i.next_power_of_two_ref();
2994    /// let next = Integer::from(r);
2995    /// assert_eq!(next, 64);
2996    /// ```
2997    ///
2998    /// [icv]: crate#incomplete-computation-values
2999    #[inline]
3000    pub fn next_power_of_two_ref(&self) -> NextPowerOfTwoIncomplete<'_> {
3001        NextPowerOfTwoIncomplete { ref_self: self }
3002    }
3003
3004    /// Finds the modulus, or the remainder of Euclidean division.
3005    ///
3006    /// The result is always zero or positive.
3007    ///
3008    /// # Panics
3009    ///
3010    /// Panics if `divisor` is zero.
3011    ///
3012    /// # Examples
3013    ///
3014    /// ```rust
3015    /// use rug::Integer;
3016    /// let dividend = Integer::from(-1003);
3017    /// let divisor = Integer::from(-10);
3018    /// let modulus = dividend.modulo(&divisor);
3019    /// assert_eq!(modulus, 7);
3020    /// ```
3021    #[inline]
3022    #[must_use]
3023    #[doc(alias = "rem_euclid")]
3024    pub fn modulo(mut self, divisor: &Self) -> Self {
3025        self.modulo_mut(divisor);
3026        self
3027    }
3028
3029    /// Finds the modulus, or the remainder of Euclidean division.
3030    ///
3031    /// The result is always zero or positive.
3032    ///
3033    /// # Panics
3034    ///
3035    /// Panics if `divisor` is zero.
3036    ///
3037    /// # Examples
3038    ///
3039    /// ```rust
3040    /// use rug::Integer;
3041    /// let mut m = Integer::from(-1003);
3042    /// let divisor = Integer::from(-10);
3043    /// m.modulo_mut(&divisor);
3044    /// assert_eq!(m, 7);
3045    /// ```
3046    #[inline]
3047    pub fn modulo_mut(&mut self, divisor: &Self) {
3048        xmpz::modulo(self, (), divisor);
3049    }
3050
3051    /// Finds the modulus, or the remainder of Euclidean division `dividend` /
3052    /// `self`.
3053    ///
3054    /// The result is always zero or positive.
3055    ///
3056    /// # Panics
3057    ///
3058    /// Panics if `self` is zero.
3059    ///
3060    /// # Examples
3061    ///
3062    /// ```rust
3063    /// use rug::Integer;
3064    /// let dividend = Integer::from(-1003);
3065    /// let mut m = Integer::from(-10);
3066    /// m.modulo_from(&dividend);
3067    /// assert_eq!(m, 7);
3068    /// ```
3069    #[inline]
3070    pub fn modulo_from(&mut self, dividend: &Self) {
3071        xmpz::modulo(self, dividend, ());
3072    }
3073
3074    /// Finds the modulus, or the remainder of Euclidean division.
3075    ///
3076    /// The result is always zero or positive.
3077    ///
3078    /// The following are implemented with the returned [incomplete-computation
3079    /// value][icv] as `Src`:
3080    ///   * <code>[Assign]\<Src> for [Integer]</code>
3081    ///   * <code>[From]\<Src> for [Integer]</code>
3082    ///   * <code>[Complete]\<[Completed][Complete::Completed] = [Integer]> for Src</code>
3083    ///
3084    /// # Examples
3085    ///
3086    /// ```rust
3087    /// use rug::Integer;
3088    /// let dividend = Integer::from(-1003);
3089    /// let divisor = Integer::from(-10);
3090    /// let r = dividend.modulo_ref(&divisor);
3091    /// let modulus = Integer::from(r);
3092    /// assert_eq!(modulus, 7);
3093    /// ```
3094    ///
3095    /// [icv]: crate#incomplete-computation-values
3096    pub fn modulo_ref<'a>(&'a self, divisor: &'a Self) -> ModuloIncomplete<'a> {
3097        ModuloIncomplete {
3098            ref_self: self,
3099            divisor,
3100        }
3101    }
3102
3103    /// Performs a division producing both the quotient and remainder.
3104    ///
3105    /// The remainder has the same sign as the dividend.
3106    ///
3107    /// # Panics
3108    ///
3109    /// Panics if `divisor` is zero.
3110    ///
3111    /// # Examples
3112    ///
3113    /// ```rust
3114    /// use rug::Integer;
3115    /// let dividend = Integer::from(23);
3116    /// let divisor = Integer::from(-10);
3117    /// let (quotient, rem) = dividend.div_rem(divisor);
3118    /// assert_eq!(quotient, -2);
3119    /// assert_eq!(rem, 3);
3120    /// ```
3121    #[inline]
3122    pub fn div_rem(mut self, mut divisor: Self) -> (Self, Self) {
3123        self.div_rem_mut(&mut divisor);
3124        (self, divisor)
3125    }
3126
3127    /// Performs a division producing both the quotient and remainder.
3128    ///
3129    /// The remainder has the same sign as the dividend.
3130    ///
3131    /// The quotient is stored in `self` and the remainder is stored in
3132    /// `divisor`.
3133    ///
3134    /// # Panics
3135    ///
3136    /// Panics if `divisor` is zero.
3137    ///
3138    /// # Examples
3139    ///
3140    /// ```rust
3141    /// use rug::Integer;
3142    /// let mut dividend_quotient = Integer::from(-23);
3143    /// let mut divisor_rem = Integer::from(10);
3144    /// dividend_quotient.div_rem_mut(&mut divisor_rem);
3145    /// assert_eq!(dividend_quotient, -2);
3146    /// assert_eq!(divisor_rem, -3);
3147    /// ```
3148    #[inline]
3149    pub fn div_rem_mut(&mut self, divisor: &mut Self) {
3150        xmpz::tdiv_qr(self, divisor, (), ());
3151    }
3152
3153    /// Performs a division producing both the quotient and remainder.
3154    ///
3155    /// The following are implemented with the returned [incomplete-computation
3156    /// value][icv] as `Src`:
3157    ///   * <code>[Assign]\<Src> for [(][tuple][Integer][], [Integer][][)][tuple]</code>
3158    ///   * <code>[Assign]\<Src> for [(][tuple]\&mut [Integer], \&mut [Integer][][)][tuple]</code>
3159    ///   * <code>[From]\<Src> for [(][tuple][Integer][], [Integer][][)][tuple]</code>
3160    ///   * <code>[Complete]\<[Completed][Complete::Completed] = [(][tuple][Integer][], [Integer][][)][tuple]> for Src</code>
3161    ///
3162    /// The remainder has the same sign as the dividend.
3163    ///
3164    /// # Examples
3165    ///
3166    /// ```rust
3167    /// use rug::{Complete, Integer};
3168    /// let dividend = Integer::from(-23);
3169    /// let divisor = Integer::from(-10);
3170    /// let (quotient, rem) = dividend.div_rem_ref(&divisor).complete();
3171    /// assert_eq!(quotient, 2);
3172    /// assert_eq!(rem, -3);
3173    /// ```
3174    ///
3175    /// [icv]: crate#incomplete-computation-values
3176    #[inline]
3177    pub fn div_rem_ref<'a>(&'a self, divisor: &'a Self) -> DivRemIncomplete<'a> {
3178        DivRemIncomplete {
3179            ref_self: self,
3180            divisor,
3181        }
3182    }
3183
3184    /// Performs a division producing both the quotient and remainder, with the
3185    /// quotient rounded up.
3186    ///
3187    /// The sign of the remainder is the opposite of the divisor’s sign.
3188    ///
3189    /// # Panics
3190    ///
3191    /// Panics if `divisor` is zero.
3192    ///
3193    /// # Examples
3194    ///
3195    /// ```rust
3196    /// use rug::Integer;
3197    /// let dividend = Integer::from(23);
3198    /// let divisor = Integer::from(-10);
3199    /// let (quotient, rem) = dividend.div_rem_ceil(divisor);
3200    /// assert_eq!(quotient, -2);
3201    /// assert_eq!(rem, 3);
3202    /// ```
3203    #[inline]
3204    pub fn div_rem_ceil(mut self, mut divisor: Self) -> (Self, Self) {
3205        self.div_rem_ceil_mut(&mut divisor);
3206        (self, divisor)
3207    }
3208
3209    /// Performs a division producing both the quotient and remainder, with the
3210    /// quotient rounded up.
3211    ///
3212    /// The sign of the remainder is the opposite of the divisor’s sign.
3213    ///
3214    /// The quotient is stored in `self` and the remainder is stored in
3215    /// `divisor`.
3216    ///
3217    /// # Panics
3218    ///
3219    /// Panics if `divisor` is zero.
3220    ///
3221    /// # Examples
3222    ///
3223    /// ```rust
3224    /// use rug::Integer;
3225    /// let mut dividend_quotient = Integer::from(-23);
3226    /// let mut divisor_rem = Integer::from(10);
3227    /// dividend_quotient.div_rem_ceil_mut(&mut divisor_rem);
3228    /// assert_eq!(dividend_quotient, -2);
3229    /// assert_eq!(divisor_rem, -3);
3230    /// ```
3231    #[inline]
3232    pub fn div_rem_ceil_mut(&mut self, divisor: &mut Self) {
3233        xmpz::cdiv_qr(self, divisor, (), ());
3234    }
3235
3236    /// Performs a division producing both the quotient and remainder, with the
3237    /// quotient rounded up.
3238    ///
3239    /// The sign of the remainder is the opposite of the divisor’s sign.
3240    ///
3241    /// The following are implemented with the returned [incomplete-computation
3242    /// value][icv] as `Src`:
3243    ///   * <code>[Assign]\<Src> for [(][tuple][Integer][], [Integer][][)][tuple]</code>
3244    ///   * <code>[Assign]\<Src> for [(][tuple]\&mut [Integer], \&mut [Integer][][)][tuple]</code>
3245    ///   * <code>[From]\<Src> for [(][tuple][Integer][], [Integer][][)][tuple]</code>
3246    ///   * <code>[Complete]\<[Completed][Complete::Completed] = [(][tuple][Integer][], [Integer][][)][tuple]> for Src</code>
3247    ///
3248    /// # Examples
3249    ///
3250    /// ```rust
3251    /// use rug::{Complete, Integer};
3252    /// let dividend = Integer::from(-23);
3253    /// let divisor = Integer::from(-10);
3254    /// let (quotient, rem) = dividend.div_rem_ceil_ref(&divisor).complete();
3255    /// assert_eq!(quotient, 3);
3256    /// assert_eq!(rem, 7);
3257    /// ```
3258    ///
3259    /// [icv]: crate#incomplete-computation-values
3260    #[inline]
3261    pub fn div_rem_ceil_ref<'a>(&'a self, divisor: &'a Self) -> DivRemCeilIncomplete<'a> {
3262        DivRemCeilIncomplete {
3263            ref_self: self,
3264            divisor,
3265        }
3266    }
3267
3268    /// Performs a division producing both the quotient and remainder, with the
3269    /// quotient rounded down.
3270    ///
3271    /// The remainder has the same sign as the divisor.
3272    ///
3273    /// # Panics
3274    ///
3275    /// Panics if `divisor` is zero.
3276    ///
3277    /// # Examples
3278    ///
3279    /// ```rust
3280    /// use rug::Integer;
3281    /// let dividend = Integer::from(23);
3282    /// let divisor = Integer::from(-10);
3283    /// let (quotient, rem) = dividend.div_rem_floor(divisor);
3284    /// assert_eq!(quotient, -3);
3285    /// assert_eq!(rem, -7);
3286    /// ```
3287    #[inline]
3288    pub fn div_rem_floor(mut self, mut divisor: Self) -> (Self, Self) {
3289        self.div_rem_floor_mut(&mut divisor);
3290        (self, divisor)
3291    }
3292
3293    /// Performs a division producing both the quotient and remainder, with the
3294    /// quotient rounded down.
3295    ///
3296    /// The remainder has the same sign as the divisor.
3297    ///
3298    /// The quotient is stored in `self` and the remainder is stored in
3299    /// `divisor`.
3300    ///
3301    /// # Panics
3302    ///
3303    /// Panics if `divisor` is zero.
3304    ///
3305    /// # Examples
3306    ///
3307    /// ```rust
3308    /// use rug::Integer;
3309    /// let mut dividend_quotient = Integer::from(-23);
3310    /// let mut divisor_rem = Integer::from(10);
3311    /// dividend_quotient.div_rem_floor_mut(&mut divisor_rem);
3312    /// assert_eq!(dividend_quotient, -3);
3313    /// assert_eq!(divisor_rem, 7);
3314    /// ```
3315    #[inline]
3316    pub fn div_rem_floor_mut(&mut self, divisor: &mut Self) {
3317        xmpz::fdiv_qr(self, divisor, (), ());
3318    }
3319
3320    /// Performs a division producing both the quotient and remainder, with the
3321    /// quotient rounded down.
3322    ///
3323    /// The remainder has the same sign as the divisor.
3324    ///
3325    /// The following are implemented with the returned [incomplete-computation
3326    /// value][icv] as `Src`:
3327    ///   * <code>[Assign]\<Src> for [(][tuple][Integer][], [Integer][][)][tuple]</code>
3328    ///   * <code>[Assign]\<Src> for [(][tuple]\&mut [Integer], \&mut [Integer][][)][tuple]</code>
3329    ///   * <code>[From]\<Src> for [(][tuple][Integer][], [Integer][][)][tuple]</code>
3330    ///   * <code>[Complete]\<[Completed][Complete::Completed] = [(][tuple][Integer][], [Integer][][)][tuple]> for Src</code>
3331    ///
3332    /// # Examples
3333    ///
3334    /// ```rust
3335    /// use rug::{Complete, Integer};
3336    /// let dividend = Integer::from(-23);
3337    /// let divisor = Integer::from(-10);
3338    /// let (quotient, rem) = dividend.div_rem_floor_ref(&divisor).complete();
3339    /// assert_eq!(quotient, 2);
3340    /// assert_eq!(rem, -3);
3341    /// ```
3342    ///
3343    /// [icv]: crate#incomplete-computation-values
3344    #[inline]
3345    pub fn div_rem_floor_ref<'a>(&'a self, divisor: &'a Self) -> DivRemFloorIncomplete<'a> {
3346        DivRemFloorIncomplete {
3347            ref_self: self,
3348            divisor,
3349        }
3350    }
3351
3352    /// Performs a division producing both the quotient and remainder, with the
3353    /// quotient rounded to the nearest integer.
3354    ///
3355    /// When the quotient before rounding lies exactly between two integers, it
3356    /// is rounded away from zero.
3357    ///
3358    /// # Panics
3359    ///
3360    /// Panics if `divisor` is zero.
3361    ///
3362    /// # Examples
3363    ///
3364    /// ```rust
3365    /// use rug::Integer;
3366    /// // 23 / -10 → -2 rem 3
3367    /// let (q, rem) = Integer::from(23).div_rem_round((-10).into());
3368    /// assert!(q == -2 && rem == 3);
3369    /// // 25 / 10 → 3 rem -5
3370    /// let (q, rem) = Integer::from(25).div_rem_round(10.into());
3371    /// assert!(q == 3 && rem == -5);
3372    /// // -27 / 10 → -3 rem 3
3373    /// let (q, rem) = Integer::from(-27).div_rem_round(10.into());
3374    /// assert!(q == -3 && rem == 3);
3375    /// ```
3376    #[inline]
3377    pub fn div_rem_round(mut self, mut divisor: Self) -> (Self, Self) {
3378        self.div_rem_round_mut(&mut divisor);
3379        (self, divisor)
3380    }
3381
3382    /// Performs a division producing both the quotient and remainder, with the
3383    /// quotient rounded to the nearest integer.
3384    ///
3385    /// When the quotient before rounding lies exactly between two integers, it
3386    /// is rounded away from zero.
3387    ///
3388    /// # Panics
3389    ///
3390    /// Panics if `divisor` is zero.
3391    ///
3392    /// # Examples
3393    ///
3394    /// ```rust
3395    /// use rug::Integer;
3396    /// // -25 / -10 → 3 rem 5
3397    /// let mut dividend_quotient = Integer::from(-25);
3398    /// let mut divisor_rem = Integer::from(-10);
3399    /// dividend_quotient.div_rem_round_mut(&mut divisor_rem);
3400    /// assert_eq!(dividend_quotient, 3);
3401    /// assert_eq!(divisor_rem, 5);
3402    /// ```
3403    #[inline]
3404    pub fn div_rem_round_mut(&mut self, divisor: &mut Self) {
3405        xmpz::rdiv_qr(self, divisor, (), ());
3406    }
3407
3408    /// Performs a division producing both the quotient and remainder, with the
3409    /// quotient rounded to the nearest integer.
3410    ///
3411    /// When the quotient before rounding lies exactly between two integers, it
3412    /// is rounded away from zero.
3413    ///
3414    /// The following are implemented with the returned [incomplete-computation
3415    /// value][icv] as `Src`:
3416    ///   * <code>[Assign]\<Src> for [(][tuple][Integer][], [Integer][][)][tuple]</code>
3417    ///   * <code>[Assign]\<Src> for [(][tuple]\&mut [Integer], \&mut [Integer][][)][tuple]</code>
3418    ///   * <code>[From]\<Src> for [(][tuple][Integer][], [Integer][][)][tuple]</code>
3419    ///   * <code>[Complete]\<[Completed][Complete::Completed] = [(][tuple][Integer][], [Integer][][)][tuple]> for Src</code>
3420    ///
3421    /// # Examples
3422    ///
3423    /// ```rust
3424    /// use rug::{Complete, Integer};
3425    /// // -28 / -10 → 3 rem 2
3426    /// let dividend = Integer::from(-28);
3427    /// let divisor = Integer::from(-10);
3428    /// let (quotient, rem) = dividend.div_rem_round_ref(&divisor).complete();
3429    /// assert_eq!(quotient, 3);
3430    /// assert_eq!(rem, 2);
3431    /// ```
3432    ///
3433    /// [icv]: crate#incomplete-computation-values
3434    #[inline]
3435    pub fn div_rem_round_ref<'a>(&'a self, divisor: &'a Self) -> DivRemRoundIncomplete<'a> {
3436        DivRemRoundIncomplete {
3437            ref_self: self,
3438            divisor,
3439        }
3440    }
3441
3442    /// Performs Euclidean division producing both the quotient and remainder,
3443    /// with a positive remainder.
3444    ///
3445    /// # Panics
3446    ///
3447    /// Panics if `divisor` is zero.
3448    ///
3449    /// # Examples
3450    ///
3451    /// ```rust
3452    /// use rug::Integer;
3453    /// let dividend = Integer::from(23);
3454    /// let divisor = Integer::from(-10);
3455    /// let (quotient, rem) = dividend.div_rem_euc(divisor);
3456    /// assert_eq!(quotient, -2);
3457    /// assert_eq!(rem, 3);
3458    /// ```
3459    #[inline]
3460    pub fn div_rem_euc(mut self, mut divisor: Self) -> (Self, Self) {
3461        self.div_rem_euc_mut(&mut divisor);
3462        (self, divisor)
3463    }
3464
3465    /// Performs Euclidean division producing both the quotient and remainder,
3466    /// with a positive remainder.
3467    ///
3468    /// The quotient is stored in `self` and the remainder is stored in
3469    /// `divisor`.
3470    ///
3471    /// # Panics
3472    ///
3473    /// Panics if `divisor` is zero.
3474    ///
3475    /// # Examples
3476    ///
3477    /// ```rust
3478    /// use rug::Integer;
3479    /// let mut dividend_quotient = Integer::from(-23);
3480    /// let mut divisor_rem = Integer::from(10);
3481    /// dividend_quotient.div_rem_euc_mut(&mut divisor_rem);
3482    /// assert_eq!(dividend_quotient, -3);
3483    /// assert_eq!(divisor_rem, 7);
3484    /// ```
3485    #[inline]
3486    pub fn div_rem_euc_mut(&mut self, divisor: &mut Self) {
3487        xmpz::ediv_qr(self, divisor, (), ());
3488    }
3489
3490    /// Performs Euclidan division producing both the quotient and remainder,
3491    /// with a positive remainder.
3492    ///
3493    /// The following are implemented with the returned [incomplete-computation
3494    /// value][icv] as `Src`:
3495    ///   * <code>[Assign]\<Src> for [(][tuple][Integer][], [Integer][][)][tuple]</code>
3496    ///   * <code>[Assign]\<Src> for [(][tuple]\&mut [Integer], \&mut [Integer][][)][tuple]</code>
3497    ///   * <code>[From]\<Src> for [(][tuple][Integer][], [Integer][][)][tuple]</code>
3498    ///   * <code>[Complete]\<[Completed][Complete::Completed] = [(][tuple][Integer][], [Integer][][)][tuple]> for Src</code>
3499    ///
3500    /// # Examples
3501    ///
3502    /// ```rust
3503    /// use rug::{Complete, Integer};
3504    /// let dividend = Integer::from(-23);
3505    /// let divisor = Integer::from(-10);
3506    /// let (quotient, rem) = dividend.div_rem_euc_ref(&divisor).complete();
3507    /// assert_eq!(quotient, 3);
3508    /// assert_eq!(rem, 7);
3509    /// ```
3510    ///
3511    /// [icv]: crate#incomplete-computation-values
3512    #[inline]
3513    pub fn div_rem_euc_ref<'a>(&'a self, divisor: &'a Self) -> DivRemEucIncomplete<'a> {
3514        DivRemEucIncomplete {
3515            ref_self: self,
3516            divisor,
3517        }
3518    }
3519
3520    /// Returns the modulo, or the remainder of Euclidean division by a [`u32`].
3521    ///
3522    /// The result is always zero or positive.
3523    ///
3524    /// # Panics
3525    ///
3526    /// Panics if `modulo` is zero.
3527    ///
3528    /// # Examples
3529    ///
3530    /// ```rust
3531    /// use rug::Integer;
3532    /// let pos = Integer::from(23);
3533    /// assert_eq!(pos.mod_u(1), 0);
3534    /// assert_eq!(pos.mod_u(10), 3);
3535    /// assert_eq!(pos.mod_u(100), 23);
3536    /// let neg = Integer::from(-23);
3537    /// assert_eq!(neg.mod_u(1), 0);
3538    /// assert_eq!(neg.mod_u(10), 7);
3539    /// assert_eq!(neg.mod_u(100), 77);
3540    /// ```
3541    #[inline]
3542    pub fn mod_u(&self, modulo: u32) -> u32 {
3543        xmpz::fdiv_ui(self, modulo.into()).wrapping_cast()
3544    }
3545
3546    /// Performs an exact division.
3547    ///
3548    /// This is much faster than normal division, but produces correct results
3549    /// only when the division is exact.
3550    ///
3551    /// # Panics
3552    ///
3553    /// Panics if `divisor` is zero.
3554    ///
3555    /// # Examples
3556    ///
3557    /// ```rust
3558    /// use rug::Integer;
3559    /// let i = Integer::from(12345 * 54321);
3560    /// let quotient = i.div_exact(&Integer::from(12345));
3561    /// assert_eq!(quotient, 54321);
3562    /// ```
3563    #[inline]
3564    #[must_use]
3565    pub fn div_exact(mut self, divisor: &Self) -> Self {
3566        self.div_exact_mut(divisor);
3567        self
3568    }
3569
3570    /// Performs an exact division.
3571    ///
3572    /// This is much faster than normal division, but produces correct results
3573    /// only when the division is exact.
3574    ///
3575    /// # Panics
3576    ///
3577    /// Panics if `divisor` is zero.
3578    ///
3579    /// # Examples
3580    ///
3581    /// ```rust
3582    /// use rug::Integer;
3583    /// let mut i = Integer::from(12345 * 54321);
3584    /// i.div_exact_mut(&Integer::from(12345));
3585    /// assert_eq!(i, 54321);
3586    /// ```
3587    #[inline]
3588    pub fn div_exact_mut(&mut self, divisor: &Self) {
3589        xmpz::divexact(self, (), divisor);
3590    }
3591
3592    /// Performs an exact division `dividend` / `self`.
3593    ///
3594    /// This is much faster than normal division, but produces correct results
3595    /// only when the division is exact.
3596    ///
3597    /// # Panics
3598    ///
3599    /// Panics if `self` is zero.
3600    ///
3601    /// # Examples
3602    ///
3603    /// ```rust
3604    /// use rug::Integer;
3605    /// let mut i = Integer::from(12345);
3606    /// i.div_exact_from(&Integer::from(12345 * 54321));
3607    /// assert_eq!(i, 54321);
3608    /// ```
3609    pub fn div_exact_from(&mut self, dividend: &Integer) {
3610        xmpz::divexact(self, dividend, ());
3611    }
3612
3613    /// Performs an exact division.
3614    ///
3615    /// This is much faster than normal division, but produces correct results
3616    /// only when the division is exact.
3617    ///
3618    /// The following are implemented with the returned [incomplete-computation
3619    /// value][icv] as `Src`:
3620    ///   * <code>[Assign]\<Src> for [Integer]</code>
3621    ///   * <code>[From]\<Src> for [Integer]</code>
3622    ///   * <code>[Complete]\<[Completed][Complete::Completed] = [Integer]> for Src</code>
3623    ///
3624    /// # Examples
3625    ///
3626    /// ```rust
3627    /// use rug::Integer;
3628    /// let i = Integer::from(12345 * 54321);
3629    /// let divisor = Integer::from(12345);
3630    /// let r = i.div_exact_ref(&divisor);
3631    /// let quotient = Integer::from(r);
3632    /// assert_eq!(quotient, 54321);
3633    /// ```
3634    ///
3635    /// [icv]: crate#incomplete-computation-values
3636    #[inline]
3637    pub fn div_exact_ref<'a>(&'a self, divisor: &'a Self) -> DivExactIncomplete<'a> {
3638        DivExactIncomplete {
3639            ref_self: self,
3640            divisor,
3641        }
3642    }
3643
3644    /// Performs an exact division.
3645    ///
3646    /// This is much faster than normal division, but produces correct results
3647    /// only when the division is exact.
3648    ///
3649    /// # Panics
3650    ///
3651    /// Panics if `divisor` is zero.
3652    ///
3653    /// # Examples
3654    ///
3655    /// ```rust
3656    /// use rug::Integer;
3657    /// let i = Integer::from(12345 * 54321);
3658    /// let q = i.div_exact_u(12345);
3659    /// assert_eq!(q, 54321);
3660    /// ```
3661    #[inline]
3662    #[must_use]
3663    pub fn div_exact_u(mut self, divisor: u32) -> Self {
3664        self.div_exact_u_mut(divisor);
3665        self
3666    }
3667
3668    /// Performs an exact division.
3669    ///
3670    /// This is much faster than normal division, but produces correct results
3671    /// only when the division is exact.
3672    ///
3673    /// # Panics
3674    ///
3675    /// Panics if `divisor` is zero.
3676    ///
3677    /// # Examples
3678    ///
3679    /// ```rust
3680    /// use rug::Integer;
3681    /// let mut i = Integer::from(12345 * 54321);
3682    /// i.div_exact_u_mut(12345);
3683    /// assert_eq!(i, 54321);
3684    /// ```
3685    #[inline]
3686    pub fn div_exact_u_mut(&mut self, divisor: u32) {
3687        xmpz::divexact_u32(self, (), divisor);
3688    }
3689
3690    /// Performs an exact division.
3691    ///
3692    /// This is much faster than normal division, but produces correct results
3693    /// only when the division is exact.
3694    ///
3695    /// The following are implemented with the returned [incomplete-computation
3696    /// value][icv] as `Src`:
3697    ///   * <code>[Assign]\<Src> for [Integer]</code>
3698    ///   * <code>[From]\<Src> for [Integer]</code>
3699    ///   * <code>[Complete]\<[Completed][Complete::Completed] = [Integer]> for Src</code>
3700    ///
3701    /// # Examples
3702    ///
3703    /// ```rust
3704    /// use rug::Integer;
3705    /// let i = Integer::from(12345 * 54321);
3706    /// let r = i.div_exact_u_ref(12345);
3707    /// assert_eq!(Integer::from(r), 54321);
3708    /// ```
3709    ///
3710    /// [icv]: crate#incomplete-computation-values
3711    #[inline]
3712    pub fn div_exact_u_ref(&self, divisor: u32) -> DivExactUIncomplete<'_> {
3713        DivExactUIncomplete {
3714            ref_self: self,
3715            divisor,
3716        }
3717    }
3718
3719    /// Finds the inverse modulo `modulo` and returns [`Ok(inverse)`][Ok] if it
3720    /// exists, or [`Err(unchanged)`][Err] if the inverse does not exist.
3721    ///
3722    /// The inverse exists if the modulo is not zero, and `self` and the modulo
3723    /// are co-prime, that is their GCD is 1.
3724    ///
3725    /// # Examples
3726    ///
3727    /// ```rust
3728    /// use rug::Integer;
3729    /// let n = Integer::from(2);
3730    /// // Modulo 4, 2 has no inverse: there is no i such that 2 × i = 1.
3731    /// let inv_mod_4 = match n.invert(&Integer::from(4)) {
3732    ///     Ok(_) => unreachable!(),
3733    ///     Err(unchanged) => unchanged,
3734    /// };
3735    /// // no inverse exists, so value is unchanged
3736    /// assert_eq!(inv_mod_4, 2);
3737    /// let n = inv_mod_4;
3738    /// // Modulo 5, the inverse of 2 is 3, as 2 × 3 = 1.
3739    /// let inv_mod_5 = match n.invert(&Integer::from(5)) {
3740    ///     Ok(inverse) => inverse,
3741    ///     Err(_) => unreachable!(),
3742    /// };
3743    /// assert_eq!(inv_mod_5, 3);
3744    /// ```
3745    #[inline]
3746    pub fn invert(mut self, modulo: &Self) -> Result<Self, Self> {
3747        match self.invert_mut(modulo) {
3748            Ok(()) => Ok(self),
3749            Err(()) => Err(self),
3750        }
3751    }
3752
3753    /// Finds the inverse modulo `modulo` if an inverse exists.
3754    ///
3755    /// The inverse exists if the modulo is not zero, and `self` and the modulo
3756    /// are co-prime, that is their GCD is 1.
3757    ///
3758    /// # Examples
3759    ///
3760    /// ```rust
3761    /// use rug::Integer;
3762    /// let mut n = Integer::from(2);
3763    /// // Modulo 4, 2 has no inverse: there is no i such that 2 × i = 1.
3764    /// match n.invert_mut(&Integer::from(4)) {
3765    ///     Ok(()) => unreachable!(),
3766    ///     Err(()) => assert_eq!(n, 2),
3767    /// }
3768    /// // Modulo 5, the inverse of 2 is 3, as 2 × 3 = 1.
3769    /// match n.invert_mut(&Integer::from(5)) {
3770    ///     Ok(()) => assert_eq!(n, 3),
3771    ///     Err(()) => unreachable!(),
3772    /// }
3773    /// ```
3774    #[inline]
3775    #[allow(clippy::result_unit_err)]
3776    pub fn invert_mut(&mut self, modulo: &Self) -> Result<(), ()> {
3777        match self.invert_ref(modulo) {
3778            Some(InvertIncomplete { sinverse, .. }) => {
3779                xmpz::finish_invert(self, &sinverse, modulo);
3780                Ok(())
3781            }
3782            None => Err(()),
3783        }
3784    }
3785
3786    /// Finds the inverse modulo `modulo` if an inverse exists.
3787    ///
3788    /// The inverse exists if the modulo is not zero, and `self` and the modulo
3789    /// are co-prime, that is their GCD is 1.
3790    ///
3791    /// The following are implemented with the unwrapped returned
3792    /// [incomplete-computation value][icv] as `Src`:
3793    ///   * <code>[Assign]\<Src> for [Integer]</code>
3794    ///   * <code>[From]\<Src> for [Integer]</code>
3795    ///   * <code>[Complete]\<[Completed][Complete::Completed] = [Integer]> for Src</code>
3796    ///
3797    /// # Examples
3798    ///
3799    /// ```rust
3800    /// use rug::Integer;
3801    /// let two = Integer::from(2);
3802    /// let four = Integer::from(4);
3803    /// let five = Integer::from(5);
3804    ///
3805    /// // Modulo 4, 2 has no inverse, there is no i such that 2 × i = 1.
3806    /// // For this conversion, if no inverse exists, the Integer
3807    /// // created is left unchanged as 0.
3808    /// assert!(two.invert_ref(&four).is_none());
3809    ///
3810    /// // Modulo 5, the inverse of 2 is 3, as 2 × 3 = 1.
3811    /// let r = two.invert_ref(&five).unwrap();
3812    /// let inverse = Integer::from(r);
3813    /// assert_eq!(inverse, 3);
3814    /// ```
3815    ///
3816    /// [icv]: crate#incomplete-computation-values
3817    pub fn invert_ref<'a>(&'a self, modulo: &'a Self) -> Option<InvertIncomplete<'a>> {
3818        xmpz::start_invert(self, modulo).map(|sinverse| InvertIncomplete { sinverse, modulo })
3819    }
3820
3821    /// Raises a number to the power of `exponent` modulo `modulo` and returns
3822    /// [`Ok(power)`][Ok] if an answer exists, or [`Err(unchanged)`][Err] if it
3823    /// does not.
3824    ///
3825    /// If the exponent is negative, then the number must have an inverse for an
3826    /// answer to exist.
3827    ///
3828    /// When the exponent is positive and the modulo is not zero, an answer
3829    /// always exists.
3830    ///
3831    /// # Examples
3832    ///
3833    /// ```rust
3834    /// use rug::Integer;
3835    /// // 7 ^ 5 = 16807
3836    /// let n = Integer::from(7);
3837    /// let e = Integer::from(5);
3838    /// let m = Integer::from(1000);
3839    /// let power = match n.pow_mod(&e, &m) {
3840    ///     Ok(power) => power,
3841    ///     Err(_) => unreachable!(),
3842    /// };
3843    /// assert_eq!(power, 807);
3844    /// ```
3845    ///
3846    /// When the exponent is negative, an answer exists if an inverse exists.
3847    ///
3848    /// ```rust
3849    /// use rug::Integer;
3850    /// // 7 × 143 modulo 1000 = 1, so 7 has an inverse 143.
3851    /// // 7 ^ -5 modulo 1000 = 143 ^ 5 modulo 1000 = 943.
3852    /// let n = Integer::from(7);
3853    /// let e = Integer::from(-5);
3854    /// let m = Integer::from(1000);
3855    /// let power = match n.pow_mod(&e, &m) {
3856    ///     Ok(power) => power,
3857    ///     Err(_) => unreachable!(),
3858    /// };
3859    /// assert_eq!(power, 943);
3860    /// ```
3861    #[inline]
3862    pub fn pow_mod(mut self, exponent: &Self, modulo: &Self) -> Result<Self, Self> {
3863        match self.pow_mod_mut(exponent, modulo) {
3864            Ok(()) => Ok(self),
3865            Err(()) => Err(self),
3866        }
3867    }
3868
3869    /// Raises a number to the power of `exponent` modulo `modulo` if an answer
3870    /// exists.
3871    ///
3872    /// If the exponent is negative, then the number must have an inverse for an
3873    /// answer to exist.
3874    ///
3875    /// # Examples
3876    ///
3877    /// ```rust
3878    /// use rug::{Assign, Integer};
3879    /// // Modulo 1000, 2 has no inverse: there is no i such that 2 × i = 1.
3880    /// let mut n = Integer::from(2);
3881    /// let e = Integer::from(-5);
3882    /// let m = Integer::from(1000);
3883    /// match n.pow_mod_mut(&e, &m) {
3884    ///     Ok(()) => unreachable!(),
3885    ///     Err(()) => assert_eq!(n, 2),
3886    /// }
3887    /// // 7 × 143 modulo 1000 = 1, so 7 has an inverse 143.
3888    /// // 7 ^ -5 modulo 1000 = 143 ^ 5 modulo 1000 = 943.
3889    /// n.assign(7);
3890    /// match n.pow_mod_mut(&e, &m) {
3891    ///     Ok(()) => assert_eq!(n, 943),
3892    ///     Err(()) => unreachable!(),
3893    /// }
3894    /// ```
3895    #[inline]
3896    #[allow(clippy::result_unit_err)]
3897    pub fn pow_mod_mut(&mut self, exponent: &Self, modulo: &Self) -> Result<(), ()> {
3898        let Some(PowModIncomplete { sinverse, .. }) = self.pow_mod_ref(exponent, modulo) else {
3899            return Err(());
3900        };
3901        if let Some(sinverse) = &sinverse {
3902            xmpz::pow_mod(self, sinverse, exponent, modulo);
3903        } else {
3904            xmpz::pow_mod(self, (), exponent, modulo);
3905        }
3906        Ok(())
3907    }
3908
3909    /// Raises a number to the power of `exponent` modulo `modulo` if an answer
3910    /// exists.
3911    ///
3912    /// If the exponent is negative, then the number must have an inverse for an
3913    /// answer to exist.
3914    ///
3915    /// The following are implemented with the unwrapped returned
3916    /// [incomplete-computation value][icv] as `Src`:
3917    ///   * <code>[Assign]\<Src> for [Integer]</code>
3918    ///   * <code>[From]\<Src> for [Integer]</code>
3919    ///   * <code>[Complete]\<[Completed][Complete::Completed] = [Integer]> for Src</code>
3920    ///
3921    /// # Examples
3922    ///
3923    /// ```rust
3924    /// use rug::Integer;
3925    /// let two = Integer::from(2);
3926    /// let thousand = Integer::from(1000);
3927    /// let minus_five = Integer::from(-5);
3928    /// let seven = Integer::from(7);
3929    ///
3930    /// // Modulo 1000, 2 has no inverse: there is no i such that 2 × i = 1.
3931    /// assert!(two.pow_mod_ref(&minus_five, &thousand).is_none());
3932    ///
3933    /// // 7 × 143 modulo 1000 = 1, so 7 has an inverse 143.
3934    /// // 7 ^ -5 modulo 1000 = 143 ^ 5 modulo 1000 = 943.
3935    /// let r = seven.pow_mod_ref(&minus_five, &thousand).unwrap();
3936    /// let power = Integer::from(r);
3937    /// assert_eq!(power, 943);
3938    /// ```
3939    ///
3940    /// [icv]: crate#incomplete-computation-values
3941    pub fn pow_mod_ref<'a>(
3942        &'a self,
3943        exponent: &'a Self,
3944        modulo: &'a Self,
3945    ) -> Option<PowModIncomplete<'a>> {
3946        if exponent.is_negative() {
3947            let InvertIncomplete { sinverse, .. } = self.invert_ref(modulo)?;
3948            Some(PowModIncomplete {
3949                ref_self: None,
3950                sinverse: Some(sinverse),
3951                exponent,
3952                modulo,
3953            })
3954        } else if !modulo.is_zero() {
3955            Some(PowModIncomplete {
3956                ref_self: Some(self),
3957                sinverse: None,
3958                exponent,
3959                modulo,
3960            })
3961        } else {
3962            None
3963        }
3964    }
3965
3966    /// Raises a number to the power of `exponent` modulo `modulo`, with
3967    /// resilience to side-channel attacks.
3968    ///
3969    /// The exponent must be greater than zero, and the modulo must be odd.
3970    ///
3971    /// This method is intended for cryptographic purposes where resilience to
3972    /// side-channel attacks is desired. The function is designed to take the
3973    /// same time and use the same cache access patterns for same-sized
3974    /// arguments, assuming that the arguments are placed at the same position
3975    /// and the machine state is identical when starting.
3976    ///
3977    /// # Panics
3978    ///
3979    /// Panics if `exponent` ≤ 0 or if `modulo` is even.
3980    ///
3981    /// # Examples
3982    ///
3983    /// ```rust
3984    /// # // wrap in fn to suppress valgrind false positive
3985    /// # fn doctest_secure_pow_mod() {
3986    /// use rug::Integer;
3987    /// // 7 ^ 4 mod 13 = 9
3988    /// let n = Integer::from(7);
3989    /// let e = Integer::from(4);
3990    /// let m = Integer::from(13);
3991    /// let power = n.secure_pow_mod(&e, &m);
3992    /// assert_eq!(power, 9);
3993    /// # }
3994    /// # doctest_secure_pow_mod();
3995    /// ```
3996    #[inline]
3997    #[must_use]
3998    pub fn secure_pow_mod(mut self, exponent: &Self, modulo: &Self) -> Self {
3999        self.secure_pow_mod_mut(exponent, modulo);
4000        self
4001    }
4002
4003    /// Raises a number to the power of `exponent` modulo `modulo`, with
4004    /// resilience to side-channel attacks.
4005    ///
4006    /// The exponent must be greater than zero, and the modulo must be odd.
4007    ///
4008    /// This method is intended for cryptographic purposes where resilience to
4009    /// side-channel attacks is desired. The function is designed to take the
4010    /// same time and use the same cache access patterns for same-sized
4011    /// arguments, assuming that the arguments are placed at the same position
4012    /// and the machine state is identical when starting.
4013    ///
4014    /// # Panics
4015    ///
4016    /// Panics if `exponent` ≤ 0 or if `modulo` is even.
4017    ///
4018    /// # Examples
4019    ///
4020    /// ```rust
4021    /// # // wrap in fn to suppress valgrind false positive
4022    /// # fn doctest_secure_pow_mod_mut() {
4023    /// use rug::Integer;
4024    /// // 7 ^ 4 mod 13 = 9
4025    /// let mut n = Integer::from(7);
4026    /// let e = Integer::from(4);
4027    /// let m = Integer::from(13);
4028    /// n.secure_pow_mod_mut(&e, &m);
4029    /// assert_eq!(n, 9);
4030    /// # }
4031    /// # doctest_secure_pow_mod_mut();
4032    /// ```
4033    #[inline]
4034    pub fn secure_pow_mod_mut(&mut self, exponent: &Self, modulo: &Self) {
4035        xmpz::powm_sec(self, (), exponent, modulo);
4036    }
4037
4038    /// Raises a number to the power of `exponent` modulo `modulo`, with
4039    /// resilience to side-channel attacks.
4040    ///
4041    /// The exponent must be greater than zero, and the modulo must be odd.
4042    ///
4043    /// This method is intended for cryptographic purposes where resilience to
4044    /// side-channel attacks is desired. The function is designed to take the
4045    /// same time and use the same cache access patterns for same-sized
4046    /// arguments, assuming that the arguments are placed at the same position
4047    /// and the machine state is identical when starting.
4048    ///
4049    /// The following are implemented with the returned [incomplete-computation
4050    /// value][icv] as `Src`:
4051    ///   * <code>[Assign]\<Src> for [Integer]</code>
4052    ///   * <code>[From]\<Src> for [Integer]</code>
4053    ///   * <code>[Complete]\<[Completed][Complete::Completed] = [Integer]> for Src</code>
4054    ///
4055    /// # Panics
4056    ///
4057    /// Panics if `exponent` ≤ 0 or if `modulo` is even.
4058    ///
4059    /// # Examples
4060    ///
4061    /// ```rust
4062    /// # // wrap in fn to suppress valgrind false positive
4063    /// # fn doctest_secure_pow_mod_ref() {
4064    /// use rug::Integer;
4065    /// // 7 ^ 4 mod 13 = 9
4066    /// let n = Integer::from(7);
4067    /// let e = Integer::from(4);
4068    /// let m = Integer::from(13);
4069    /// let power = Integer::from(n.secure_pow_mod_ref(&e, &m));
4070    /// assert_eq!(power, 9);
4071    /// # }
4072    /// # doctest_secure_pow_mod_ref();
4073    /// ```
4074    ///
4075    /// [icv]: crate#incomplete-computation-values
4076    #[inline]
4077    pub fn secure_pow_mod_ref<'a>(
4078        &'a self,
4079        exponent: &'a Self,
4080        modulo: &'a Self,
4081    ) -> SecurePowModIncomplete<'a> {
4082        SecurePowModIncomplete {
4083            ref_self: self,
4084            exponent,
4085            modulo,
4086        }
4087    }
4088
4089    /// Raises `base` to the power of `exponent`.
4090    ///
4091    /// The following are implemented with the returned [incomplete-computation
4092    /// value][icv] as `Src`:
4093    ///   * <code>[Assign]\<Src> for [Integer]</code>
4094    ///   * <code>[From]\<Src> for [Integer]</code>
4095    ///   * <code>[Complete]\<[Completed][Complete::Completed] = [Integer]> for Src</code>
4096    ///
4097    /// # Examples
4098    ///
4099    /// ```rust
4100    /// use rug::{Complete, Integer};
4101    /// assert_eq!(Integer::u_pow_u(13, 12).complete(), 13_u64.pow(12));
4102    /// ```
4103    ///
4104    /// [icv]: crate#incomplete-computation-values
4105    #[inline]
4106    pub fn u_pow_u(base: u32, exponent: u32) -> UPowUIncomplete {
4107        UPowUIncomplete { base, exponent }
4108    }
4109
4110    /// Raises `base` to the power of `exponent`.
4111    ///
4112    /// The following are implemented with the returned [incomplete-computation
4113    /// value][icv] as `Src`:
4114    ///   * <code>[Assign]\<Src> for [Integer]</code>
4115    ///   * <code>[From]\<Src> for [Integer]</code>
4116    ///   * <code>[Complete]\<[Completed][Complete::Completed] = [Integer]> for Src</code>
4117    ///
4118    /// # Examples
4119    ///
4120    /// ```rust
4121    /// use rug::{Assign, Integer};
4122    /// let mut ans = Integer::new();
4123    /// ans.assign(Integer::i_pow_u(-13, 13));
4124    /// assert_eq!(ans, (-13_i64).pow(13));
4125    /// ans.assign(Integer::i_pow_u(13, 13));
4126    /// assert_eq!(ans, (13_i64).pow(13));
4127    /// ```
4128    ///
4129    /// [icv]: crate#incomplete-computation-values
4130    #[inline]
4131    pub fn i_pow_u(base: i32, exponent: u32) -> IPowUIncomplete {
4132        IPowUIncomplete { base, exponent }
4133    }
4134
4135    /// Computes the <i>n</i>th root and truncates the result.
4136    ///
4137    /// # Panics
4138    ///
4139    /// Panics if <i>n</i> is zero or if <i>n</i> is even and the value is
4140    /// negative.
4141    ///
4142    /// # Examples
4143    ///
4144    /// ```rust
4145    /// use rug::Integer;
4146    /// let i = Integer::from(1004);
4147    /// let root = i.root(3);
4148    /// assert_eq!(root, 10);
4149    /// ```
4150    #[inline]
4151    #[must_use]
4152    pub fn root(mut self, n: u32) -> Self {
4153        self.root_mut(n);
4154        self
4155    }
4156
4157    /// Computes the <i>n</i>th root and truncates the result.
4158    ///
4159    /// # Panics
4160    ///
4161    /// Panics if <i>n</i> is zero or if <i>n</i> is even and the value is
4162    /// negative.
4163    ///
4164    /// # Examples
4165    ///
4166    /// ```rust
4167    /// use rug::Integer;
4168    /// let mut i = Integer::from(1004);
4169    /// i.root_mut(3);
4170    /// assert_eq!(i, 10);
4171    /// ```
4172    #[inline]
4173    pub fn root_mut(&mut self, n: u32) {
4174        xmpz::root(self, (), n.into());
4175    }
4176
4177    /// Computes the <i>n</i>th root and truncates the result.
4178    ///
4179    /// The following are implemented with the returned [incomplete-computation
4180    /// value][icv] as `Src`:
4181    ///   * <code>[Assign]\<Src> for [Integer]</code>
4182    ///   * <code>[From]\<Src> for [Integer]</code>
4183    ///   * <code>[Complete]\<[Completed][Complete::Completed] = [Integer]> for Src</code>
4184    ///
4185    /// # Examples
4186    ///
4187    /// ```rust
4188    /// use rug::Integer;
4189    /// let i = Integer::from(1004);
4190    /// assert_eq!(Integer::from(i.root_ref(3)), 10);
4191    /// ```
4192    ///
4193    /// [icv]: crate#incomplete-computation-values
4194    #[inline]
4195    pub fn root_ref(&self, n: u32) -> RootIncomplete<'_> {
4196        let n = n.into();
4197        RootIncomplete { ref_self: self, n }
4198    }
4199
4200    /// Computes the <i>n</i>th root and returns the truncated root and the
4201    /// remainder.
4202    ///
4203    /// The remainder is the original number minus the truncated root raised to
4204    /// the power of <i>n</i>.
4205    ///
4206    /// The initial value of `remainder` is ignored.
4207    ///
4208    /// # Panics
4209    ///
4210    /// Panics if <i>n</i> is zero or if <i>n</i> is even and the value is
4211    /// negative.
4212    ///
4213    /// # Examples
4214    ///
4215    /// ```rust
4216    /// use rug::Integer;
4217    /// let i = Integer::from(1004);
4218    /// let (root, rem) = i.root_rem(Integer::new(), 3);
4219    /// assert_eq!(root, 10);
4220    /// assert_eq!(rem, 4);
4221    /// ```
4222    #[inline]
4223    pub fn root_rem(mut self, mut remainder: Self, n: u32) -> (Self, Self) {
4224        self.root_rem_mut(&mut remainder, n);
4225        (self, remainder)
4226    }
4227
4228    /// Computes the <i>n</i>th root and returns the truncated root and the
4229    /// remainder.
4230    ///
4231    /// The remainder is the original number minus the truncated root raised to
4232    /// the power of <i>n</i>.
4233    ///
4234    /// The initial value of `remainder` is ignored.
4235    ///
4236    /// # Panics
4237    ///
4238    /// Panics if <i>n</i> is zero or if <i>n</i> is even and the value is
4239    /// negative.
4240    ///
4241    /// # Examples
4242    ///
4243    /// ```rust
4244    /// use rug::Integer;
4245    /// let mut i = Integer::from(1004);
4246    /// let mut rem = Integer::new();
4247    /// i.root_rem_mut(&mut rem, 3);
4248    /// assert_eq!(i, 10);
4249    /// assert_eq!(rem, 4);
4250    /// ```
4251    #[inline]
4252    pub fn root_rem_mut(&mut self, remainder: &mut Self, n: u32) {
4253        xmpz::rootrem(self, remainder, (), n.into());
4254    }
4255
4256    /// Computes the <i>n</i>th root and returns the truncated root and the
4257    /// remainder.
4258    ///
4259    /// The remainder is the original number minus the truncated root raised to
4260    /// the power of <i>n</i>.
4261    ///
4262    /// The following are implemented with the returned [incomplete-computation
4263    /// value][icv] as `Src`:
4264    ///   * <code>[Assign]\<Src> for [(][tuple][Integer][], [Integer][][)][tuple]</code>
4265    ///   * <code>[Assign]\<Src> for [(][tuple]\&mut [Integer], \&mut [Integer][][)][tuple]</code>
4266    ///   * <code>[From]\<Src> for [(][tuple][Integer][], [Integer][][)][tuple]</code>
4267    ///   * <code>[Complete]\<[Completed][Complete::Completed] = [(][tuple][Integer][], [Integer][][)][tuple]> for Src</code>
4268    ///
4269    /// # Examples
4270    ///
4271    /// ```rust
4272    /// use rug::{Assign, Complete, Integer};
4273    /// let i = Integer::from(1004);
4274    /// let mut root = Integer::new();
4275    /// let mut rem = Integer::new();
4276    /// // 1004 = 10^3 + 5
4277    /// (&mut root, &mut rem).assign(i.root_rem_ref(3));
4278    /// assert_eq!(root, 10);
4279    /// assert_eq!(rem, 4);
4280    /// // 1004 = 3^6 + 275
4281    /// let (other_root, other_rem) = i.root_rem_ref(6).complete();
4282    /// assert_eq!(other_root, 3);
4283    /// assert_eq!(other_rem, 275);
4284    /// ```
4285    ///
4286    /// [icv]: crate#incomplete-computation-values
4287    #[inline]
4288    pub fn root_rem_ref(&self, n: u32) -> RootRemIncomplete<'_> {
4289        let n = n.into();
4290        RootRemIncomplete { ref_self: self, n }
4291    }
4292
4293    /// Computes the square.
4294    ///
4295    /// This method cannot be replaced by a multiplication using the `*`
4296    /// operator: `i * i` and `i * &i` are both errors.
4297    ///
4298    /// # Examples
4299    ///
4300    /// ```rust
4301    /// use rug::Integer;
4302    /// let i = Integer::from(13);
4303    /// let square = i.square();
4304    /// assert_eq!(square, 169);
4305    /// ```
4306    #[inline]
4307    #[must_use]
4308    pub fn square(mut self) -> Self {
4309        self.square_mut();
4310        self
4311    }
4312
4313    /// Computes the square.
4314    ///
4315    /// This method cannot be replaced by a compound multiplication and
4316    /// assignment using the `*=` operataor: `i *= i;` and `i *= &i;` are both
4317    /// errors.
4318    ///
4319    /// # Examples
4320    ///
4321    /// ```rust
4322    /// use rug::Integer;
4323    /// let mut i = Integer::from(13);
4324    /// i.square_mut();
4325    /// assert_eq!(i, 169);
4326    /// ```
4327    #[inline]
4328    pub fn square_mut(&mut self) {
4329        xmpz::mul(self, (), ());
4330    }
4331
4332    /// Computes the square.
4333    ///
4334    /// The following are implemented with the returned [incomplete-computation
4335    /// value][icv] as `Src`:
4336    ///   * <code>[Assign]\<Src> for [Integer]</code>
4337    ///   * <code>[From]\<Src> for [Integer]</code>
4338    ///   * <code>[Complete]\<[Completed][Complete::Completed] = [Integer]> for Src</code>
4339    ///   * <code>[AddAssign]\<Src> for [Integer]</code>
4340    ///   * <code>[Add]\<Src> for [Integer]</code>,
4341    ///     <code>[Add]\<[Integer]> for Src</code>
4342    ///   * <code>[SubAssign]\<Src> for [Integer]</code>,
4343    ///     <code>[SubFrom]\<Src> for [Integer]</code>
4344    ///   * <code>[Sub]\<Src> for [Integer]</code>,
4345    ///     <code>[Sub]\<[Integer]> for Src</code>
4346    ///
4347    /// `i.square_ref()` produces the exact same result as `&i * &i`.
4348    ///
4349    /// # Examples
4350    ///
4351    /// ```rust
4352    /// use rug::Integer;
4353    /// let i = Integer::from(13);
4354    /// assert_eq!(Integer::from(i.square_ref()), 169);
4355    /// ```
4356    ///
4357    /// [icv]: crate#incomplete-computation-values
4358    #[inline]
4359    pub fn square_ref(&self) -> MulIncomplete<'_> {
4360        self * self
4361    }
4362
4363    /// Computes the square root and truncates the result.
4364    ///
4365    /// # Panics
4366    ///
4367    /// Panics if the value is negative.
4368    ///
4369    /// # Examples
4370    ///
4371    /// ```rust
4372    /// use rug::Integer;
4373    /// let i = Integer::from(104);
4374    /// let sqrt = i.sqrt();
4375    /// assert_eq!(sqrt, 10);
4376    /// ```
4377    #[inline]
4378    #[must_use]
4379    pub fn sqrt(mut self) -> Self {
4380        self.sqrt_mut();
4381        self
4382    }
4383
4384    /// Computes the square root and truncates the result.
4385    ///
4386    /// # Panics
4387    ///
4388    /// Panics if the value is negative.
4389    ///
4390    /// # Examples
4391    ///
4392    /// ```rust
4393    /// use rug::Integer;
4394    /// let mut i = Integer::from(104);
4395    /// i.sqrt_mut();
4396    /// assert_eq!(i, 10);
4397    /// ```
4398    #[inline]
4399    pub fn sqrt_mut(&mut self) {
4400        xmpz::sqrt(self, ());
4401    }
4402
4403    /// Computes the square root and truncates the result.
4404    ///
4405    /// The following are implemented with the returned [incomplete-computation
4406    /// value][icv] as `Src`:
4407    ///   * <code>[Assign]\<Src> for [Integer]</code>
4408    ///   * <code>[From]\<Src> for [Integer]</code>
4409    ///   * <code>[Complete]\<[Completed][Complete::Completed] = [Integer]> for Src</code>
4410    ///
4411    /// # Examples
4412    ///
4413    /// ```rust
4414    /// use rug::Integer;
4415    /// let i = Integer::from(104);
4416    /// assert_eq!(Integer::from(i.sqrt_ref()), 10);
4417    /// ```
4418    ///
4419    /// [icv]: crate#incomplete-computation-values
4420    #[inline]
4421    pub fn sqrt_ref(&self) -> SqrtIncomplete<'_> {
4422        SqrtIncomplete { ref_self: self }
4423    }
4424
4425    /// Computes the square root and the remainder.
4426    ///
4427    /// The remainder is the original number minus the truncated root squared.
4428    ///
4429    /// The initial value of `remainder` is ignored.
4430    ///
4431    /// # Panics
4432    ///
4433    /// Panics if the value is negative.
4434    ///
4435    /// # Examples
4436    ///
4437    /// ```rust
4438    /// use rug::Integer;
4439    /// let i = Integer::from(104);
4440    /// let (sqrt, rem) = i.sqrt_rem(Integer::new());
4441    /// assert_eq!(sqrt, 10);
4442    /// assert_eq!(rem, 4);
4443    /// ```
4444    #[inline]
4445    pub fn sqrt_rem(mut self, mut remainder: Self) -> (Self, Self) {
4446        self.sqrt_rem_mut(&mut remainder);
4447        (self, remainder)
4448    }
4449
4450    /// Computes the square root and the remainder.
4451    ///
4452    /// The remainder is the original number minus the truncated root squared.
4453    ///
4454    /// The initial value of `remainder` is ignored.
4455    ///
4456    /// # Panics
4457    ///
4458    /// Panics if the value is negative.
4459    ///
4460    /// # Examples
4461    ///
4462    /// ```rust
4463    /// use rug::Integer;
4464    /// let mut i = Integer::from(104);
4465    /// let mut rem = Integer::new();
4466    /// i.sqrt_rem_mut(&mut rem);
4467    /// assert_eq!(i, 10);
4468    /// assert_eq!(rem, 4);
4469    /// ```
4470    #[inline]
4471    pub fn sqrt_rem_mut(&mut self, remainder: &mut Self) {
4472        xmpz::sqrtrem(self, remainder, ());
4473    }
4474
4475    /// Computes the square root and the remainder.
4476    ///
4477    /// The remainder is the original number minus the truncated root squared.
4478    ///
4479    /// The following are implemented with the returned [incomplete-computation
4480    /// value][icv] as `Src`:
4481    ///   * <code>[Assign]\<Src> for [(][tuple][Integer][], [Integer][][)][tuple]</code>
4482    ///   * <code>[Assign]\<Src> for [(][tuple]\&mut [Integer], \&mut [Integer][][)][tuple]</code>
4483    ///   * <code>[From]\<Src> for [(][tuple][Integer][], [Integer][][)][tuple]</code>
4484    ///   * <code>[Complete]\<[Completed][Complete::Completed] = [(][tuple][Integer][], [Integer][][)][tuple]> for Src</code>
4485    ///
4486    /// # Examples
4487    ///
4488    /// ```rust
4489    /// use rug::{Assign, Integer};
4490    /// let i = Integer::from(104);
4491    /// let mut sqrt = Integer::new();
4492    /// let mut rem = Integer::new();
4493    /// let r = i.sqrt_rem_ref();
4494    /// (&mut sqrt, &mut rem).assign(r);
4495    /// assert_eq!(sqrt, 10);
4496    /// assert_eq!(rem, 4);
4497    /// let r = i.sqrt_rem_ref();
4498    /// let (other_sqrt, other_rem) = <(Integer, Integer)>::from(r);
4499    /// assert_eq!(other_sqrt, 10);
4500    /// assert_eq!(other_rem, 4);
4501    /// ```
4502    ///
4503    /// [icv]: crate#incomplete-computation-values
4504    #[inline]
4505    pub fn sqrt_rem_ref(&self) -> SqrtRemIncomplete<'_> {
4506        SqrtRemIncomplete { ref_self: self }
4507    }
4508
4509    /// Determines wheter a number is prime.
4510    ///
4511    /// This function uses some trial divisions, a Baille-PSW probable prime
4512    /// test, then `reps`&nbsp;&minus;&nbsp;24 Miller-Rabin probabilistic
4513    /// primality tests.
4514    ///
4515    /// # Examples
4516    ///
4517    /// ```rust
4518    /// use rug::integer::IsPrime;
4519    /// use rug::Integer;
4520    /// let no = Integer::from(163 * 4003);
4521    /// assert_eq!(no.is_probably_prime(30), IsPrime::No);
4522    /// let yes = Integer::from(817_504_243);
4523    /// assert_eq!(yes.is_probably_prime(30), IsPrime::Yes);
4524    /// // 16_412_292_043_871_650_369 is actually a prime.
4525    /// let probably = Integer::from(16_412_292_043_871_650_369_u64);
4526    /// assert_eq!(probably.is_probably_prime(30), IsPrime::Probably);
4527    /// ```
4528    #[inline]
4529    pub fn is_probably_prime(&self, reps: u32) -> IsPrime {
4530        match xmpz::probab_prime_p(self, reps.strict_cast()) {
4531            0 => IsPrime::No,
4532            1 => IsPrime::Probably,
4533            2 => IsPrime::Yes,
4534            _ => unreachable!(),
4535        }
4536    }
4537
4538    /// Identifies primes using a probabilistic algorithm; the chance of a
4539    /// composite passing will be extremely small.
4540    ///
4541    /// # Examples
4542    ///
4543    /// ```rust
4544    /// use rug::Integer;
4545    /// let i = Integer::from(800_000_000);
4546    /// let prime = i.next_prime();
4547    /// assert_eq!(prime, 800_000_011);
4548    /// ```
4549    #[inline]
4550    #[must_use]
4551    pub fn next_prime(mut self) -> Self {
4552        self.next_prime_mut();
4553        self
4554    }
4555
4556    /// Identifies primes using a probabilistic algorithm; the chance of a
4557    /// composite passing will be extremely small.
4558    ///
4559    /// # Examples
4560    ///
4561    /// ```rust
4562    /// use rug::Integer;
4563    /// let mut i = Integer::from(800_000_000);
4564    /// i.next_prime_mut();
4565    /// assert_eq!(i, 800_000_011);
4566    /// ```
4567    #[inline]
4568    pub fn next_prime_mut(&mut self) {
4569        xmpz::nextprime(self, ());
4570    }
4571
4572    /// Identifies primes using a probabilistic algorithm; the chance of a
4573    /// composite passing will be extremely small.
4574    ///
4575    /// The following are implemented with the returned [incomplete-computation
4576    /// value][icv] as `Src`:
4577    ///   * <code>[Assign]\<Src> for [Integer]</code>
4578    ///   * <code>[From]\<Src> for [Integer]</code>
4579    ///   * <code>[Complete]\<[Completed][Complete::Completed] = [Integer]> for Src</code>
4580    ///
4581    /// # Examples
4582    ///
4583    /// ```rust
4584    /// use rug::Integer;
4585    /// let i = Integer::from(800_000_000);
4586    /// let r = i.next_prime_ref();
4587    /// let prime = Integer::from(r);
4588    /// assert_eq!(prime, 800_000_011);
4589    /// ```
4590    ///
4591    /// [icv]: crate#incomplete-computation-values
4592    #[inline]
4593    pub fn next_prime_ref(&self) -> NextPrimeIncomplete<'_> {
4594        NextPrimeIncomplete { ref_self: self }
4595    }
4596
4597    /// Identifies previous prime number using a probabilistic algorithm; the
4598    /// chance of a composite passing will be extremely small.
4599    ///
4600    /// # Examples
4601    ///
4602    /// ```rust
4603    /// use rug::Integer;
4604    /// let i = Integer::from(800_000_000);
4605    /// let prime = i.prev_prime();
4606    /// assert_eq!(prime, 799_999_999);
4607    /// ```
4608    #[inline]
4609    #[must_use]
4610    pub fn prev_prime(mut self) -> Self {
4611        self.prev_prime_mut();
4612        self
4613    }
4614
4615    /// Identifies previous prime number using a probabilistic algorithm; the
4616    /// chance of a composite passing will be extremely small.
4617    ///
4618    /// # Examples
4619    ///
4620    /// ```rust
4621    /// use rug::Integer;
4622    /// let mut i = Integer::from(800_000_000);
4623    /// i.prev_prime_mut();
4624    /// assert_eq!(i, 799_999_999);
4625    /// ```
4626    #[inline]
4627    pub fn prev_prime_mut(&mut self) {
4628        xmpz::prevprime(self, ());
4629    }
4630
4631    /// Identifies previous prime number using a probabilistic algorithm; the
4632    /// chance of a composite passing will be extremely small.
4633    ///
4634    /// The following are implemented with the returned [incomplete-computation
4635    /// value][icv] as `Src`:
4636    ///   * <code>[Assign]\<Src> for [Integer]</code>
4637    ///   * <code>[From]\<Src> for [Integer]</code>
4638    ///   * <code>[Complete]\<[Completed][Complete::Completed] = [Integer]> for Src</code>
4639    ///
4640    /// # Examples
4641    ///
4642    /// ```rust
4643    /// use rug::Integer;
4644    /// let i = Integer::from(800_000_000);
4645    /// let r = i.prev_prime_ref();
4646    /// let prime = Integer::from(r);
4647    /// assert_eq!(prime, 799_999_999);
4648    /// ```
4649    ///
4650    /// [icv]: crate#incomplete-computation-values
4651    #[inline]
4652    pub fn prev_prime_ref(&self) -> PrevPrimeIncomplete<'_> {
4653        PrevPrimeIncomplete { ref_self: self }
4654    }
4655
4656    /// Finds the greatest common divisor.
4657    ///
4658    /// The result is always positive except when both inputs are zero.
4659    ///
4660    /// # Examples
4661    ///
4662    /// ```rust
4663    /// use rug::{Assign, Integer};
4664    /// let a = Integer::new();
4665    /// let mut b = Integer::new();
4666    /// // gcd of 0, 0 is 0
4667    /// let gcd1 = a.gcd(&b);
4668    /// assert_eq!(gcd1, 0);
4669    /// b.assign(10);
4670    /// // gcd of 0, 10 is 10
4671    /// let gcd2 = gcd1.gcd(&b);
4672    /// assert_eq!(gcd2, 10);
4673    /// b.assign(25);
4674    /// // gcd of 10, 25 is 5
4675    /// let gcd3 = gcd2.gcd(&b);
4676    /// assert_eq!(gcd3, 5);
4677    /// ```
4678    #[inline]
4679    #[must_use]
4680    pub fn gcd(mut self, other: &Self) -> Self {
4681        self.gcd_mut(other);
4682        self
4683    }
4684
4685    /// Finds the greatest common divisor.
4686    ///
4687    /// The result is always positive except when both inputs are zero.
4688    ///
4689    /// # Examples
4690    ///
4691    /// ```rust
4692    /// use rug::{Assign, Integer};
4693    /// let mut a = Integer::new();
4694    /// let mut b = Integer::new();
4695    /// // gcd of 0, 0 is 0
4696    /// a.gcd_mut(&b);
4697    /// assert_eq!(a, 0);
4698    /// b.assign(10);
4699    /// // gcd of 0, 10 is 10
4700    /// a.gcd_mut(&b);
4701    /// assert_eq!(a, 10);
4702    /// b.assign(25);
4703    /// // gcd of 10, 25 is 5
4704    /// a.gcd_mut(&b);
4705    /// assert_eq!(a, 5);
4706    /// ```
4707    #[inline]
4708    pub fn gcd_mut(&mut self, other: &Self) {
4709        xmpz::gcd(self, (), other);
4710    }
4711
4712    /// Finds the greatest common divisor.
4713    ///
4714    /// The result is always positive except when both inputs are zero.
4715    ///
4716    /// The following are implemented with the returned [incomplete-computation
4717    /// value][icv] as `Src`:
4718    ///   * <code>[Assign]\<Src> for [Integer]</code>
4719    ///   * <code>[From]\<Src> for [Integer]</code>
4720    ///   * <code>[Complete]\<[Completed][Complete::Completed] = [Integer]> for Src</code>
4721    ///
4722    /// # Examples
4723    ///
4724    /// ```rust
4725    /// use rug::Integer;
4726    /// let a = Integer::from(100);
4727    /// let b = Integer::from(125);
4728    /// let r = a.gcd_ref(&b);
4729    /// // gcd of 100, 125 is 25
4730    /// assert_eq!(Integer::from(r), 25);
4731    /// ```
4732    ///
4733    /// [icv]: crate#incomplete-computation-values
4734    #[inline]
4735    pub fn gcd_ref<'a>(&'a self, other: &'a Self) -> GcdIncomplete<'a> {
4736        GcdIncomplete {
4737            ref_self: self,
4738            other,
4739        }
4740    }
4741
4742    /// Finds the greatest common divisor.
4743    ///
4744    /// The result is always positive except when both inputs are zero.
4745    ///
4746    /// # Examples
4747    ///
4748    /// ```rust
4749    /// use rug::Integer;
4750    /// let i = Integer::new();
4751    /// // gcd of 0, 0 is 0
4752    /// let gcd1 = i.gcd_u(0);
4753    /// assert_eq!(gcd1, 0);
4754    /// // gcd of 0, 10 is 10
4755    /// let gcd2 = gcd1.gcd_u(10);
4756    /// assert_eq!(gcd2, 10);
4757    /// // gcd of 10, 25 is 5
4758    /// let gcd3 = gcd2.gcd_u(25);
4759    /// assert_eq!(gcd3, 5);
4760    /// ```
4761    #[inline]
4762    #[must_use]
4763    pub fn gcd_u(mut self, other: u32) -> Self {
4764        self.gcd_u_mut(other);
4765        self
4766    }
4767
4768    /// Finds the greatest common divisor.
4769    ///
4770    /// The result is always positive except when both inputs are zero.
4771    ///
4772    /// # Examples
4773    ///
4774    /// ```rust
4775    /// use rug::Integer;
4776    /// let mut i = Integer::new();
4777    /// // gcd of 0, 0 is 0
4778    /// i.gcd_u_mut(0);
4779    /// assert_eq!(i, 0);
4780    /// // gcd of 0, 10 is 10
4781    /// i.gcd_u_mut(10);
4782    /// assert_eq!(i, 10);
4783    /// // gcd of 10, 25 is 5
4784    /// i.gcd_u_mut(25);
4785    /// assert_eq!(i, 5);
4786    /// ```
4787    #[inline]
4788    pub fn gcd_u_mut(&mut self, other: u32) {
4789        xmpz::gcd_ui(self, (), other.into());
4790    }
4791
4792    /// Finds the greatest common divisor.
4793    ///
4794    /// The result is always positive except when both inputs are zero.
4795    ///
4796    /// The following are implemented with the returned [incomplete-computation
4797    /// value][icv] as `Src`:
4798    ///   * <code>[Assign]\<Src> for [Integer]</code>
4799    ///   * <code>[From]\<Src> for [Integer]</code>
4800    ///   * <code>[From]\<Src> for [Option]\<[u32]></code>
4801    ///   * <code>[Complete]\<[Completed][Complete::Completed] = [Integer]> for Src</code>
4802    ///
4803    /// The implementation of <code>[From]\<Src> for [Option]\<[u32]></code> is
4804    /// useful to obtain the result as a [`u32`] if it fits. If
4805    /// `other`&nbsp;>&nbsp;0 , the result always fits. If the result does not
4806    /// fit, it is equal to the absolute value of `self`.
4807    ///
4808    /// # Examples
4809    ///
4810    /// ```rust
4811    /// use rug::Integer;
4812    /// let i = Integer::from(100);
4813    /// let r = i.gcd_u_ref(125);
4814    /// // gcd of 100, 125 is 25
4815    /// assert_eq!(Integer::from(r), 25);
4816    /// let r = i.gcd_u_ref(125);
4817    /// assert_eq!(Option::<u32>::from(r), Some(25));
4818    /// ```
4819    ///
4820    /// [icv]: crate#incomplete-computation-values
4821    #[inline]
4822    pub fn gcd_u_ref(&self, other: u32) -> GcdUIncomplete<'_> {
4823        let other = other.into();
4824        GcdUIncomplete {
4825            ref_self: self,
4826            other,
4827        }
4828    }
4829
4830    /// Finds the greatest common divisor (GCD) of the two inputs (`self` and
4831    /// `other`), and two coefficients to obtain the GCD from the two inputs.
4832    ///
4833    /// The GCD is always positive except when both inputs are zero. If the
4834    /// inputs are <i>a</i> and <i>b</i>, then the GCD is <i>g</i> and the
4835    /// coefficients are <i>s</i> and <i>t</i> such that
4836    ///
4837    /// <i>a</i> × <i>s</i> + <i>b</i> × <i>t</i> = <i>g</i>
4838    ///
4839    /// The values <i>s</i> and <i>t</i> are chosen such that normally,
4840    /// |<i>s</i>|&nbsp;<&nbsp;|<i>b</i>|&nbsp;/&nbsp;(2<i>g</i>) and
4841    /// |<i>t</i>|&nbsp;<&nbsp;|<i>a</i>|&nbsp;/&nbsp;(2<i>g</i>), and these
4842    /// relations define <i>s</i> and <i>t</i> uniquely. There are a few
4843    /// exceptional cases:
4844    ///
4845    ///   * If |<i>a</i>|&nbsp;=&nbsp;|<i>b</i>|, then <i>s</i>&nbsp;=&nbsp;0,
4846    ///     <i>t</i>&nbsp;=&nbsp;sgn(<i>b</i>).
4847    ///   * Otherwise, if <i>b</i>&nbsp;=&nbsp;0 or
4848    ///     |<i>b</i>|&nbsp;=&nbsp;2<i>g</i>, then
4849    ///     <i>s</i>&nbsp;=&nbsp;sgn(<i>a</i>), and if <i>a</i>&nbsp;=&nbsp;0 or
4850    ///     |<i>a</i>|&nbsp;=&nbsp;2<i>g</i>, then
4851    ///     <i>t</i>&nbsp;=&nbsp;sgn(<i>b</i>).
4852    ///
4853    /// The initial value of `rop` is ignored.
4854    ///
4855    /// # Examples
4856    ///
4857    /// ```rust
4858    /// use rug::Integer;
4859    /// let a = Integer::from(4);
4860    /// let b = Integer::from(6);
4861    /// let (g, s, t) = a.extended_gcd(b, Integer::new());
4862    /// assert_eq!(g, 2);
4863    /// assert_eq!(s, -1);
4864    /// assert_eq!(t, 1);
4865    /// ```
4866    #[inline]
4867    pub fn extended_gcd(mut self, mut other: Self, mut rop: Self) -> (Self, Self, Self) {
4868        self.extended_gcd_mut(&mut other, &mut rop);
4869        (self, other, rop)
4870    }
4871
4872    /// Finds the greatest common divisor (GCD) of the two inputs (`self` and
4873    /// `other`), and two coefficients to obtain the GCD from the two inputs.
4874    ///
4875    /// The GCD is stored in `self`, and the two coefficients are stored in
4876    /// `other` and `rop`.
4877    ///
4878    /// The GCD is always positive except when both inputs are zero. If the
4879    /// inputs are <i>a</i> and <i>b</i>, then the GCD is <i>g</i> and the
4880    /// coefficients are <i>s</i> and <i>t</i> such that
4881    ///
4882    /// <i>a</i> × <i>s</i> + <i>b</i> × <i>t</i> = <i>g</i>
4883    ///
4884    /// The values <i>s</i> and <i>t</i> are chosen such that normally,
4885    /// |<i>s</i>|&nbsp;<&nbsp;|<i>b</i>|&nbsp;/&nbsp;(2<i>g</i>) and
4886    /// |<i>t</i>|&nbsp;<&nbsp;|<i>a</i>|&nbsp;/&nbsp;(2<i>g</i>), and these
4887    /// relations define <i>s</i> and <i>t</i> uniquely. There are a few
4888    /// exceptional cases:
4889    ///
4890    ///   * If |<i>a</i>|&nbsp;=&nbsp;|<i>b</i>|, then <i>s</i>&nbsp;=&nbsp;0,
4891    ///     <i>t</i>&nbsp;=&nbsp;sgn(<i>b</i>).
4892    ///   * Otherwise, if <i>b</i>&nbsp;=&nbsp;0 or
4893    ///     |<i>b</i>|&nbsp;=&nbsp;2<i>g</i>, then
4894    ///     <i>s</i>&nbsp;=&nbsp;sgn(<i>a</i>), and if <i>a</i>&nbsp;=&nbsp;0 or
4895    ///     |<i>a</i>|&nbsp;=&nbsp;2<i>g</i>, then
4896    ///     <i>t</i>&nbsp;=&nbsp;sgn(<i>b</i>).
4897    ///
4898    /// The initial value of `rop` is ignored.
4899    ///
4900    /// # Examples
4901    ///
4902    /// ```rust
4903    /// use rug::Integer;
4904    /// let mut a_g = Integer::from(4);
4905    /// let mut b_s = Integer::from(6);
4906    /// let mut t = Integer::new();
4907    /// a_g.extended_gcd_mut(&mut b_s, &mut t);
4908    /// assert_eq!(a_g, 2);
4909    /// assert_eq!(b_s, -1);
4910    /// assert_eq!(t, 1);
4911    /// ```
4912    #[inline]
4913    pub fn extended_gcd_mut(&mut self, other: &mut Self, rop: &mut Self) {
4914        xmpz::gcdext(self, other, Some(rop), (), ());
4915    }
4916
4917    /// Finds the greatest common divisor (GCD) of the two inputs (`self` and
4918    /// `other`), and two coefficients to obtain the GCD from the two inputs.
4919    ///
4920    /// The following are implemented with the returned [incomplete-computation
4921    /// value][icv] as `Src`:
4922    ///   * <code>[Assign]\<Src> for [(][tuple][Integer][], [Integer], [Integer][][)][tuple]</code>
4923    ///   * <code>[Assign]\<Src> for [(][tuple]\&mut [Integer], \&mut [Integer], \&mut [Integer][][)][tuple]</code>
4924    ///   * <code>[From]\<Src> for [(][tuple][Integer][], [Integer], [Integer][][)][tuple]</code>
4925    ///   * <code>[Complete]\<[Completed][Complete::Completed] = [(][tuple][Integer][], [Integer], [Integer][][)][tuple]> for Src</code>
4926    ///
4927    /// In the case that only one of the two coefficients is required, the
4928    /// following are also implemented:
4929    ///   * <code>[Assign]\<Src> for [(][tuple][Integer][], [Integer][][)][tuple]</code>
4930    ///   * <code>[Assign]\<Src> for [(][tuple]\&mut [Integer], \&mut [Integer][][)][tuple]</code>
4931    ///   * <code>[From]\<Src> for [(][tuple][Integer][], [Integer][][)][tuple]</code>
4932    ///
4933    /// The GCD is always positive except when both inputs are zero. If the
4934    /// inputs are <i>a</i> and <i>b</i>, then the GCD is <i>g</i> and the
4935    /// coefficients are <i>s</i> and <i>t</i> such that
4936    ///
4937    /// <i>a</i> × <i>s</i> + <i>b</i> × <i>t</i> = <i>g</i>
4938    ///
4939    /// The values <i>s</i> and <i>t</i> are chosen such that normally,
4940    /// |<i>s</i>|&nbsp;<&nbsp;|<i>b</i>|&nbsp;/&nbsp;(2<i>g</i>) and
4941    /// |<i>t</i>|&nbsp;<&nbsp;|<i>a</i>|&nbsp;/&nbsp;(2<i>g</i>), and these
4942    /// relations define <i>s</i> and <i>t</i> uniquely. There are a few
4943    /// exceptional cases:
4944    ///
4945    ///   * If |<i>a</i>|&nbsp;=&nbsp;|<i>b</i>|, then <i>s</i>&nbsp;=&nbsp;0,
4946    ///     <i>t</i>&nbsp;=&nbsp;sgn(<i>b</i>).
4947    ///   * Otherwise, if <i>b</i>&nbsp;=&nbsp;0 or
4948    ///     |<i>b</i>|&nbsp;=&nbsp;2<i>g</i>, then
4949    ///     <i>s</i>&nbsp;=&nbsp;sgn(<i>a</i>), and if <i>a</i>&nbsp;=&nbsp;0 or
4950    ///     |<i>a</i>|&nbsp;=&nbsp;2<i>g</i>, then
4951    ///     <i>t</i>&nbsp;=&nbsp;sgn(<i>b</i>).
4952    ///
4953    /// # Examples
4954    ///
4955    /// ```rust
4956    /// use rug::{Assign, Integer};
4957    /// let a = Integer::from(4);
4958    /// let b = Integer::from(6);
4959    /// let r = a.extended_gcd_ref(&b);
4960    /// let mut g = Integer::new();
4961    /// let mut s = Integer::new();
4962    /// let mut t = Integer::new();
4963    /// (&mut g, &mut s, &mut t).assign(r);
4964    /// assert_eq!(a, 4);
4965    /// assert_eq!(b, 6);
4966    /// assert_eq!(g, 2);
4967    /// assert_eq!(s, -1);
4968    /// assert_eq!(t, 1);
4969    /// ```
4970    ///
4971    /// In the case that only one of the two coefficients is required, this can
4972    /// be achieved as follows:
4973    ///
4974    /// ```rust
4975    /// use rug::{Assign, Integer};
4976    /// let a = Integer::from(4);
4977    /// let b = Integer::from(6);
4978    ///
4979    /// // no t required
4980    /// let (mut g1, mut s1) = (Integer::new(), Integer::new());
4981    /// (&mut g1, &mut s1).assign(a.extended_gcd_ref(&b));
4982    /// assert_eq!(g1, 2);
4983    /// assert_eq!(s1, -1);
4984    ///
4985    /// // no s required
4986    /// let (mut g2, mut t2) = (Integer::new(), Integer::new());
4987    /// (&mut g2, &mut t2).assign(b.extended_gcd_ref(&a));
4988    /// assert_eq!(g2, 2);
4989    /// assert_eq!(t2, 1);
4990    /// ```
4991    ///
4992    /// [icv]: crate#incomplete-computation-values
4993    #[inline]
4994    pub fn extended_gcd_ref<'a>(&'a self, other: &'a Self) -> GcdExtIncomplete<'a> {
4995        GcdExtIncomplete {
4996            ref_self: self,
4997            other,
4998        }
4999    }
5000
5001    /// Finds the least common multiple.
5002    ///
5003    /// The result is always positive except when one or both inputs are zero.
5004    ///
5005    /// # Examples
5006    ///
5007    /// ```rust
5008    /// use rug::{Assign, Integer};
5009    /// let a = Integer::from(10);
5010    /// let mut b = Integer::from(25);
5011    /// // lcm of 10, 25 is 50
5012    /// let lcm1 = a.lcm(&b);
5013    /// assert_eq!(lcm1, 50);
5014    /// b.assign(0);
5015    /// // lcm of 50, 0 is 0
5016    /// let lcm2 = lcm1.lcm(&b);
5017    /// assert_eq!(lcm2, 0);
5018    /// ```
5019    #[inline]
5020    #[must_use]
5021    pub fn lcm(mut self, other: &Self) -> Self {
5022        self.lcm_mut(other);
5023        self
5024    }
5025
5026    /// Finds the least common multiple.
5027    ///
5028    /// The result is always positive except when one or both inputs are zero.
5029    ///
5030    /// # Examples
5031    ///
5032    /// ```rust
5033    /// use rug::{Assign, Integer};
5034    /// let mut a = Integer::from(10);
5035    /// let mut b = Integer::from(25);
5036    /// // lcm of 10, 25 is 50
5037    /// a.lcm_mut(&b);
5038    /// assert_eq!(a, 50);
5039    /// b.assign(0);
5040    /// // lcm of 50, 0 is 0
5041    /// a.lcm_mut(&b);
5042    /// assert_eq!(a, 0);
5043    /// ```
5044    #[inline]
5045    pub fn lcm_mut(&mut self, other: &Self) {
5046        xmpz::lcm(self, (), other);
5047    }
5048
5049    /// Finds the least common multiple.
5050    ///
5051    /// The result is always positive except when one or both inputs are zero.
5052    ///
5053    /// The following are implemented with the returned [incomplete-computation
5054    /// value][icv] as `Src`:
5055    ///   * <code>[Assign]\<Src> for [Integer]</code>
5056    ///   * <code>[From]\<Src> for [Integer]</code>
5057    ///   * <code>[Complete]\<[Completed][Complete::Completed] = [Integer]> for Src</code>
5058    ///
5059    /// # Examples
5060    ///
5061    /// ```rust
5062    /// use rug::Integer;
5063    /// let a = Integer::from(100);
5064    /// let b = Integer::from(125);
5065    /// let r = a.lcm_ref(&b);
5066    /// // lcm of 100, 125 is 500
5067    /// assert_eq!(Integer::from(r), 500);
5068    /// ```
5069    ///
5070    /// [icv]: crate#incomplete-computation-values
5071    #[inline]
5072    pub fn lcm_ref<'a>(&'a self, other: &'a Self) -> LcmIncomplete<'a> {
5073        LcmIncomplete {
5074            ref_self: self,
5075            other,
5076        }
5077    }
5078
5079    /// Finds the least common multiple.
5080    ///
5081    /// The result is always positive except when one or both inputs are zero.
5082    ///
5083    /// # Examples
5084    ///
5085    /// ```rust
5086    /// use rug::Integer;
5087    /// let i = Integer::from(10);
5088    /// // lcm of 10, 25 is 50
5089    /// let lcm1 = i.lcm_u(25);
5090    /// assert_eq!(lcm1, 50);
5091    /// // lcm of 50, 0 is 0
5092    /// let lcm2 = lcm1.lcm_u(0);
5093    /// assert_eq!(lcm2, 0);
5094    /// ```
5095    #[inline]
5096    #[must_use]
5097    pub fn lcm_u(mut self, other: u32) -> Self {
5098        self.lcm_u_mut(other);
5099        self
5100    }
5101
5102    /// Finds the least common multiple.
5103    ///
5104    /// The result is always positive except when one or both inputs are zero.
5105    ///
5106    /// # Examples
5107    ///
5108    /// ```rust
5109    /// use rug::Integer;
5110    /// let mut i = Integer::from(10);
5111    /// // lcm of 10, 25 is 50
5112    /// i.lcm_u_mut(25);
5113    /// assert_eq!(i, 50);
5114    /// // lcm of 50, 0 is 0
5115    /// i.lcm_u_mut(0);
5116    /// assert_eq!(i, 0);
5117    /// ```
5118    #[inline]
5119    pub fn lcm_u_mut(&mut self, other: u32) {
5120        xmpz::lcm_ui(self, (), other.into());
5121    }
5122
5123    /// Finds the least common multiple.
5124    ///
5125    /// The result is always positive except when one or both inputs are zero.
5126    ///
5127    /// The following are implemented with the returned [incomplete-computation
5128    /// value][icv] as `Src`:
5129    ///   * <code>[Assign]\<Src> for [Integer]</code>
5130    ///   * <code>[From]\<Src> for [Integer]</code>
5131    ///   * <code>[Complete]\<[Completed][Complete::Completed] = [Integer]> for Src</code>
5132    ///
5133    /// # Examples
5134    ///
5135    /// ```rust
5136    /// use rug::Integer;
5137    /// let i = Integer::from(100);
5138    /// let r = i.lcm_u_ref(125);
5139    /// // lcm of 100, 125 is 500
5140    /// assert_eq!(Integer::from(r), 500);
5141    /// ```
5142    ///
5143    /// [icv]: crate#incomplete-computation-values
5144    #[inline]
5145    pub fn lcm_u_ref(&self, other: u32) -> LcmUIncomplete<'_> {
5146        let other = other.into();
5147        LcmUIncomplete {
5148            ref_self: self,
5149            other,
5150        }
5151    }
5152
5153    /// Calculates the Jacobi symbol (`self`/<i>n</i>).
5154    ///
5155    /// # Examples
5156    ///
5157    /// ```rust
5158    /// use rug::{Assign, Integer};
5159    /// let m = Integer::from(10);
5160    /// let mut n = Integer::from(13);
5161    /// assert_eq!(m.jacobi(&n), 1);
5162    /// n.assign(15);
5163    /// assert_eq!(m.jacobi(&n), 0);
5164    /// n.assign(17);
5165    /// assert_eq!(m.jacobi(&n), -1);
5166    /// ```
5167    #[inline]
5168    pub fn jacobi(&self, n: &Self) -> i32 {
5169        xmpz::jacobi(self, n).cast()
5170    }
5171
5172    /// Calculates the Legendre symbol (`self`/<i>p</i>).
5173    ///
5174    /// # Examples
5175    ///
5176    /// ```rust
5177    /// use rug::{Assign, Integer};
5178    /// let a = Integer::from(5);
5179    /// let mut p = Integer::from(7);
5180    /// assert_eq!(a.legendre(&p), -1);
5181    /// p.assign(11);
5182    /// assert_eq!(a.legendre(&p), 1);
5183    /// ```
5184    #[inline]
5185    pub fn legendre(&self, p: &Self) -> i32 {
5186        xmpz::legendre(self, p).cast()
5187    }
5188
5189    /// Calculates the Jacobi symbol (`self`/<i>n</i>) with the Kronecker
5190    /// extension.
5191    ///
5192    /// # Examples
5193    ///
5194    /// ```rust
5195    /// use rug::{Assign, Integer};
5196    /// let k = Integer::from(3);
5197    /// let mut n = Integer::from(16);
5198    /// assert_eq!(k.kronecker(&n), 1);
5199    /// n.assign(17);
5200    /// assert_eq!(k.kronecker(&n), -1);
5201    /// n.assign(18);
5202    /// assert_eq!(k.kronecker(&n), 0);
5203    /// ```
5204    #[inline]
5205    pub fn kronecker(&self, n: &Self) -> i32 {
5206        xmpz::kronecker(self, n).cast()
5207    }
5208
5209    /// Removes all occurrences of `factor`, and returns the number of
5210    /// occurrences removed.
5211    ///
5212    /// # Examples
5213    ///
5214    /// ```rust
5215    /// use rug::Integer;
5216    /// let mut i = Integer::from(Integer::u_pow_u(13, 50));
5217    /// i *= 1000;
5218    /// let (remove, count) = i.remove_factor(&Integer::from(13));
5219    /// assert_eq!(remove, 1000);
5220    /// assert_eq!(count, 50);
5221    /// ```
5222    #[inline]
5223    pub fn remove_factor(mut self, factor: &Self) -> (Self, u32) {
5224        let count = self.remove_factor_mut(factor);
5225        (self, count)
5226    }
5227
5228    /// Removes all occurrences of `factor`, and returns the number of
5229    /// occurrences removed.
5230    ///
5231    /// # Examples
5232    ///
5233    /// ```rust
5234    /// use rug::Integer;
5235    /// let mut i = Integer::from(Integer::u_pow_u(13, 50));
5236    /// i *= 1000;
5237    /// let count = i.remove_factor_mut(&Integer::from(13));
5238    /// assert_eq!(i, 1000);
5239    /// assert_eq!(count, 50);
5240    /// ```
5241    #[inline]
5242    pub fn remove_factor_mut(&mut self, factor: &Self) -> u32 {
5243        xmpz::remove(self, (), factor).strict_cast()
5244    }
5245
5246    /// Removes all occurrences of `factor`, and counts the number of
5247    /// occurrences removed.
5248    ///
5249    /// The following are implemented with the returned [incomplete-computation
5250    /// value][icv] as `Src`:
5251    ///   * <code>[Assign]\<Src> for [(][tuple][Integer][], [u32][][)][tuple]</code>
5252    ///   * <code>[Assign]\<Src> for [(][tuple]\&mut [Integer], \&mut [u32][][)][tuple]</code>
5253    ///   * <code>[From]\<Src> for [(][tuple][Integer][], [u32][][)][tuple]</code>
5254    ///   * <code>[Complete]\<[Completed][Complete::Completed] = [(][tuple][Integer][], [u32][][)][tuple]> for Src</code>
5255    ///
5256    /// # Examples
5257    ///
5258    /// ```rust
5259    /// use rug::{Assign, Integer};
5260    /// let mut i = Integer::from(Integer::u_pow_u(13, 50));
5261    /// i *= 1000;
5262    /// let factor = Integer::from(13);
5263    /// let r = i.remove_factor_ref(&factor);
5264    /// let (mut j, mut count) = (Integer::new(), 0);
5265    /// (&mut j, &mut count).assign(r);
5266    /// assert_eq!(count, 50);
5267    /// assert_eq!(j, 1000);
5268    /// ```
5269    ///
5270    /// [icv]: crate#incomplete-computation-values
5271    #[inline]
5272    pub fn remove_factor_ref<'a>(&'a self, factor: &'a Self) -> RemoveFactorIncomplete<'a> {
5273        RemoveFactorIncomplete {
5274            ref_self: self,
5275            factor,
5276        }
5277    }
5278
5279    /// Computes the factorial of <i>n</i>.
5280    ///
5281    /// The following are implemented with the returned [incomplete-computation
5282    /// value][icv] as `Src`:
5283    ///   * <code>[Assign]\<Src> for [Integer]</code>
5284    ///   * <code>[From]\<Src> for [Integer]</code>
5285    ///   * <code>[Complete]\<[Completed][Complete::Completed] = [Integer]> for Src</code>
5286    ///
5287    /// # Examples
5288    ///
5289    /// ```rust
5290    /// use rug::{Complete, Integer};
5291    /// // 10 × 9 × 8 × 7 × 6 × 5 × 4 × 3 × 2 × 1
5292    /// assert_eq!(Integer::factorial(10).complete(), 3628800);
5293    /// ```
5294    ///
5295    /// [icv]: crate#incomplete-computation-values
5296    #[inline]
5297    pub fn factorial(n: u32) -> FactorialIncomplete {
5298        let n = n.into();
5299        FactorialIncomplete { n }
5300    }
5301
5302    /// Computes the double factorial of <i>n</i>.
5303    ///
5304    /// The following are implemented with the returned [incomplete-computation
5305    /// value][icv] as `Src`:
5306    ///   * <code>[Assign]\<Src> for [Integer]</code>
5307    ///   * <code>[From]\<Src> for [Integer]</code>
5308    ///   * <code>[Complete]\<[Completed][Complete::Completed] = [Integer]> for Src</code>
5309    ///
5310    /// # Examples
5311    ///
5312    /// ```rust
5313    /// use rug::{Complete, Integer};
5314    /// // 10 × 8 × 6 × 4 × 2
5315    /// assert_eq!(Integer::factorial_2(10).complete(), 3840);
5316    /// ```
5317    ///
5318    /// [icv]: crate#incomplete-computation-values
5319    #[inline]
5320    pub fn factorial_2(n: u32) -> Factorial2Incomplete {
5321        let n = n.into();
5322        Factorial2Incomplete { n }
5323    }
5324
5325    /// Computes the <i>m</i>-multi factorial of <i>n</i>.
5326    ///
5327    /// The following are implemented with the returned [incomplete-computation
5328    /// value][icv] as `Src`:
5329    ///   * <code>[Assign]\<Src> for [Integer]</code>
5330    ///   * <code>[From]\<Src> for [Integer]</code>
5331    ///   * <code>[Complete]\<[Completed][Complete::Completed] = [Integer]> for Src</code>
5332    ///
5333    /// # Examples
5334    ///
5335    /// ```rust
5336    /// use rug::{Complete, Integer};
5337    /// // 10 × 7 × 4 × 1
5338    /// assert_eq!(Integer::factorial_m(10, 3).complete(), 280);
5339    /// ```
5340    ///
5341    /// [icv]: crate#incomplete-computation-values
5342    #[inline]
5343    pub fn factorial_m(n: u32, m: u32) -> FactorialMIncomplete {
5344        let n = n.into();
5345        let m = m.into();
5346        FactorialMIncomplete { n, m }
5347    }
5348
5349    /// Computes the primorial of <i>n</i>.
5350    ///
5351    /// The following are implemented with the returned [incomplete-computation
5352    /// value][icv] as `Src`:
5353    ///   * <code>[Assign]\<Src> for [Integer]</code>
5354    ///   * <code>[From]\<Src> for [Integer]</code>
5355    ///   * <code>[Complete]\<[Completed][Complete::Completed] = [Integer]> for Src</code>
5356    ///
5357    /// # Examples
5358    ///
5359    /// ```rust
5360    /// use rug::{Complete, Integer};
5361    /// // 7 × 5 × 3 × 2
5362    /// assert_eq!(Integer::primorial(10).complete(), 210);
5363    /// ```
5364    ///
5365    /// [icv]: crate#incomplete-computation-values
5366    #[inline]
5367    pub fn primorial(n: u32) -> PrimorialIncomplete {
5368        let n = n.into();
5369        PrimorialIncomplete { n }
5370    }
5371
5372    /// Computes the binomial coefficient over <i>k</i>.
5373    ///
5374    /// # Examples
5375    ///
5376    /// ```rust
5377    /// use rug::Integer;
5378    /// // 7 choose 2 is 21
5379    /// let i = Integer::from(7);
5380    /// let bin = i.binomial(2);
5381    /// assert_eq!(bin, 21);
5382    /// ```
5383    #[inline]
5384    #[must_use]
5385    pub fn binomial(mut self, k: u32) -> Self {
5386        self.binomial_mut(k);
5387        self
5388    }
5389
5390    /// Computes the binomial coefficient over <i>k</i>.
5391    ///
5392    /// # Examples
5393    ///
5394    /// ```rust
5395    /// use rug::Integer;
5396    /// // 7 choose 2 is 21
5397    /// let mut i = Integer::from(7);
5398    /// i.binomial_mut(2);
5399    /// assert_eq!(i, 21);
5400    /// ```
5401    #[inline]
5402    pub fn binomial_mut(&mut self, k: u32) {
5403        xmpz::bin_ui(self, (), k.into());
5404    }
5405
5406    /// Computes the binomial coefficient over <i>k</i>.
5407    ///
5408    /// The following are implemented with the returned [incomplete-computation
5409    /// value][icv] as `Src`:
5410    ///   * <code>[Assign]\<Src> for [Integer]</code>
5411    ///   * <code>[From]\<Src> for [Integer]</code>
5412    ///   * <code>[Complete]\<[Completed][Complete::Completed] = [Integer]> for Src</code>
5413    ///
5414    /// # Examples
5415    ///
5416    /// ```rust
5417    /// use rug::{Complete, Integer};
5418    /// // 7 choose 2 is 21
5419    /// let i = Integer::from(7);
5420    /// assert_eq!(i.binomial_ref(2).complete(), 21);
5421    /// ```
5422    ///
5423    /// [icv]: crate#incomplete-computation-values
5424    #[inline]
5425    pub fn binomial_ref(&self, k: u32) -> BinomialIncomplete<'_> {
5426        let k = k.into();
5427        BinomialIncomplete { ref_self: self, k }
5428    }
5429
5430    /// Computes the binomial coefficient <i>n</i> over <i>k</i>.
5431    ///
5432    /// The following are implemented with the returned [incomplete-computation
5433    /// value][icv] as `Src`:
5434    ///   * <code>[Assign]\<Src> for [Integer]</code>
5435    ///   * <code>[From]\<Src> for [Integer]</code>
5436    ///   * <code>[Complete]\<[Completed][Complete::Completed] = [Integer]> for Src</code>
5437    ///
5438    /// # Examples
5439    ///
5440    /// ```rust
5441    /// use rug::Integer;
5442    /// // 7 choose 2 is 21
5443    /// let b = Integer::binomial_u(7, 2);
5444    /// let i = Integer::from(b);
5445    /// assert_eq!(i, 21);
5446    /// ```
5447    ///
5448    /// [icv]: crate#incomplete-computation-values
5449    #[inline]
5450    pub fn binomial_u(n: u32, k: u32) -> BinomialUIncomplete {
5451        let n = n.into();
5452        let k = k.into();
5453        BinomialUIncomplete { n, k }
5454    }
5455
5456    /// Computes the Fibonacci number.
5457    ///
5458    /// The following are implemented with the returned [incomplete-computation
5459    /// value][icv] as `Src`:
5460    ///   * <code>[Assign]\<Src> for [Integer]</code>
5461    ///   * <code>[From]\<Src> for [Integer]</code>
5462    ///   * <code>[Complete]\<[Completed][Complete::Completed] = [Integer]> for Src</code>
5463    ///
5464    /// This function is meant for an isolated number. If a sequence of
5465    /// Fibonacci numbers is required, the first two values of the sequence
5466    /// should be computed with the [`fibonacci_2`][Integer::fibonacci_2]
5467    /// method, then iterations should be used.
5468    ///
5469    /// # Examples
5470    ///
5471    /// ```rust
5472    /// use rug::{Complete, Integer};
5473    /// assert_eq!(Integer::fibonacci(12).complete(), 144);
5474    /// ```
5475    ///
5476    /// [icv]: crate#incomplete-computation-values
5477    #[inline]
5478    pub fn fibonacci(n: u32) -> FibonacciIncomplete {
5479        let n = n.into();
5480        FibonacciIncomplete { n }
5481    }
5482
5483    /// Computes a Fibonacci number, and the previous Fibonacci number.
5484    ///
5485    /// The following are implemented with the returned [incomplete-computation
5486    /// value][icv] as `Src`:
5487    ///   * <code>[Assign]\<Src> for [(][tuple][Integer][], [Integer][][)][tuple]</code>
5488    ///   * <code>[Assign]\<Src> for [(][tuple]\&mut [Integer], \&mut [Integer][][)][tuple]</code>
5489    ///   * <code>[From]\<Src> for [(][tuple][Integer][], [Integer][][)][tuple]</code>
5490    ///   * <code>[Complete]\<[Completed][Complete::Completed] = [(][tuple][Integer][], [Integer][][)][tuple]> for Src</code>
5491    ///
5492    /// This function is meant to calculate isolated numbers. If a sequence of
5493    /// Fibonacci numbers is required, the first two values of the sequence
5494    /// should be computed with this function, then iterations should be used.
5495    ///
5496    /// # Examples
5497    ///
5498    /// ```rust
5499    /// use rug::{Assign, Integer};
5500    /// let f = Integer::fibonacci_2(12);
5501    /// let mut pair = <(Integer, Integer)>::from(f);
5502    /// assert_eq!(pair.0, 144);
5503    /// assert_eq!(pair.1, 89);
5504    /// // Fibonacci number F[-1] is 1
5505    /// pair.assign(Integer::fibonacci_2(0));
5506    /// assert_eq!(pair.0, 0);
5507    /// assert_eq!(pair.1, 1);
5508    /// ```
5509    ///
5510    /// [icv]: crate#incomplete-computation-values
5511    #[inline]
5512    pub fn fibonacci_2(n: u32) -> Fibonacci2Incomplete {
5513        let n = n.into();
5514        Fibonacci2Incomplete { n }
5515    }
5516
5517    /// Computes the Lucas number.
5518    ///
5519    /// The following are implemented with the returned [incomplete-computation
5520    /// value][icv] as `Src`:
5521    ///   * <code>[Assign]\<Src> for [Integer]</code>
5522    ///   * <code>[From]\<Src> for [Integer]</code>
5523    ///   * <code>[Complete]\<[Completed][Complete::Completed] = [Integer]> for Src</code>
5524    ///
5525    /// This function is meant for an isolated number. If a sequence of Lucas
5526    /// numbers is required, the first two values of the sequence should be
5527    /// computed with the [`lucas_2`][Integer::lucas_2] method, then iterations
5528    /// should be used.
5529    ///
5530    /// # Examples
5531    ///
5532    /// ```rust
5533    /// use rug::{Complete, Integer};
5534    /// assert_eq!(Integer::lucas(12).complete(), 322);
5535    /// ```
5536    ///
5537    /// [icv]: crate#incomplete-computation-values
5538    #[inline]
5539    pub fn lucas(n: u32) -> LucasIncomplete {
5540        let n = n.into();
5541        LucasIncomplete { n }
5542    }
5543
5544    /// Computes a Lucas number, and the previous Lucas number.
5545    ///
5546    /// The following are implemented with the returned [incomplete-computation
5547    /// value][icv] as `Src`:
5548    ///   * <code>[Assign]\<Src> for [(][tuple][Integer][], [Integer][][)][tuple]</code>
5549    ///   * <code>[Assign]\<Src> for [(][tuple]\&mut [Integer], \&mut [Integer][][)][tuple]</code>
5550    ///   * <code>[From]\<Src> for [(][tuple][Integer][], [Integer][][)][tuple]</code>
5551    ///   * <code>[Complete]\<[Completed][Complete::Completed] = [(][tuple][Integer][], [Integer][][)][tuple]> for Src</code>
5552    ///
5553    /// This function is meant to calculate isolated numbers. If a sequence of
5554    /// Lucas numbers is required, the first two values of the sequence should
5555    /// be computed with this function, then iterations should be used.
5556    ///
5557    /// # Examples
5558    ///
5559    /// ```rust
5560    /// use rug::{Assign, Integer};
5561    /// let l = Integer::lucas_2(12);
5562    /// let mut pair = <(Integer, Integer)>::from(l);
5563    /// assert_eq!(pair.0, 322);
5564    /// assert_eq!(pair.1, 199);
5565    /// pair.assign(Integer::lucas_2(0));
5566    /// assert_eq!(pair.0, 2);
5567    /// assert_eq!(pair.1, -1);
5568    /// ```
5569    ///
5570    /// [icv]: crate#incomplete-computation-values
5571    #[inline]
5572    pub fn lucas_2(n: u32) -> Lucas2Incomplete {
5573        let n = n.into();
5574        Lucas2Incomplete { n }
5575    }
5576
5577    #[cfg(feature = "rand")]
5578    /// Generates a random number with a specified maximum number of bits.
5579    ///
5580    /// The following are implemented with the returned [incomplete-computation
5581    /// value][icv] as `Src`:
5582    ///   * <code>[Assign]\<Src> for [Integer]</code>
5583    ///   * <code>[From]\<Src> for [Integer]</code>
5584    ///   * <code>[Complete]\<[Completed][Complete::Completed] = [Integer]> for Src</code>
5585    ///
5586    /// # Examples
5587    ///
5588    /// ```rust
5589    /// use rug::rand::RandState;
5590    /// use rug::{Assign, Integer};
5591    /// let mut rand = RandState::new();
5592    /// let mut i = Integer::from(Integer::random_bits(0, &mut rand));
5593    /// assert_eq!(i, 0);
5594    /// i.assign(Integer::random_bits(80, &mut rand));
5595    /// assert!(i.significant_bits() <= 80);
5596    /// ```
5597    ///
5598    /// [icv]: crate#incomplete-computation-values
5599    #[inline]
5600    pub fn random_bits(bits: u32, rng: &mut dyn MutRandState) -> RandomBitsIncomplete<'_> {
5601        let bits = bits.into();
5602        RandomBitsIncomplete { bits, rng }
5603    }
5604
5605    #[cfg(feature = "rand")]
5606    /// Generates a non-negative random number below the given boundary value.
5607    ///
5608    /// # Panics
5609    ///
5610    /// Panics if the boundary value is less than or equal to zero.
5611    ///
5612    /// # Examples
5613    ///
5614    /// ```rust
5615    /// use rug::rand::RandState;
5616    /// use rug::Integer;
5617    /// let mut rand = RandState::new();
5618    /// let i = Integer::from(15);
5619    /// let below = i.random_below(&mut rand);
5620    /// println!("0 ≤ {} < 15", below);
5621    /// assert!(below < 15);
5622    /// ```
5623    #[inline]
5624    #[must_use]
5625    pub fn random_below(mut self, rng: &mut dyn MutRandState) -> Self {
5626        self.random_below_mut(rng);
5627        self
5628    }
5629
5630    #[cfg(feature = "rand")]
5631    /// Generates a non-negative random number below the given boundary value.
5632    ///
5633    /// # Panics
5634    ///
5635    /// Panics if the boundary value is less than or equal to zero.
5636    ///
5637    /// # Examples
5638    ///
5639    /// ```rust
5640    /// use rug::rand::RandState;
5641    /// use rug::Integer;
5642    /// let mut rand = RandState::new();
5643    /// let mut i = Integer::from(15);
5644    /// i.random_below_mut(&mut rand);
5645    /// println!("0 ≤ {} < 15", i);
5646    /// assert!(i < 15);
5647    /// ```
5648    #[inline]
5649    pub fn random_below_mut(&mut self, rng: &mut dyn MutRandState) {
5650        xmpz::urandomm(self, rng, ());
5651    }
5652
5653    #[cfg(feature = "rand")]
5654    /// Generates a non-negative random number below the given boundary value.
5655    ///
5656    /// The following are implemented with the returned [incomplete-computation
5657    /// value][icv] as `Src`:
5658    ///   * <code>[Assign]\<Src> for [Integer]</code>
5659    ///   * <code>[From]\<Src> for [Integer]</code>
5660    ///   * <code>[Complete]\<[Completed][Complete::Completed] = [Integer]> for Src</code>
5661    ///
5662    /// # Panics
5663    ///
5664    /// Panics if the boundary value is less than or equal to zero.
5665    ///
5666    /// # Examples
5667    ///
5668    /// ```rust
5669    /// use rug::rand::RandState;
5670    /// use rug::Integer;
5671    /// let mut rand = RandState::new();
5672    /// let bound = Integer::from(15);
5673    /// let i = Integer::from(bound.random_below_ref(&mut rand));
5674    /// println!("0 ≤ {} < {}", i, bound);
5675    /// assert!(i < bound);
5676    /// ```
5677    ///
5678    /// [icv]: crate#incomplete-computation-values
5679    #[inline]
5680    pub fn random_below_ref<'a>(
5681        &'a self,
5682        rng: &'a mut dyn MutRandState,
5683    ) -> RandomBelowIncomplete<'a> {
5684        RandomBelowIncomplete {
5685            ref_self: self,
5686            rng,
5687        }
5688    }
5689
5690    /// This method has been renamed to [`extended_gcd`][Integer::extended_gcd].
5691    #[deprecated(since = "1.18.0", note = "renamed to `extended_gcd`")]
5692    #[inline]
5693    pub fn gcd_cofactors(self, other: Self, rop: Self) -> (Self, Self, Self) {
5694        self.extended_gcd(other, rop)
5695    }
5696
5697    /// This method has been renamed to
5698    /// [`extended_gcd_mut`][Integer::extended_gcd_mut].
5699    #[deprecated(since = "1.18.0", note = "renamed to `extended_gcd_mut`")]
5700    #[inline]
5701    pub fn gcd_cofactors_mut(&mut self, other: &mut Self, rop: &mut Self) {
5702        self.extended_gcd_mut(other, rop);
5703    }
5704
5705    /// This method has been renamed to
5706    /// [`extended_gcd_ref`][Integer::extended_gcd_ref].
5707    #[deprecated(since = "1.18.0", note = "renamed to `extended_gcd_ref`")]
5708    #[inline]
5709    pub fn gcd_cofactors_ref<'a>(&'a self, other: &'a Self) -> GcdExtIncomplete<'a> {
5710        self.extended_gcd_ref(other)
5711    }
5712}
5713
5714#[derive(Debug)]
5715pub struct SumIncomplete<'a, I>
5716where
5717    I: Iterator<Item = &'a Integer>,
5718{
5719    values: I,
5720}
5721
5722impl<'a, I> Assign<SumIncomplete<'a, I>> for Integer
5723where
5724    I: Iterator<Item = &'a Self>,
5725{
5726    fn assign(&mut self, mut src: SumIncomplete<'a, I>) {
5727        if let Some(first) = src.values.next() {
5728            self.assign(first);
5729        } else {
5730            self.assign(0u32);
5731            return;
5732        }
5733        self.add_assign(src);
5734    }
5735}
5736
5737impl<'a, I> From<SumIncomplete<'a, I>> for Integer
5738where
5739    I: Iterator<Item = &'a Self>,
5740{
5741    fn from(mut src: SumIncomplete<'a, I>) -> Self {
5742        let mut dst = match src.values.next() {
5743            Some(first) => first.clone(),
5744            None => return Integer::new(),
5745        };
5746        dst.add_assign(src);
5747        dst
5748    }
5749}
5750
5751impl<'a, I> Complete for SumIncomplete<'a, I>
5752where
5753    I: Iterator<Item = &'a Integer>,
5754{
5755    type Completed = Integer;
5756    #[inline]
5757    fn complete(self) -> Integer {
5758        Integer::from(self)
5759    }
5760}
5761
5762impl<'a, I> Add<SumIncomplete<'a, I>> for Integer
5763where
5764    I: Iterator<Item = &'a Self>,
5765{
5766    type Output = Self;
5767    #[inline]
5768    fn add(mut self, rhs: SumIncomplete<'a, I>) -> Self {
5769        self.add_assign(rhs);
5770        self
5771    }
5772}
5773
5774impl<'a, I> Add<Integer> for SumIncomplete<'a, I>
5775where
5776    I: Iterator<Item = &'a Integer>,
5777{
5778    type Output = Integer;
5779    #[inline]
5780    fn add(self, mut rhs: Integer) -> Integer {
5781        rhs.add_assign(self);
5782        rhs
5783    }
5784}
5785
5786impl<'a, I> AddAssign<SumIncomplete<'a, I>> for Integer
5787where
5788    I: Iterator<Item = &'a Self>,
5789{
5790    fn add_assign(&mut self, src: SumIncomplete<'a, I>) {
5791        for i in src.values {
5792            self.add_assign(i);
5793        }
5794    }
5795}
5796
5797impl<'a, I> Sub<SumIncomplete<'a, I>> for Integer
5798where
5799    I: Iterator<Item = &'a Self>,
5800{
5801    type Output = Self;
5802    #[inline]
5803    fn sub(mut self, rhs: SumIncomplete<'a, I>) -> Self {
5804        self.sub_assign(rhs);
5805        self
5806    }
5807}
5808
5809impl<'a, I> Sub<Integer> for SumIncomplete<'a, I>
5810where
5811    I: Iterator<Item = &'a Integer>,
5812{
5813    type Output = Integer;
5814    #[inline]
5815    fn sub(self, mut rhs: Integer) -> Integer {
5816        rhs.neg_assign();
5817        rhs.add_assign(self);
5818        rhs
5819    }
5820}
5821
5822impl<'a, I> SubAssign<SumIncomplete<'a, I>> for Integer
5823where
5824    I: Iterator<Item = &'a Self>,
5825{
5826    fn sub_assign(&mut self, src: SumIncomplete<'a, I>) {
5827        for i in src.values {
5828            self.sub_assign(i);
5829        }
5830    }
5831}
5832
5833impl<'a, I> SubFrom<SumIncomplete<'a, I>> for Integer
5834where
5835    I: Iterator<Item = &'a Self>,
5836{
5837    fn sub_from(&mut self, src: SumIncomplete<'a, I>) {
5838        self.neg_assign();
5839        self.add_assign(src);
5840    }
5841}
5842
5843#[derive(Debug)]
5844pub struct DotIncomplete<'a, I>
5845where
5846    I: Iterator<Item = (&'a Integer, &'a Integer)>,
5847{
5848    values: I,
5849}
5850
5851impl<'a, I> Assign<DotIncomplete<'a, I>> for Integer
5852where
5853    I: Iterator<Item = (&'a Integer, &'a Integer)>,
5854{
5855    fn assign(&mut self, mut src: DotIncomplete<'a, I>) {
5856        if let Some(first) = src.values.next() {
5857            self.assign(first.0 * first.1);
5858        } else {
5859            self.assign(0u32);
5860            return;
5861        }
5862        self.add_assign(src);
5863    }
5864}
5865
5866impl<'a, I> From<DotIncomplete<'a, I>> for Integer
5867where
5868    I: Iterator<Item = (&'a Integer, &'a Integer)>,
5869{
5870    fn from(mut src: DotIncomplete<'a, I>) -> Self {
5871        let mut dst = match src.values.next() {
5872            Some(first) => Integer::from(first.0 * first.1),
5873            None => return Integer::new(),
5874        };
5875        dst.add_assign(src);
5876        dst
5877    }
5878}
5879
5880impl<'a, I> Complete for DotIncomplete<'a, I>
5881where
5882    I: Iterator<Item = (&'a Integer, &'a Integer)>,
5883{
5884    type Completed = Integer;
5885    #[inline]
5886    fn complete(self) -> Integer {
5887        Integer::from(self)
5888    }
5889}
5890
5891impl<'a, I> Add<DotIncomplete<'a, I>> for Integer
5892where
5893    I: Iterator<Item = (&'a Integer, &'a Integer)>,
5894{
5895    type Output = Self;
5896    #[inline]
5897    fn add(mut self, rhs: DotIncomplete<'a, I>) -> Self {
5898        self.add_assign(rhs);
5899        self
5900    }
5901}
5902
5903impl<'a, I> Add<Integer> for DotIncomplete<'a, I>
5904where
5905    I: Iterator<Item = (&'a Integer, &'a Integer)>,
5906{
5907    type Output = Integer;
5908    #[inline]
5909    fn add(self, mut rhs: Integer) -> Integer {
5910        rhs.add_assign(self);
5911        rhs
5912    }
5913}
5914
5915impl<'a, I> AddAssign<DotIncomplete<'a, I>> for Integer
5916where
5917    I: Iterator<Item = (&'a Integer, &'a Integer)>,
5918{
5919    fn add_assign(&mut self, src: DotIncomplete<'a, I>) {
5920        for i in src.values {
5921            #[allow(clippy::suspicious_op_assign_impl)]
5922            AddAssign::add_assign(self, i.0 * i.1);
5923        }
5924    }
5925}
5926
5927impl<'a, I> Sub<DotIncomplete<'a, I>> for Integer
5928where
5929    I: Iterator<Item = (&'a Integer, &'a Integer)>,
5930{
5931    type Output = Self;
5932    #[inline]
5933    fn sub(mut self, rhs: DotIncomplete<'a, I>) -> Self {
5934        self.sub_assign(rhs);
5935        self
5936    }
5937}
5938
5939impl<'a, I> Sub<Integer> for DotIncomplete<'a, I>
5940where
5941    I: Iterator<Item = (&'a Integer, &'a Integer)>,
5942{
5943    type Output = Integer;
5944    #[inline]
5945    fn sub(self, mut rhs: Integer) -> Integer {
5946        rhs.neg_assign();
5947        rhs.add_assign(self);
5948        rhs
5949    }
5950}
5951
5952impl<'a, I> SubAssign<DotIncomplete<'a, I>> for Integer
5953where
5954    I: Iterator<Item = (&'a Integer, &'a Integer)>,
5955{
5956    fn sub_assign(&mut self, src: DotIncomplete<'a, I>) {
5957        for i in src.values {
5958            #[allow(clippy::suspicious_op_assign_impl)]
5959            SubAssign::sub_assign(self, i.0 * i.1);
5960        }
5961    }
5962}
5963
5964impl<'a, I> SubFrom<DotIncomplete<'a, I>> for Integer
5965where
5966    I: Iterator<Item = (&'a Integer, &'a Integer)>,
5967{
5968    fn sub_from(&mut self, src: DotIncomplete<'a, I>) {
5969        self.neg_assign();
5970        self.add_assign(src);
5971    }
5972}
5973
5974#[derive(Debug)]
5975pub struct ProductIncomplete<'a, I>
5976where
5977    I: Iterator<Item = &'a Integer>,
5978{
5979    values: I,
5980}
5981
5982impl<'a, I> Assign<ProductIncomplete<'a, I>> for Integer
5983where
5984    I: Iterator<Item = &'a Self>,
5985{
5986    fn assign(&mut self, mut src: ProductIncomplete<'a, I>) {
5987        if let Some(first) = src.values.next() {
5988            self.assign(first);
5989        } else {
5990            self.assign(1u32);
5991            return;
5992        }
5993        self.mul_assign(src);
5994    }
5995}
5996
5997impl<'a, I> From<ProductIncomplete<'a, I>> for Integer
5998where
5999    I: Iterator<Item = &'a Self>,
6000{
6001    fn from(mut src: ProductIncomplete<'a, I>) -> Self {
6002        let mut dst = match src.values.next() {
6003            Some(first) => first.clone(),
6004            None => return Integer::from(1),
6005        };
6006        dst.mul_assign(src);
6007        dst
6008    }
6009}
6010
6011impl<'a, I> Complete for ProductIncomplete<'a, I>
6012where
6013    I: Iterator<Item = &'a Integer>,
6014{
6015    type Completed = Integer;
6016    #[inline]
6017    fn complete(self) -> Integer {
6018        Integer::from(self)
6019    }
6020}
6021
6022impl<'a, I> Mul<ProductIncomplete<'a, I>> for Integer
6023where
6024    I: Iterator<Item = &'a Self>,
6025{
6026    type Output = Self;
6027    #[inline]
6028    fn mul(mut self, rhs: ProductIncomplete<'a, I>) -> Self {
6029        self.mul_assign(rhs);
6030        self
6031    }
6032}
6033
6034impl<'a, I> Mul<Integer> for ProductIncomplete<'a, I>
6035where
6036    I: Iterator<Item = &'a Integer>,
6037{
6038    type Output = Integer;
6039    #[inline]
6040    fn mul(self, mut rhs: Integer) -> Integer {
6041        rhs.mul_assign(self);
6042        rhs
6043    }
6044}
6045
6046impl<'a, I> MulAssign<ProductIncomplete<'a, I>> for Integer
6047where
6048    I: Iterator<Item = &'a Self>,
6049{
6050    fn mul_assign(&mut self, mut src: ProductIncomplete<'a, I>) {
6051        let mut other = match src.values.next() {
6052            Some(next) => Integer::from(&*self * next),
6053            None => return,
6054        };
6055        loop {
6056            if let Some(next) = src.values.next() {
6057                self.assign(&other * next);
6058            } else {
6059                self.assign(other);
6060                return;
6061            }
6062            match src.values.next() {
6063                Some(next) => {
6064                    other.assign(&*self * next);
6065                }
6066                None => {
6067                    return;
6068                }
6069            }
6070            if self.is_zero() {
6071                return;
6072            }
6073        }
6074    }
6075}
6076
6077ref_math_op1! { Integer; xmpz::abs; struct AbsIncomplete {} }
6078ref_math_op1! { Integer; xmpz::signum; struct SignumIncomplete {} }
6079
6080#[derive(Debug)]
6081pub struct ClampIncomplete<'s, 'min, 'max, Min, Max>
6082where
6083    Integer: PartialOrd<Min> + PartialOrd<Max> + for<'a> Assign<&'a Min> + for<'a> Assign<&'a Max>,
6084{
6085    ref_self: &'s Integer,
6086    min: &'min Min,
6087    max: &'max Max,
6088}
6089
6090impl<Min, Max> Assign<ClampIncomplete<'_, '_, '_, Min, Max>> for Integer
6091where
6092    Self: PartialOrd<Min> + PartialOrd<Max> + for<'a> Assign<&'a Min> + for<'a> Assign<&'a Max>,
6093{
6094    #[inline]
6095    fn assign(&mut self, src: ClampIncomplete<Min, Max>) {
6096        if src.ref_self.lt(src.min) {
6097            self.assign(src.min);
6098            assert!(!(*self).gt(src.max), "minimum larger than maximum");
6099        } else if src.ref_self.gt(src.max) {
6100            self.assign(src.max);
6101            assert!(!(*self).lt(src.min), "minimum larger than maximum");
6102        } else {
6103            self.assign(src.ref_self);
6104        }
6105    }
6106}
6107
6108impl<Min, Max> From<ClampIncomplete<'_, '_, '_, Min, Max>> for Integer
6109where
6110    Self: PartialOrd<Min> + PartialOrd<Max> + for<'a> Assign<&'a Min> + for<'a> Assign<&'a Max>,
6111{
6112    #[inline]
6113    fn from(src: ClampIncomplete<Min, Max>) -> Self {
6114        let mut dst = Integer::new();
6115        dst.assign(src);
6116        dst
6117    }
6118}
6119
6120impl<Min, Max> Complete for ClampIncomplete<'_, '_, '_, Min, Max>
6121where
6122    Integer: PartialOrd<Min> + PartialOrd<Max> + for<'a> Assign<&'a Min> + for<'a> Assign<&'a Max>,
6123{
6124    type Completed = Integer;
6125    #[inline]
6126    fn complete(self) -> Integer {
6127        Integer::from(self)
6128    }
6129}
6130
6131ref_math_op1! { Integer; xmpz::fdiv_r_2exp; struct KeepBitsIncomplete { n: bitcnt_t } }
6132ref_math_op1! { Integer; xmpz::keep_signed_bits; struct KeepSignedBitsIncomplete { n: bitcnt_t } }
6133ref_math_op1! { Integer; xmpz::next_pow_of_two; struct NextPowerOfTwoIncomplete {} }
6134ref_math_op2! { Integer; xmpz::modulo; struct ModuloIncomplete { divisor } }
6135ref_math_op2_2! { Integer; xmpz::tdiv_qr; struct DivRemIncomplete { divisor } }
6136ref_math_op2_2! { Integer; xmpz::cdiv_qr; struct DivRemCeilIncomplete { divisor } }
6137ref_math_op2_2! { Integer; xmpz::fdiv_qr; struct DivRemFloorIncomplete { divisor } }
6138ref_math_op2_2! { Integer; xmpz::rdiv_qr; struct DivRemRoundIncomplete { divisor } }
6139ref_math_op2_2! { Integer; xmpz::ediv_qr; struct DivRemEucIncomplete { divisor } }
6140ref_math_op2! { Integer; xmpz::divexact; struct DivExactIncomplete { divisor } }
6141ref_math_op1! { Integer; xmpz::divexact_u32; struct DivExactUIncomplete { divisor: u32 } }
6142
6143#[derive(Debug)]
6144pub struct PowModIncomplete<'a> {
6145    ref_self: Option<&'a Integer>,
6146    sinverse: Option<Integer>,
6147    exponent: &'a Integer,
6148    modulo: &'a Integer,
6149}
6150
6151impl Assign<PowModIncomplete<'_>> for Integer {
6152    #[inline]
6153    fn assign(&mut self, src: PowModIncomplete<'_>) {
6154        match (src.ref_self, src.sinverse) {
6155            (Some(base), None) => {
6156                debug_assert!(!src.exponent.is_negative());
6157                xmpz::pow_mod(self, base, src.exponent, src.modulo);
6158            }
6159            (None, Some(sinverse)) => {
6160                debug_assert!(src.exponent.is_negative());
6161                xmpz::pow_mod(self, &sinverse, src.exponent, src.modulo);
6162            }
6163            _ => unreachable!(),
6164        }
6165    }
6166}
6167
6168// do not use from_assign! macro to reuse sinverse
6169impl From<PowModIncomplete<'_>> for Integer {
6170    #[inline]
6171    fn from(src: PowModIncomplete<'_>) -> Self {
6172        match (src.ref_self, src.sinverse) {
6173            (Some(base), None) => {
6174                debug_assert!(!src.exponent.is_negative());
6175                let mut dst = Integer::new();
6176                xmpz::pow_mod(&mut dst, base, src.exponent, src.modulo);
6177                dst
6178            }
6179            (None, Some(mut sinverse)) => {
6180                debug_assert!(src.exponent.is_negative());
6181                xmpz::pow_mod(&mut sinverse, (), src.exponent, src.modulo);
6182                sinverse
6183            }
6184            _ => unreachable!(),
6185        }
6186    }
6187}
6188
6189impl Complete for PowModIncomplete<'_> {
6190    type Completed = Integer;
6191    #[inline]
6192    fn complete(self) -> Integer {
6193        Integer::from(self)
6194    }
6195}
6196
6197pub struct SecurePowModIncomplete<'a> {
6198    ref_self: &'a Integer,
6199    exponent: &'a Integer,
6200    modulo: &'a Integer,
6201}
6202
6203impl Assign<SecurePowModIncomplete<'_>> for Integer {
6204    #[inline]
6205    fn assign(&mut self, src: SecurePowModIncomplete<'_>) {
6206        xmpz::powm_sec(self, src.ref_self, src.exponent, src.modulo);
6207    }
6208}
6209
6210from_assign! { SecurePowModIncomplete<'_> => Integer }
6211
6212ref_math_op0! { Integer; xmpz::u32_pow_u32; struct UPowUIncomplete { base: u32, exponent: u32 } }
6213ref_math_op0! { Integer; xmpz::i32_pow_u32; struct IPowUIncomplete { base: i32, exponent: u32 } }
6214ref_math_op1! { Integer; xmpz::root; struct RootIncomplete { n: c_ulong } }
6215ref_math_op1_2! { Integer; xmpz::rootrem; struct RootRemIncomplete { n: c_ulong } }
6216ref_math_op1! { Integer; xmpz::sqrt; struct SqrtIncomplete {} }
6217ref_math_op1_2! { Integer; xmpz::sqrtrem; struct SqrtRemIncomplete {} }
6218ref_math_op1! { Integer; xmpz::nextprime; struct NextPrimeIncomplete {} }
6219ref_math_op1! { Integer; xmpz::prevprime; struct PrevPrimeIncomplete {} }
6220ref_math_op2! { Integer; xmpz::gcd; struct GcdIncomplete { other } }
6221ref_math_op1! { Integer; xmpz::gcd_ui; struct GcdUIncomplete { other: c_ulong } }
6222
6223impl From<GcdUIncomplete<'_>> for Option<u32> {
6224    #[inline]
6225    fn from(src: GcdUIncomplete) -> Self {
6226        let gcd = xmpz::gcd_opt_ui(None, src.ref_self, src.other.into());
6227        if gcd == 0 && !src.ref_self.is_zero() {
6228            None
6229        } else {
6230            gcd.checked_cast()
6231        }
6232    }
6233}
6234
6235#[derive(Debug)]
6236pub struct GcdExtIncomplete<'a> {
6237    ref_self: &'a Integer,
6238    other: &'a Integer,
6239}
6240
6241impl Assign<GcdExtIncomplete<'_>> for (&mut Integer, &mut Integer, &mut Integer) {
6242    #[inline]
6243    fn assign(&mut self, src: GcdExtIncomplete<'_>) {
6244        xmpz::gcdext(self.0, self.1, Some(self.2), src.ref_self, src.other);
6245    }
6246}
6247
6248impl Assign<GcdExtIncomplete<'_>> for (Integer, Integer, Integer) {
6249    #[inline]
6250    fn assign(&mut self, src: GcdExtIncomplete<'_>) {
6251        (&mut self.0, &mut self.1, &mut self.2).assign(src);
6252    }
6253}
6254
6255from_assign! { GcdExtIncomplete<'_> => Integer, Integer, Integer }
6256
6257impl Assign<GcdExtIncomplete<'_>> for (&mut Integer, &mut Integer) {
6258    #[inline]
6259    fn assign(&mut self, src: GcdExtIncomplete<'_>) {
6260        xmpz::gcdext(self.0, self.1, None, src.ref_self, src.other);
6261    }
6262}
6263
6264impl Assign<GcdExtIncomplete<'_>> for (Integer, Integer) {
6265    #[inline]
6266    fn assign(&mut self, src: GcdExtIncomplete<'_>) {
6267        Assign::assign(&mut (&mut self.0, &mut self.1), src);
6268    }
6269}
6270
6271impl From<GcdExtIncomplete<'_>> for (Integer, Integer) {
6272    #[inline]
6273    fn from(src: GcdExtIncomplete<'_>) -> Self {
6274        let mut dst = Self::default();
6275        Assign::assign(&mut (&mut dst.0, &mut dst.1), src);
6276        dst
6277    }
6278}
6279
6280ref_math_op2! { Integer; xmpz::lcm; struct LcmIncomplete { other } }
6281ref_math_op1! { Integer; xmpz::lcm_ui; struct LcmUIncomplete { other: c_ulong } }
6282
6283#[derive(Debug)]
6284pub struct InvertIncomplete<'a> {
6285    sinverse: Integer,
6286    modulo: &'a Integer,
6287}
6288
6289impl Assign<InvertIncomplete<'_>> for Integer {
6290    #[inline]
6291    fn assign(&mut self, src: InvertIncomplete<'_>) {
6292        xmpz::finish_invert(self, &src.sinverse, src.modulo);
6293    }
6294}
6295
6296// do not use from_assign! macro to reuse sinverse
6297impl From<InvertIncomplete<'_>> for Integer {
6298    #[inline]
6299    fn from(mut src: InvertIncomplete<'_>) -> Self {
6300        xmpz::finish_invert(&mut src.sinverse, (), src.modulo);
6301        src.sinverse
6302    }
6303}
6304
6305impl Complete for InvertIncomplete<'_> {
6306    type Completed = Integer;
6307    #[inline]
6308    fn complete(self) -> Integer {
6309        Integer::from(self)
6310    }
6311}
6312
6313#[derive(Debug)]
6314pub struct RemoveFactorIncomplete<'a> {
6315    ref_self: &'a Integer,
6316    factor: &'a Integer,
6317}
6318
6319impl Assign<RemoveFactorIncomplete<'_>> for (&mut Integer, &mut u32) {
6320    #[inline]
6321    fn assign(&mut self, src: RemoveFactorIncomplete<'_>) {
6322        *self.1 = xmpz::remove(self.0, src.ref_self, src.factor).strict_cast();
6323    }
6324}
6325
6326impl Assign<RemoveFactorIncomplete<'_>> for (Integer, u32) {
6327    #[inline]
6328    fn assign(&mut self, src: RemoveFactorIncomplete<'_>) {
6329        (&mut self.0, &mut self.1).assign(src);
6330    }
6331}
6332
6333from_assign! { RemoveFactorIncomplete<'_> => Integer, u32 }
6334
6335ref_math_op0! { Integer; xmpz::fac_ui; struct FactorialIncomplete { n: c_ulong } }
6336ref_math_op0! { Integer; xmpz::twofac_ui; struct Factorial2Incomplete { n: c_ulong } }
6337ref_math_op0! { Integer; xmpz::mfac_uiui; struct FactorialMIncomplete { n: c_ulong, m: c_ulong } }
6338ref_math_op0! { Integer; xmpz::primorial_ui; struct PrimorialIncomplete { n: c_ulong } }
6339ref_math_op1! { Integer; xmpz::bin_ui; struct BinomialIncomplete { k: c_ulong } }
6340ref_math_op0! { Integer; xmpz::bin_uiui; struct BinomialUIncomplete { n: c_ulong, k: c_ulong } }
6341ref_math_op0! { Integer; xmpz::fib_ui; struct FibonacciIncomplete { n: c_ulong } }
6342ref_math_op0_2! { Integer; xmpz::fib2_ui; struct Fibonacci2Incomplete { n: c_ulong } }
6343ref_math_op0! { Integer; xmpz::lucnum_ui; struct LucasIncomplete { n: c_ulong } }
6344ref_math_op0_2! { Integer; xmpz::lucnum2_ui; struct Lucas2Incomplete { n: c_ulong } }
6345
6346#[cfg(feature = "rand")]
6347pub struct RandomBitsIncomplete<'a> {
6348    bits: bitcnt_t,
6349    rng: &'a mut dyn MutRandState,
6350}
6351
6352#[cfg(feature = "rand")]
6353impl Assign<RandomBitsIncomplete<'_>> for Integer {
6354    #[inline]
6355    fn assign(&mut self, src: RandomBitsIncomplete) {
6356        xmpz::urandomb(self, src.rng, src.bits);
6357    }
6358}
6359
6360#[cfg(feature = "rand")]
6361from_assign! { RandomBitsIncomplete<'_> => Integer }
6362
6363#[cfg(feature = "rand")]
6364pub struct RandomBelowIncomplete<'a> {
6365    ref_self: &'a Integer,
6366    rng: &'a mut dyn MutRandState,
6367}
6368
6369#[cfg(feature = "rand")]
6370impl Assign<RandomBelowIncomplete<'_>> for Integer {
6371    #[inline]
6372    fn assign(&mut self, src: RandomBelowIncomplete) {
6373        xmpz::urandomm(self, src.rng, src.ref_self);
6374    }
6375}
6376
6377#[cfg(feature = "rand")]
6378from_assign! { RandomBelowIncomplete<'_> => Integer }
6379
6380pub(crate) fn req_chars(i: &Integer, radix: i32, extra: usize) -> usize {
6381    assert!((2..=36).contains(&radix), "radix out of range");
6382    let size = unsafe { gmp::mpz_sizeinbase(i.as_raw(), radix) };
6383    let size_extra = size.checked_add(extra).expect("overflow");
6384    if i.is_negative() {
6385        size_extra.checked_add(1).expect("overflow")
6386    } else {
6387        size_extra
6388    }
6389}
6390
6391pub(crate) fn append_to_string(s: &mut StringLike, i: &Integer, radix: i32, to_upper: bool) {
6392    // add 1 for nul
6393    let size = req_chars(i, radix, 1);
6394    s.reserve(size);
6395    let reserved_ptr = s.as_str().as_ptr();
6396    let case_radix = if to_upper { -radix } else { radix };
6397    unsafe {
6398        let alloced = s.reserved_space();
6399        gmp::mpz_get_str(
6400            misc::cast_ptr_mut(alloced.as_mut_ptr()),
6401            case_radix.cast(),
6402            i.as_raw(),
6403        );
6404        let nul_index = alloced
6405            .iter()
6406            .position(|&x: &MaybeUninit<u8>| {
6407                // SAFETY: bytes will be initialized up to and including nul
6408                x.assume_init() == 0
6409            })
6410            .unwrap();
6411        s.increase_len(nul_index);
6412    }
6413    debug_assert_eq!(reserved_ptr, s.as_str().as_ptr());
6414}
6415
6416#[derive(Debug)]
6417pub struct ParseIncomplete {
6418    is_negative: bool,
6419    digits: VecLike<u8>,
6420    radix: i32,
6421}
6422
6423impl Assign<ParseIncomplete> for Integer {
6424    #[inline]
6425    fn assign(&mut self, src: ParseIncomplete) {
6426        // SAFETY: radix is in correct range, and all digits are < radix
6427        unsafe {
6428            self.assign_bytes_radix_unchecked(src.digits.as_slice(), src.radix, src.is_negative);
6429        }
6430    }
6431}
6432
6433from_assign! { ParseIncomplete => Integer }
6434
6435fn parse(bytes: &[u8], radix: i32) -> Result<ParseIncomplete, ParseIntegerError> {
6436    use self::{ParseErrorKind as Kind, ParseIntegerError as Error};
6437
6438    assert!((2..=36).contains(&radix), "radix out of range");
6439    let bradix = radix.strict_as::<u8>();
6440
6441    let mut digits = VecLike::new();
6442    digits.reserve(bytes.len());
6443    let mut has_sign = false;
6444    let mut is_negative = false;
6445    let mut has_digits = false;
6446    for &b in bytes {
6447        let digit = match b {
6448            b'+' if !has_sign && !has_digits => {
6449                has_sign = true;
6450                continue;
6451            }
6452            b'-' if !has_sign && !has_digits => {
6453                is_negative = true;
6454                has_sign = true;
6455                continue;
6456            }
6457            b'_' if has_digits => continue,
6458            b' ' | b'\t' | b'\n' | 0x0b | 0x0c | 0x0d => continue,
6459
6460            b'0'..=b'9' => b - b'0',
6461            b'a'..=b'z' => b - b'a' + 10,
6462            b'A'..=b'Z' => b - b'A' + 10,
6463
6464            // error
6465            _ => bradix,
6466        };
6467        if digit >= bradix {
6468            return Err(Error {
6469                kind: Kind::InvalidDigit,
6470            });
6471        };
6472        has_digits = true;
6473        if digit > 0 || !digits.as_slice().is_empty() {
6474            digits.push(digit);
6475        }
6476    }
6477    if !has_digits {
6478        return Err(Error {
6479            kind: Kind::NoDigits,
6480        });
6481    }
6482    Ok(ParseIncomplete {
6483        is_negative,
6484        digits,
6485        radix,
6486    })
6487}
6488
6489/**
6490An error which can be returned when parsing an [`Integer`].
6491
6492See the <code>[Integer]::[parse\_radix][Integer::parse_radix]</code> method for
6493details on what strings are accepted.
6494
6495# Examples
6496
6497```rust
6498use rug::integer::ParseIntegerError;
6499use rug::Integer;
6500// This string is not an integer.
6501let s = "something completely different (_!_!_)";
6502let error: ParseIntegerError = match Integer::parse_radix(s, 4) {
6503    Ok(_) => unreachable!(),
6504    Err(error) => error,
6505};
6506println!("Parse error: {}", error);
6507```
6508*/
6509#[derive(Clone, Copy, Debug, Eq, PartialEq)]
6510pub struct ParseIntegerError {
6511    kind: ParseErrorKind,
6512}
6513
6514#[derive(Clone, Copy, Debug, Eq, PartialEq)]
6515enum ParseErrorKind {
6516    InvalidDigit,
6517    NoDigits,
6518}
6519
6520impl ParseIntegerError {
6521    fn desc(&self) -> &str {
6522        use self::ParseErrorKind::*;
6523        match self.kind {
6524            InvalidDigit => "invalid digit found in string",
6525            NoDigits => "string has no digits",
6526        }
6527    }
6528}
6529
6530impl Display for ParseIntegerError {
6531    fn fmt(&self, f: &mut Formatter<'_>) -> FmtResult {
6532        Display::fmt(self.desc(), f)
6533    }
6534}
6535
6536impl Error for ParseIntegerError {
6537    #[allow(deprecated)]
6538    fn description(&self) -> &str {
6539        self.desc()
6540    }
6541}
6542
6543#[derive(Clone, Copy, Debug, Eq, Hash, Ord, PartialEq, PartialOrd)]
6544/**
6545Whether a number is prime.
6546
6547See the
6548<code>[Integer]::[is\_probably\_prime][Integer::is_probably_prime]</code>
6549method.
6550
6551# Examples
6552
6553```rust
6554use rug::integer::IsPrime;
6555use rug::Integer;
6556let no = Integer::from(163 * 4003);
6557assert_eq!(no.is_probably_prime(30), IsPrime::No);
6558let yes = Integer::from(817_504_243);
6559assert_eq!(yes.is_probably_prime(30), IsPrime::Yes);
6560// 16_412_292_043_871_650_369 is actually a prime.
6561let probably = Integer::from(16_412_292_043_871_650_369_u64);
6562assert_eq!(probably.is_probably_prime(30), IsPrime::Probably);
6563```
6564*/
6565pub enum IsPrime {
6566    /// The number is definitely not prime.
6567    No,
6568    /// The number is probably prime.
6569    Probably,
6570    /// The number is definitely prime.
6571    Yes,
6572}
6573
6574/// Conversions between [`Integer`] and a [slice] of digits of this
6575/// type are provided.
6576///
6577/// For conversion from digits to [`Integer`], see
6578/// <code>[Integer]::[from\_digits][Integer::from_digits]</code>
6579/// and
6580/// <code>[Integer]::[assign\_digits][Integer::assign_digits]</code>.
6581/// For conversion from [`Integer`] to digits, see
6582/// <code>[Integer]::[significant\_digits][Integer::significant_digits]</code>,
6583/// <code>[Integer]::[to\_digits][Integer::to_digits]</code>, and
6584/// <code>[Integer]::[write\_digits][Integer::write_digits]</code>.
6585///
6586/// This trait is sealed and cannot be implemented for more types; it
6587/// is implemented for [`bool`] and the unsigned integer types [`u8`],
6588/// [`u16`], [`u32`], [`u64`], [`u128`] and [`usize`].
6589///
6590/// [slice]: prim@slice
6591pub trait UnsignedPrimitive: SealedUnsignedPrimitive {}
6592
6593pub struct PrivateUnsignedPrimitive {
6594    bytes: usize,
6595    bits: usize,
6596    nails: usize,
6597}
6598
6599/// # Safety
6600///
6601/// Bit patterns can be written to the implementing type. Implementations must
6602/// make sure that all bit patterns are allowed.
6603pub unsafe trait SealedUnsignedPrimitive: Sized {
6604    const PRIVATE: PrivateUnsignedPrimitive = PrivateUnsignedPrimitive {
6605        bytes: mem::size_of::<Self>(),
6606        bits: mem::size_of::<Self>() * 8,
6607        nails: 0,
6608    };
6609}
6610
6611// Safety: We set nails to 7 so that only 0 or 1 can be written into bool.
6612impl UnsignedPrimitive for bool {}
6613unsafe impl SealedUnsignedPrimitive for bool {
6614    const PRIVATE: PrivateUnsignedPrimitive = PrivateUnsignedPrimitive {
6615        bytes: mem::size_of::<Self>(),
6616        bits: 1,
6617        nails: mem::size_of::<Self>() * 8 - 1,
6618    };
6619}
6620
6621impl UnsignedPrimitive for u8 {}
6622unsafe impl SealedUnsignedPrimitive for u8 {}
6623
6624impl UnsignedPrimitive for u16 {}
6625unsafe impl SealedUnsignedPrimitive for u16 {}
6626
6627impl UnsignedPrimitive for u32 {}
6628unsafe impl SealedUnsignedPrimitive for u32 {}
6629
6630impl UnsignedPrimitive for u64 {}
6631unsafe impl SealedUnsignedPrimitive for u64 {}
6632
6633impl UnsignedPrimitive for u128 {}
6634unsafe impl SealedUnsignedPrimitive for u128 {}
6635
6636impl UnsignedPrimitive for usize {}
6637unsafe impl SealedUnsignedPrimitive for usize {}