diff --git a/Cargo.toml b/Cargo.toml index 720512a6..95e61f3b 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -8,14 +8,14 @@ categories = [ "algorithms", "data-structures", "science" ] license = "MIT OR Apache-2.0" name = "num-bigint" repository = "https://github.com/rust-num/num-bigint" -version = "0.4.6" +version = "0.5.0" readme = "README.md" exclude = ["/ci/*", "/.github/*"] edition = "2021" rust-version = "1.60" [features] -default = ["std"] +default = ["std", "rand"] std = ["num-integer/std", "num-traits/std"] arbitrary = ["dep:arbitrary"] quickcheck = ["dep:quickcheck"] @@ -56,7 +56,7 @@ features = ["i128"] [dependencies.rand] optional = true -version = "0.8" +version = "0.9" default-features = false [dependencies.serde] @@ -73,3 +73,15 @@ default-features = false optional = true version = "1" default-features = false + +[dev-dependencies] +rand = { version = "0.9", features = ["thread_rng"]} + +[lints.clippy] +correctness = "deny" +perf = "deny" +complexity = "deny" +suspicious = "deny" +style = "warn" +pedantic = "warn" +nursery = "warn" \ No newline at end of file diff --git a/README.md b/README.md index cce185b9..f933ac35 100644 --- a/README.md +++ b/README.md @@ -13,7 +13,7 @@ Add this to your `Cargo.toml`: ```toml [dependencies] -num-bigint = "0.4" +num-bigint = "0.5" ``` ## Features @@ -29,12 +29,12 @@ if your compiler is not new enough. feature is enabled. To enable it include rand as ```toml -rand = "0.8" -num-bigint = { version = "0.4", features = ["rand"] } +rand = " =0.9.0-beta.3" +num-bigint = { version = "0.5", features = ["rand"] } ``` Note that you must use the version of `rand` that `num-bigint` is compatible -with: `0.8`. +with: ` =0.9.0-beta.3`. ## Releases diff --git a/benches/bigint.rs b/benches/bigint.rs index 22795274..0a4ed601 100644 --- a/benches/bigint.rs +++ b/benches/bigint.rs @@ -13,24 +13,24 @@ use rng::get_rng; fn multiply_bench(b: &mut Bencher, xbits: u64, ybits: u64) { let mut rng = get_rng(); - let x = rng.gen_bigint(xbits); - let y = rng.gen_bigint(ybits); + let x = rng.random_bigint(xbits); + let y = rng.random_bigint(ybits); b.iter(|| &x * &y); } fn divide_bench(b: &mut Bencher, xbits: u64, ybits: u64) { let mut rng = get_rng(); - let x = rng.gen_bigint(xbits); - let y = rng.gen_bigint(ybits); + let x = rng.random_bigint(xbits); + let y = rng.random_bigint(ybits); b.iter(|| &x / &y); } fn remainder_bench(b: &mut Bencher, xbits: u64, ybits: u64) { let mut rng = get_rng(); - let x = rng.gen_bigint(xbits); - let y = rng.gen_bigint(ybits); + let x = rng.random_bigint(xbits); + let y = rng.random_bigint(ybits); b.iter(|| &x % &y); } @@ -186,7 +186,7 @@ fn fib_to_string(b: &mut Bencher) { fn to_str_radix_bench(b: &mut Bencher, radix: u32, bits: u64) { let mut rng = get_rng(); - let x = rng.gen_bigint(bits); + let x = rng.random_bigint(bits); b.iter(|| x.to_str_radix(radix)); } @@ -222,7 +222,7 @@ fn to_str_radix_36(b: &mut Bencher) { fn from_str_radix_bench(b: &mut Bencher, radix: u32) { let mut rng = get_rng(); - let x = rng.gen_bigint(1009); + let x = rng.random_bigint(1009); let s = x.to_str_radix(radix); assert_eq!(x, BigInt::from_str_radix(&s, radix).unwrap()); b.iter(|| BigInt::from_str_radix(&s, radix)); @@ -256,7 +256,7 @@ fn from_str_radix_36(b: &mut Bencher) { fn rand_bench(b: &mut Bencher, bits: u64) { let mut rng = get_rng(); - b.iter(|| rng.gen_bigint(bits)); + b.iter(|| rng.random_bigint(bits)); } #[bench] @@ -308,7 +308,7 @@ fn shl(b: &mut Bencher) { for i in 0..50 { m <<= i; } - }) + }); } #[bench] @@ -320,14 +320,14 @@ fn shr(b: &mut Bencher) { for i in 0..50 { m >>= i; } - }) + }); } #[bench] fn hash(b: &mut Bencher) { use std::collections::HashSet; let mut rng = get_rng(); - let v: Vec = (1000..2000).map(|bits| rng.gen_bigint(bits)).collect(); + let v: Vec = (1000..2000).map(|bits| rng.random_bigint(bits)).collect(); b.iter(|| { let h: HashSet<&BigInt> = v.iter().collect(); assert_eq!(h.len(), v.len()); @@ -342,7 +342,9 @@ fn pow_bench(b: &mut Bencher) { for _i in 2..=upper { i_big += 1u32; for j in 2..=upper { - i_big.pow(j); + let x = i_big.pow(j); + // added black box to prevent the compiler from optimizing out the pow + std::hint::black_box(&x); } } }); @@ -382,7 +384,7 @@ fn pow_bench_1e100000(b: &mut Bencher) { } /// This modulus is the prime from the 2048-bit MODP DH group: -/// https://tools.ietf.org/html/rfc3526#section-3 +/// const RFC3526_2048BIT_MODP_GROUP: &str = "\ FFFFFFFF_FFFFFFFF_C90FDAA2_2168C234_C4C6628B_80DC1CD1\ 29024E08_8A67CC74_020BBEA6_3B139B22_514A0879_8E3404DD\ @@ -399,8 +401,8 @@ const RFC3526_2048BIT_MODP_GROUP: &str = "\ #[bench] fn modpow(b: &mut Bencher) { let mut rng = get_rng(); - let base = rng.gen_biguint(2048); - let e = rng.gen_biguint(2048); + let base = rng.random_biguint(2048); + let e = rng.random_biguint(2048); let m = BigUint::from_str_radix(RFC3526_2048BIT_MODP_GROUP, 16).unwrap(); b.iter(|| base.modpow(&e, &m)); @@ -409,8 +411,8 @@ fn modpow(b: &mut Bencher) { #[bench] fn modpow_even(b: &mut Bencher) { let mut rng = get_rng(); - let base = rng.gen_biguint(2048); - let e = rng.gen_biguint(2048); + let base = rng.random_biguint(2048); + let e = rng.random_biguint(2048); // Make the modulus even, so monty (base-2^32) doesn't apply. let m = BigUint::from_str_radix(RFC3526_2048BIT_MODP_GROUP, 16).unwrap() - 1u32; @@ -420,7 +422,7 @@ fn modpow_even(b: &mut Bencher) { #[bench] fn to_u32_digits(b: &mut Bencher) { let mut rng = get_rng(); - let n = rng.gen_biguint(2048); + let n = rng.random_biguint(2048); b.iter(|| n.to_u32_digits()); } @@ -428,7 +430,7 @@ fn to_u32_digits(b: &mut Bencher) { #[bench] fn iter_u32_digits(b: &mut Bencher) { let mut rng = get_rng(); - let n = rng.gen_biguint(2048); + let n = rng.random_biguint(2048); b.iter(|| n.iter_u32_digits().max()); } @@ -436,7 +438,7 @@ fn iter_u32_digits(b: &mut Bencher) { #[bench] fn to_u64_digits(b: &mut Bencher) { let mut rng = get_rng(); - let n = rng.gen_biguint(2048); + let n = rng.random_biguint(2048); b.iter(|| n.to_u64_digits()); } @@ -444,7 +446,7 @@ fn to_u64_digits(b: &mut Bencher) { #[bench] fn iter_u64_digits(b: &mut Bencher) { let mut rng = get_rng(); - let n = rng.gen_biguint(2048); + let n = rng.random_biguint(2048); b.iter(|| n.iter_u64_digits().max()); } diff --git a/benches/gcd.rs b/benches/gcd.rs index c211b6ef..f015aa0c 100644 --- a/benches/gcd.rs +++ b/benches/gcd.rs @@ -13,8 +13,8 @@ use rng::get_rng; fn bench(b: &mut Bencher, bits: u64, gcd: fn(&BigUint, &BigUint) -> BigUint) { let mut rng = get_rng(); - let x = rng.gen_biguint(bits); - let y = rng.gen_biguint(bits); + let x = rng.random_biguint(bits); + let y = rng.random_biguint(bits); assert_eq!(euclid(&x, &y), x.gcd(&y)); diff --git a/benches/rng/mod.rs b/benches/rng/mod.rs index 33e4f0fa..8827a043 100644 --- a/benches/rng/mod.rs +++ b/benches/rng/mod.rs @@ -28,11 +28,11 @@ impl RngCore for XorShiftStar { for chunk in dest.chunks_mut(8) { let bytes = self.next_u64().to_le_bytes(); let slice = &bytes[..chunk.len()]; - chunk.copy_from_slice(slice) + chunk.copy_from_slice(slice); } } - fn try_fill_bytes(&mut self, dest: &mut [u8]) -> Result<(), rand::Error> { - Ok(self.fill_bytes(dest)) - } + // fn try_fill_bytes(&mut self, dest: &mut [u8]) -> Result<(), rand::Error> { + // Ok(self.fill_bytes(dest)) + // } } diff --git a/benches/roots.rs b/benches/roots.rs index 7afc4f76..f72017c7 100644 --- a/benches/roots.rs +++ b/benches/roots.rs @@ -20,9 +20,9 @@ use rng::get_rng; fn check(x: &BigUint, n: u32) { let root = x.nth_root(n); if n == 2 { - assert_eq!(root, x.sqrt()) + assert_eq!(root, x.sqrt()); } else if n == 3 { - assert_eq!(root, x.cbrt()) + assert_eq!(root, x.cbrt()); } let lo = root.pow(n); @@ -37,8 +37,8 @@ fn check(x: &BigUint, n: u32) { } fn bench_sqrt(b: &mut Bencher, bits: u64) { - let x = get_rng().gen_biguint(bits); - eprintln!("bench_sqrt({})", x); + let x = get_rng().random_biguint(bits); + eprintln!("bench_sqrt({x})"); check(&x, 2); b.iter(|| x.sqrt()); @@ -65,8 +65,8 @@ fn big4k_sqrt(b: &mut Bencher) { } fn bench_cbrt(b: &mut Bencher, bits: u64) { - let x = get_rng().gen_biguint(bits); - eprintln!("bench_cbrt({})", x); + let x = get_rng().random_biguint(bits); + eprintln!("bench_cbrt({x})"); check(&x, 3); b.iter(|| x.cbrt()); @@ -93,8 +93,8 @@ fn big4k_cbrt(b: &mut Bencher) { } fn bench_nth_root(b: &mut Bencher, bits: u64, n: u32) { - let x = get_rng().gen_biguint(bits); - eprintln!("bench_{}th_root({})", n, x); + let x = get_rng().random_biguint(bits); + eprintln!("bench_{n}th_root({x})"); check(&x, n); b.iter(|| x.nth_root(n)); diff --git a/benches/shootout-pidigits.rs b/benches/shootout-pidigits.rs index b95d42cc..d8f01d2e 100644 --- a/benches/shootout-pidigits.rs +++ b/benches/shootout-pidigits.rs @@ -52,8 +52,8 @@ struct Context { } impl Context { - fn new() -> Context { - Context { + fn new() -> Self { + Self { numer: One::one(), accum: Zero::zero(), denom: One::one(), @@ -68,7 +68,7 @@ impl Context { if self.numer > self.accum { return -1; } - let (q, r) = (&self.numer * Context::from_i32(3) + &self.accum).div_rem(&self.denom); + let (q, r) = (&self.numer * Self::from_i32(3) + &self.accum).div_rem(&self.denom); if r + &self.numer >= self.denom { return -1; } @@ -76,15 +76,15 @@ impl Context { } fn next_term(&mut self, k: i32) { - let y2 = Context::from_i32(k * 2 + 1); + let y2 = Self::from_i32(k * 2 + 1); self.accum = (&self.accum + (&self.numer << 1)) * &y2; - self.numer = &self.numer * Context::from_i32(k); + self.numer = &self.numer * Self::from_i32(k); self.denom = &self.denom * y2; } fn eliminate_digit(&mut self, d: i32) { - let d = Context::from_i32(d); - let ten = Context::from_i32(10); + let d = Self::from_i32(d); + let ten = Self::from_i32(10); self.accum = (&self.accum - &self.denom * d) * &ten; self.numer = &self.numer * ten; } @@ -105,9 +105,9 @@ fn pidigits(n: isize, out: &mut dyn io::Write) -> io::Result<()> { } } - write!(out, "{}", d)?; + write!(out, "{d}")?; if i % 10 == 0 { - writeln!(out, "\t:{}", i)?; + writeln!(out, "\t:{i}")?; } context.eliminate_digit(d); @@ -118,7 +118,7 @@ fn pidigits(n: isize, out: &mut dyn io::Write) -> io::Result<()> { for _ in m..10 { write!(out, " ")?; } - writeln!(out, "\t:{}", n)?; + writeln!(out, "\t:{n}")?; } Ok(()) } diff --git a/src/bigint.rs b/src/bigint.rs index b4f84b9e..03cc6170 100644 --- a/src/bigint.rs +++ b/src/bigint.rs @@ -40,11 +40,11 @@ pub enum Sign { } impl Neg for Sign { - type Output = Sign; + type Output = Self; /// Negate `Sign` value. #[inline] - fn neg(self) -> Sign { + fn neg(self) -> Self { match self { Minus => Plus, NoSign => NoSign, @@ -64,7 +64,7 @@ pub struct BigInt { impl Clone for BigInt { #[inline] fn clone(&self) -> Self { - BigInt { + Self { sign: self.sign, data: self.data.clone(), } @@ -90,7 +90,7 @@ impl hash::Hash for BigInt { impl PartialEq for BigInt { #[inline] - fn eq(&self, other: &BigInt) -> bool { + fn eq(&self, other: &Self) -> bool { debug_assert!((self.sign != NoSign) ^ self.data.is_zero()); debug_assert!((other.sign != NoSign) ^ other.data.is_zero()); self.sign == other.sign && (self.sign == NoSign || self.data == other.data) @@ -101,14 +101,14 @@ impl Eq for BigInt {} impl PartialOrd for BigInt { #[inline] - fn partial_cmp(&self, other: &BigInt) -> Option { + fn partial_cmp(&self, other: &Self) -> Option { Some(self.cmp(other)) } } impl Ord for BigInt { #[inline] - fn cmp(&self, other: &BigInt) -> Ordering { + fn cmp(&self, other: &Self) -> Ordering { debug_assert!((self.sign != NoSign) ^ self.data.is_zero()); debug_assert!((other.sign != NoSign) ^ other.data.is_zero()); let scmp = self.sign.cmp(&other.sign); @@ -126,7 +126,7 @@ impl Ord for BigInt { impl Default for BigInt { #[inline] - fn default() -> BigInt { + fn default() -> Self { Self::ZERO } } @@ -174,9 +174,9 @@ impl fmt::UpperHex for BigInt { // ! 0 = !...0 00 = ...f ff = -1 // !+1 = !...0 01 = ...f fe = -2 impl Not for BigInt { - type Output = BigInt; + type Output = Self; - fn not(mut self) -> BigInt { + fn not(mut self) -> Self { match self.sign { NoSign | Plus => { self.data += 1u32; @@ -205,7 +205,7 @@ impl Not for &BigInt { impl Zero for BigInt { #[inline] - fn zero() -> BigInt { + fn zero() -> Self { Self::ZERO } @@ -228,8 +228,8 @@ impl ConstZero for BigInt { impl One for BigInt { #[inline] - fn one() -> BigInt { - BigInt { + fn one() -> Self { + Self { sign: Plus, data: BigUint::one(), } @@ -249,15 +249,15 @@ impl One for BigInt { impl Signed for BigInt { #[inline] - fn abs(&self) -> BigInt { + fn abs(&self) -> Self { match self.sign { Plus | NoSign => self.clone(), - Minus => BigInt::from(self.data.clone()), + Minus => Self::from(self.data.clone()), } } #[inline] - fn abs_sub(&self, other: &BigInt) -> BigInt { + fn abs_sub(&self, other: &Self) -> Self { if *self <= *other { Self::ZERO } else { @@ -266,10 +266,10 @@ impl Signed for BigInt { } #[inline] - fn signum(&self) -> BigInt { + fn signum(&self) -> Self { match self.sign { - Plus => BigInt::one(), - Minus => -BigInt::one(), + Plus => Self::one(), + Minus => -Self::one(), NoSign => Self::ZERO, } } @@ -321,10 +321,10 @@ impl_unsigned_abs!(i128, u128); impl_unsigned_abs!(isize, usize); impl Neg for BigInt { - type Output = BigInt; + type Output = Self; #[inline] - fn neg(mut self) -> BigInt { + fn neg(mut self) -> Self { self.sign = -self.sign; self } @@ -341,11 +341,11 @@ impl Neg for &BigInt { impl Integer for BigInt { #[inline] - fn div_rem(&self, other: &BigInt) -> (BigInt, BigInt) { + fn div_rem(&self, other: &Self) -> (Self, Self) { // r.sign == self.sign let (d_ui, r_ui) = self.data.div_rem(&other.data); - let d = BigInt::from_biguint(self.sign, d_ui); - let r = BigInt::from_biguint(self.sign, r_ui); + let d = Self::from_biguint(self.sign, d_ui); + let r = Self::from_biguint(self.sign, r_ui); if other.is_negative() { (-d, r) } else { @@ -354,12 +354,12 @@ impl Integer for BigInt { } #[inline] - fn div_floor(&self, other: &BigInt) -> BigInt { + fn div_floor(&self, other: &Self) -> Self { let (d_ui, m) = self.data.div_mod_floor(&other.data); - let d = BigInt::from(d_ui); + let d = Self::from(d_ui); match (self.sign, other.sign) { - (Plus, Plus) | (NoSign, Plus) | (Minus, Minus) => d, - (Plus, Minus) | (NoSign, Minus) | (Minus, Plus) => { + (Plus | NoSign, Plus) | (Minus, Minus) => d, + (Plus | NoSign, Minus) | (Minus, Plus) => { if m.is_zero() { -d } else { @@ -371,13 +371,13 @@ impl Integer for BigInt { } #[inline] - fn mod_floor(&self, other: &BigInt) -> BigInt { + fn mod_floor(&self, other: &Self) -> Self { // m.sign == other.sign let m_ui = self.data.mod_floor(&other.data); - let m = BigInt::from_biguint(other.sign, m_ui); + let m = Self::from_biguint(other.sign, m_ui); match (self.sign, other.sign) { - (Plus, Plus) | (NoSign, Plus) | (Minus, Minus) => m, - (Plus, Minus) | (NoSign, Minus) | (Minus, Plus) => { + (Plus | NoSign, Plus) | (Minus, Minus) => m, + (Plus | NoSign, Minus) | (Minus, Plus) => { if m.is_zero() { m } else { @@ -388,14 +388,14 @@ impl Integer for BigInt { } } - fn div_mod_floor(&self, other: &BigInt) -> (BigInt, BigInt) { + fn div_mod_floor(&self, other: &Self) -> (Self, Self) { // m.sign == other.sign let (d_ui, m_ui) = self.data.div_mod_floor(&other.data); - let d = BigInt::from(d_ui); - let m = BigInt::from_biguint(other.sign, m_ui); + let d = Self::from(d_ui); + let m = Self::from_biguint(other.sign, m_ui); match (self.sign, other.sign) { - (Plus, Plus) | (NoSign, Plus) | (Minus, Minus) => (d, m), - (Plus, Minus) | (NoSign, Minus) | (Minus, Plus) => { + (Plus | NoSign, Plus) | (Minus, Minus) => (d, m), + (Plus | NoSign, Minus) | (Minus, Plus) => { if m.is_zero() { (-d, m) } else { @@ -409,10 +409,10 @@ impl Integer for BigInt { #[inline] fn div_ceil(&self, other: &Self) -> Self { let (d_ui, m) = self.data.div_mod_floor(&other.data); - let d = BigInt::from(d_ui); + let d = Self::from(d_ui); match (self.sign, other.sign) { - (Plus, Minus) | (NoSign, Minus) | (Minus, Plus) => -d, - (Plus, Plus) | (NoSign, Plus) | (Minus, Minus) => { + (Plus | NoSign, Minus) | (Minus, Plus) => -d, + (Plus | NoSign, Plus) | (Minus, Minus) => { if m.is_zero() { d } else { @@ -427,45 +427,45 @@ impl Integer for BigInt { /// /// The result is always positive. #[inline] - fn gcd(&self, other: &BigInt) -> BigInt { - BigInt::from(self.data.gcd(&other.data)) + fn gcd(&self, other: &Self) -> Self { + Self::from(self.data.gcd(&other.data)) } /// Calculates the Lowest Common Multiple (LCM) of the number and `other`. #[inline] - fn lcm(&self, other: &BigInt) -> BigInt { - BigInt::from(self.data.lcm(&other.data)) + fn lcm(&self, other: &Self) -> Self { + Self::from(self.data.lcm(&other.data)) } /// Calculates the Greatest Common Divisor (GCD) and /// Lowest Common Multiple (LCM) together. #[inline] - fn gcd_lcm(&self, other: &BigInt) -> (BigInt, BigInt) { + fn gcd_lcm(&self, other: &Self) -> (Self, Self) { let (gcd, lcm) = self.data.gcd_lcm(&other.data); - (BigInt::from(gcd), BigInt::from(lcm)) + (Self::from(gcd), Self::from(lcm)) } /// Greatest common divisor, least common multiple, and Bézout coefficients. #[inline] - fn extended_gcd_lcm(&self, other: &BigInt) -> (num_integer::ExtendedGcd, BigInt) { + fn extended_gcd_lcm(&self, other: &Self) -> (num_integer::ExtendedGcd, Self) { let egcd = self.extended_gcd(other); let lcm = if egcd.gcd.is_zero() { Self::ZERO } else { - BigInt::from(&self.data / &egcd.gcd.data * &other.data) + Self::from(&self.data / &egcd.gcd.data * &other.data) }; (egcd, lcm) } /// Deprecated, use `is_multiple_of` instead. #[inline] - fn divides(&self, other: &BigInt) -> bool { + fn divides(&self, other: &Self) -> bool { self.is_multiple_of(other) } /// Returns `true` if the number is a multiple of `other`. #[inline] - fn is_multiple_of(&self, other: &BigInt) -> bool { + fn is_multiple_of(&self, other: &Self) -> bool { self.data.is_multiple_of(&other.data) } @@ -510,21 +510,20 @@ impl Roots for BigInt { fn nth_root(&self, n: u32) -> Self { assert!( !(self.is_negative() && n.is_even()), - "root of degree {} is imaginary", - n + "root of degree {n} is imaginary" ); - BigInt::from_biguint(self.sign, self.data.nth_root(n)) + Self::from_biguint(self.sign, self.data.nth_root(n)) } fn sqrt(&self) -> Self { assert!(!self.is_negative(), "square root is imaginary"); - BigInt::from_biguint(self.sign, self.data.sqrt()) + Self::from_biguint(self.sign, self.data.sqrt()) } fn cbrt(&self) -> Self { - BigInt::from_biguint(self.sign, self.data.cbrt()) + Self::from_biguint(self.sign, self.data.cbrt()) } } @@ -554,9 +553,10 @@ impl IntDigits for BigInt { } } -/// A generic trait for converting a value to a [`BigInt`]. This may return -/// `None` when converting from `f32` or `f64`, and will always succeed -/// when converting from any integer or unsigned primitive, or [`BigUint`]. +/// A generic trait for converting a value to a [`BigInt`]. +/// +/// This may return `None` when converting from `f32` or `f64`, and +/// will always succeed when converting from any integer or unsigned primitive, or [`BigUint`]. pub trait ToBigInt { /// Converts the value of `self` to a [`BigInt`]. fn to_bigint(&self) -> Option; @@ -564,7 +564,7 @@ pub trait ToBigInt { impl BigInt { /// A constant `BigInt` with value 0, useful for static initialization. - pub const ZERO: Self = BigInt { + pub const ZERO: Self = Self { sign: NoSign, data: BigUint::ZERO, }; @@ -572,31 +572,34 @@ impl BigInt { /// Creates and initializes a [`BigInt`]. /// /// The base 232 digits are ordered least significant digit first. + #[must_use] #[inline] - pub fn new(sign: Sign, digits: Vec) -> BigInt { - BigInt::from_biguint(sign, BigUint::new(digits)) + pub fn new(sign: Sign, digits: Vec) -> Self { + Self::from_biguint(sign, BigUint::new(digits)) } /// Creates and initializes a [`BigInt`]. /// /// The base 232 digits are ordered least significant digit first. + #[must_use] #[inline] - pub fn from_biguint(mut sign: Sign, mut data: BigUint) -> BigInt { + pub fn from_biguint(mut sign: Sign, mut data: BigUint) -> Self { if sign == NoSign { data.assign_from_slice(&[]); } else if data.is_zero() { sign = NoSign; } - BigInt { sign, data } + Self { sign, data } } /// Creates and initializes a [`BigInt`]. /// /// The base 232 digits are ordered least significant digit first. + #[must_use] #[inline] - pub fn from_slice(sign: Sign, slice: &[u32]) -> BigInt { - BigInt::from_biguint(sign, BigUint::from_slice(slice)) + pub fn from_slice(sign: Sign, slice: &[u32]) -> Self { + Self::from_biguint(sign, BigUint::from_slice(slice)) } /// Reinitializes a [`BigInt`]. @@ -630,33 +633,37 @@ impl BigInt { /// assert_eq!(BigInt::from_bytes_be(Sign::Plus, b"Hello world!"), /// BigInt::parse_bytes(b"22405534230753963835153736737", 10).unwrap()); /// ``` + #[must_use] #[inline] - pub fn from_bytes_be(sign: Sign, bytes: &[u8]) -> BigInt { - BigInt::from_biguint(sign, BigUint::from_bytes_be(bytes)) + pub fn from_bytes_be(sign: Sign, bytes: &[u8]) -> Self { + Self::from_biguint(sign, BigUint::from_bytes_be(bytes)) } /// Creates and initializes a [`BigInt`]. /// /// The bytes are in little-endian byte order. + #[must_use] #[inline] - pub fn from_bytes_le(sign: Sign, bytes: &[u8]) -> BigInt { - BigInt::from_biguint(sign, BigUint::from_bytes_le(bytes)) + pub fn from_bytes_le(sign: Sign, bytes: &[u8]) -> Self { + Self::from_biguint(sign, BigUint::from_bytes_le(bytes)) } /// Creates and initializes a [`BigInt`] from an array of bytes in /// two's complement binary representation. /// /// The digits are in big-endian base 28. + #[must_use] #[inline] - pub fn from_signed_bytes_be(digits: &[u8]) -> BigInt { + pub fn from_signed_bytes_be(digits: &[u8]) -> Self { convert::from_signed_bytes_be(digits) } /// Creates and initializes a [`BigInt`] from an array of bytes in two's complement. /// /// The digits are in little-endian base 28. + #[must_use] #[inline] - pub fn from_signed_bytes_le(digits: &[u8]) -> BigInt { + pub fn from_signed_bytes_le(digits: &[u8]) -> Self { convert::from_signed_bytes_le(digits) } @@ -671,10 +678,11 @@ impl BigInt { /// assert_eq!(BigInt::parse_bytes(b"ABCD", 16), ToBigInt::to_bigint(&0xABCD)); /// assert_eq!(BigInt::parse_bytes(b"G", 16), None); /// ``` + #[must_use] #[inline] - pub fn parse_bytes(buf: &[u8], radix: u32) -> Option { + pub fn parse_bytes(buf: &[u8], radix: u32) -> Option { let s = str::from_utf8(buf).ok()?; - BigInt::from_str_radix(s, radix).ok() + Self::from_str_radix(s, radix).ok() } /// Creates and initializes a [`BigInt`]. Each `u8` of the input slice is @@ -693,9 +701,10 @@ impl BigInt { /// let a = BigInt::from_radix_be(Sign::Minus, &inbase190, 190).unwrap(); /// assert_eq!(a.to_radix_be(190), (Sign:: Minus, inbase190)); /// ``` - pub fn from_radix_be(sign: Sign, buf: &[u8], radix: u32) -> Option { + #[must_use] + pub fn from_radix_be(sign: Sign, buf: &[u8], radix: u32) -> Option { let u = BigUint::from_radix_be(buf, radix)?; - Some(BigInt::from_biguint(sign, u)) + Some(Self::from_biguint(sign, u)) } /// Creates and initializes a [`BigInt`]. Each `u8` of the input slice is @@ -714,9 +723,10 @@ impl BigInt { /// let a = BigInt::from_radix_be(Sign::Minus, &inbase190, 190).unwrap(); /// assert_eq!(a.to_radix_be(190), (Sign::Minus, inbase190)); /// ``` - pub fn from_radix_le(sign: Sign, buf: &[u8], radix: u32) -> Option { + #[must_use] + pub fn from_radix_le(sign: Sign, buf: &[u8], radix: u32) -> Option { let u = BigUint::from_radix_le(buf, radix)?; - Some(BigInt::from_biguint(sign, u)) + Some(Self::from_biguint(sign, u)) } /// Returns the sign and the byte representation of the [`BigInt`] in big-endian byte order. @@ -729,6 +739,7 @@ impl BigInt { /// let i = -1125.to_bigint().unwrap(); /// assert_eq!(i.to_bytes_be(), (Sign::Minus, vec![4, 101])); /// ``` + #[must_use] #[inline] pub fn to_bytes_be(&self) -> (Sign, Vec) { (self.sign, self.data.to_bytes_be()) @@ -744,6 +755,7 @@ impl BigInt { /// let i = -1125.to_bigint().unwrap(); /// assert_eq!(i.to_bytes_le(), (Sign::Minus, vec![101, 4])); /// ``` + #[must_use] #[inline] pub fn to_bytes_le(&self) -> (Sign, Vec) { (self.sign, self.data.to_bytes_le()) @@ -763,6 +775,7 @@ impl BigInt { /// assert_eq!(BigInt::from(-112500000000i64).to_u32_digits(), (Sign::Minus, vec![830850304, 26])); /// assert_eq!(BigInt::from(112500000000i64).to_u32_digits(), (Sign::Plus, vec![830850304, 26])); /// ``` + #[must_use] #[inline] pub fn to_u32_digits(&self) -> (Sign, Vec) { (self.sign, self.data.to_u32_digits()) @@ -783,6 +796,7 @@ impl BigInt { /// assert_eq!(BigInt::from(112500000000i64).to_u64_digits(), (Sign::Plus, vec![112500000000])); /// assert_eq!(BigInt::from(1u128 << 64).to_u64_digits(), (Sign::Plus, vec![0, 1])); /// ``` + #[must_use] #[inline] pub fn to_u64_digits(&self) -> (Sign, Vec) { (self.sign, self.data.to_u64_digits()) @@ -802,6 +816,7 @@ impl BigInt { /// assert_eq!(BigInt::from(-112500000000i64).iter_u32_digits().collect::>(), vec![830850304, 26]); /// assert_eq!(BigInt::from(112500000000i64).iter_u32_digits().collect::>(), vec![830850304, 26]); /// ``` + #[must_use] #[inline] pub fn iter_u32_digits(&self) -> U32Digits<'_> { self.data.iter_u32_digits() @@ -822,6 +837,7 @@ impl BigInt { /// assert_eq!(BigInt::from(112500000000i64).iter_u64_digits().collect::>(), vec![112500000000u64]); /// assert_eq!(BigInt::from(1u128 << 64).iter_u64_digits().collect::>(), vec![0, 1]); /// ``` + #[must_use] #[inline] pub fn iter_u64_digits(&self) -> U64Digits<'_> { self.data.iter_u64_digits() @@ -837,6 +853,7 @@ impl BigInt { /// let i = -1125.to_bigint().unwrap(); /// assert_eq!(i.to_signed_bytes_be(), vec![251, 155]); /// ``` + #[must_use] #[inline] pub fn to_signed_bytes_be(&self) -> Vec { convert::to_signed_bytes_be(self) @@ -852,6 +869,7 @@ impl BigInt { /// let i = -1125.to_bigint().unwrap(); /// assert_eq!(i.to_signed_bytes_le(), vec![155, 251]); /// ``` + #[must_use] #[inline] pub fn to_signed_bytes_le(&self) -> Vec { convert::to_signed_bytes_le(self) @@ -868,6 +886,7 @@ impl BigInt { /// let i = BigInt::parse_bytes(b"ff", 16).unwrap(); /// assert_eq!(i.to_str_radix(16), "ff"); /// ``` + #[must_use] #[inline] pub fn to_str_radix(&self, radix: u32) -> String { let mut v = to_str_radix_reversed(&self.data, radix); @@ -894,6 +913,7 @@ impl BigInt { /// (Sign::Minus, vec![2, 94, 27])); /// // 0xFFFF = 65535 = 2*(159^2) + 94*159 + 27 /// ``` + #[must_use] #[inline] pub fn to_radix_be(&self, radix: u32) -> (Sign, Vec) { (self.sign, self.data.to_radix_be(radix)) @@ -913,6 +933,7 @@ impl BigInt { /// (Sign::Minus, vec![27, 94, 2])); /// // 0xFFFF = 65535 = 27 + 94*159 + 2*(159^2) /// ``` + #[must_use] #[inline] pub fn to_radix_le(&self, radix: u32) -> (Sign, Vec) { (self.sign, self.data.to_radix_le(radix)) @@ -929,8 +950,9 @@ impl BigInt { /// assert_eq!(BigInt::from(-4321).sign(), Sign::Minus); /// assert_eq!(BigInt::ZERO.sign(), Sign::NoSign); /// ``` + #[must_use] #[inline] - pub fn sign(&self) -> Sign { + pub const fn sign(&self) -> Sign { self.sign } @@ -946,8 +968,9 @@ impl BigInt { /// assert_eq!(BigInt::from(-4321).magnitude(), &BigUint::from(4321u32)); /// assert!(BigInt::ZERO.magnitude().is_zero()); /// ``` + #[must_use] #[inline] - pub fn magnitude(&self) -> &BigUint { + pub const fn magnitude(&self) -> &BigUint { &self.data } @@ -963,6 +986,7 @@ impl BigInt { /// assert_eq!(BigInt::from(-4321).into_parts(), (Sign::Minus, BigUint::from(4321u32))); /// assert_eq!(BigInt::ZERO.into_parts(), (Sign::NoSign, BigUint::ZERO)); /// ``` + #[must_use] #[inline] pub fn into_parts(self) -> (Sign, BigUint) { (self.sign, self.data) @@ -970,12 +994,14 @@ impl BigInt { /// Determines the fewest bits necessary to express the [`BigInt`], /// not including the sign. + #[must_use] #[inline] pub fn bits(&self) -> u64 { self.data.bits() } /// Converts this [`BigInt`] into a [`BigUint`], if it's not negative. + #[must_use] #[inline] pub fn to_biguint(&self) -> Option { match self.sign { @@ -985,23 +1011,27 @@ impl BigInt { } } + #[must_use] #[inline] - pub fn checked_add(&self, v: &BigInt) -> Option { + pub fn checked_add(&self, v: &Self) -> Option { Some(self + v) } + #[must_use] #[inline] - pub fn checked_sub(&self, v: &BigInt) -> Option { + pub fn checked_sub(&self, v: &Self) -> Option { Some(self - v) } + #[must_use] #[inline] - pub fn checked_mul(&self, v: &BigInt) -> Option { + pub fn checked_mul(&self, v: &Self) -> Option { Some(self * v) } + #[must_use] #[inline] - pub fn checked_div(&self, v: &BigInt) -> Option { + pub fn checked_div(&self, v: &Self) -> Option { if v.is_zero() { return None; } @@ -1009,6 +1039,7 @@ impl BigInt { } /// Returns `self ^ exponent`. + #[must_use] pub fn pow(&self, exponent: u32) -> Self { Pow::pow(self, exponent) } @@ -1021,6 +1052,7 @@ impl BigInt { /// or in the interval `(modulus, 0]` for `modulus < 0` /// /// Panics if the exponent is negative or the modulus is zero. + #[must_use] pub fn modpow(&self, exponent: &Self, modulus: &Self) -> Self { power::modpow(self, exponent, modulus) } @@ -1071,6 +1103,7 @@ impl BigInt { /// assert_eq!(x, BigInt::from(-106)); /// assert_eq!((&b * x).mod_floor(&n), &n + 1); /// ``` + #[must_use] pub fn modinv(&self, modulus: &Self) -> Option { let result = self.data.modinv(&modulus.data)?; // The sign of the result follows the modulus, like `mod_floor`. @@ -1080,35 +1113,43 @@ impl BigInt { (false, true) => (Minus, &modulus.data - result), (true, true) => (Minus, result), }; - Some(BigInt::from_biguint(sign, mag)) + Some(Self::from_biguint(sign, mag)) } /// Returns the truncated principal square root of `self` -- /// see [`num_integer::Roots::sqrt()`]. + #[must_use] pub fn sqrt(&self) -> Self { Roots::sqrt(self) } /// Returns the truncated principal cube root of `self` -- /// see [`num_integer::Roots::cbrt()`]. + #[must_use] pub fn cbrt(&self) -> Self { Roots::cbrt(self) } /// Returns the truncated principal `n`th root of `self` -- /// See [`num_integer::Roots::nth_root()`]. + #[must_use] pub fn nth_root(&self, n: u32) -> Self { Roots::nth_root(self, n) } /// Returns the number of least-significant bits that are zero, /// or `None` if the entire number is zero. + #[must_use] pub fn trailing_zeros(&self) -> Option { self.data.trailing_zeros() } /// Returns whether the bit in position `bit` is set, /// using the two's complement for negative numbers + /// + /// # Panics + /// - if `self` is negative **and** its magnitude is zero (this represents an invalid "negative zero", which cannot be created through the public API). + #[must_use] pub fn bit(&self, bit: u64) -> bool { if self.is_negative() { // Let the binary representation of a number be diff --git a/src/bigint/addition.rs b/src/bigint/addition.rs index 0d3a0e2a..1ce872a1 100644 --- a/src/bigint/addition.rs +++ b/src/bigint/addition.rs @@ -55,27 +55,27 @@ impl Add for &BigInt { } } -impl Add<&BigInt> for BigInt { - type Output = BigInt; +impl Add<&Self> for BigInt { + type Output = Self; #[inline] - fn add(self, other: &BigInt) -> BigInt { + fn add(self, other: &Self) -> Self { bigint_add!(self, self, self.data, other, other.clone(), &other.data) } } -impl Add for BigInt { - type Output = BigInt; +impl Add for BigInt { + type Output = Self; #[inline] - fn add(self, other: BigInt) -> BigInt { + fn add(self, other: Self) -> Self { bigint_add!(self, self, self.data, other, other, other.data) } } -impl AddAssign<&BigInt> for BigInt { +impl AddAssign<&Self> for BigInt { #[inline] - fn add_assign(&mut self, other: &BigInt) { + fn add_assign(&mut self, other: &Self) { let n = mem::replace(self, Self::ZERO); *self = n + other; } @@ -89,17 +89,17 @@ forward_all_scalar_binop_to_val_val_commutative!(impl Add for BigInt, add); forward_all_scalar_binop_to_val_val_commutative!(impl Add for BigInt, add); impl Add for BigInt { - type Output = BigInt; + type Output = Self; #[inline] - fn add(self, other: u32) -> BigInt { + fn add(self, other: u32) -> Self { match self.sign { NoSign => From::from(other), - Plus => BigInt::from(self.data + other), + Plus => Self::from(self.data + other), Minus => match self.data.cmp(&From::from(other)) { Equal => Self::ZERO, - Less => BigInt::from(other - self.data), - Greater => -BigInt::from(self.data - other), + Less => Self::from(other - self.data), + Greater => -Self::from(self.data - other), }, } } @@ -114,17 +114,17 @@ impl AddAssign for BigInt { } impl Add for BigInt { - type Output = BigInt; + type Output = Self; #[inline] - fn add(self, other: u64) -> BigInt { + fn add(self, other: u64) -> Self { match self.sign { NoSign => From::from(other), - Plus => BigInt::from(self.data + other), + Plus => Self::from(self.data + other), Minus => match self.data.cmp(&From::from(other)) { Equal => Self::ZERO, - Less => BigInt::from(other - self.data), - Greater => -BigInt::from(self.data - other), + Less => Self::from(other - self.data), + Greater => -Self::from(self.data - other), }, } } @@ -139,17 +139,17 @@ impl AddAssign for BigInt { } impl Add for BigInt { - type Output = BigInt; + type Output = Self; #[inline] - fn add(self, other: u128) -> BigInt { + fn add(self, other: u128) -> Self { match self.sign { - NoSign => BigInt::from(other), - Plus => BigInt::from(self.data + other), + NoSign => Self::from(other), + Plus => Self::from(self.data + other), Minus => match self.data.cmp(&From::from(other)) { Equal => Self::ZERO, - Less => BigInt::from(other - self.data), - Greater => -BigInt::from(self.data - other), + Less => Self::from(other - self.data), + Greater => -Self::from(self.data - other), }, } } @@ -167,10 +167,10 @@ forward_all_scalar_binop_to_val_val_commutative!(impl Add for BigInt, add); forward_all_scalar_binop_to_val_val_commutative!(impl Add for BigInt, add); impl Add for BigInt { - type Output = BigInt; + type Output = Self; #[inline] - fn add(self, other: i32) -> BigInt { + fn add(self, other: i32) -> Self { match other.checked_uabs() { Positive(u) => self + u, Negative(u) => self - u, @@ -188,10 +188,10 @@ impl AddAssign for BigInt { } impl Add for BigInt { - type Output = BigInt; + type Output = Self; #[inline] - fn add(self, other: i64) -> BigInt { + fn add(self, other: i64) -> Self { match other.checked_uabs() { Positive(u) => self + u, Negative(u) => self - u, @@ -209,10 +209,10 @@ impl AddAssign for BigInt { } impl Add for BigInt { - type Output = BigInt; + type Output = Self; #[inline] - fn add(self, other: i128) -> BigInt { + fn add(self, other: i128) -> Self { match other.checked_uabs() { Positive(u) => self + u, Negative(u) => self - u, @@ -231,7 +231,7 @@ impl AddAssign for BigInt { impl CheckedAdd for BigInt { #[inline] - fn checked_add(&self, v: &BigInt) -> Option { + fn checked_add(&self, v: &Self) -> Option { Some(self.add(v)) } } diff --git a/src/bigint/bits.rs b/src/bigint/bits.rs index ac4fe1de..e002ef91 100644 --- a/src/bigint/bits.rs +++ b/src/bigint/bits.rs @@ -60,7 +60,7 @@ fn bitand_neg_pos(a: &mut Vec, b: &[BigDigit]) { Equal => {} Less => { let extra = &b[a.len()..]; - a.extend(extra.iter().cloned()); + a.extend(extra.iter().copied()); } } } @@ -82,7 +82,7 @@ fn bitand_neg_neg(a: &mut Vec, b: &[BigDigit]) { debug_assert!(b.len() > a.len() || carry_b == 0); match Ord::cmp(&a.len(), &b.len()) { Greater => { - for ai in a[b.len()..].iter_mut() { + for ai in &mut a[b.len()..] { let twos_a = negate_carry(*ai, &mut carry_a); *ai = negate_carry(twos_a, &mut carry_and); } @@ -130,11 +130,11 @@ impl BitAnd<&BigInt> for &BigInt { } } -impl BitAnd<&BigInt> for BigInt { - type Output = BigInt; +impl BitAnd<&Self> for BigInt { + type Output = Self; #[inline] - fn bitand(mut self, other: &BigInt) -> BigInt { + fn bitand(mut self, other: &Self) -> Self { self &= other; self } @@ -142,8 +142,8 @@ impl BitAnd<&BigInt> for BigInt { forward_val_assign!(impl BitAndAssign for BigInt, bitand_assign); -impl BitAndAssign<&BigInt> for BigInt { - fn bitand_assign(&mut self, other: &BigInt) { +impl BitAndAssign<&Self> for BigInt { + fn bitand_assign(&mut self, other: &Self) { match (self.sign, other.sign) { (NoSign, _) => {} (_, NoSign) => self.set_zero(), @@ -211,7 +211,7 @@ fn bitor_neg_pos(a: &mut [BigDigit], b: &[BigDigit]) { } debug_assert!(a.len() > b.len() || carry_a == 0); if a.len() > b.len() { - for ai in a[b.len()..].iter_mut() { + for ai in &mut a[b.len()..] { let twos_a = negate_carry(*ai, &mut carry_a); *ai = negate_carry(twos_a, &mut carry_or); } @@ -270,11 +270,11 @@ impl BitOr<&BigInt> for &BigInt { } } -impl BitOr<&BigInt> for BigInt { - type Output = BigInt; +impl BitOr<&Self> for BigInt { + type Output = Self; #[inline] - fn bitor(mut self, other: &BigInt) -> BigInt { + fn bitor(mut self, other: &Self) -> Self { self |= other; self } @@ -282,8 +282,8 @@ impl BitOr<&BigInt> for BigInt { forward_val_assign!(impl BitOrAssign for BigInt, bitor_assign); -impl BitOrAssign<&BigInt> for BigInt { - fn bitor_assign(&mut self, other: &BigInt) { +impl BitOrAssign<&Self> for BigInt { + fn bitor_assign(&mut self, other: &Self) { match (self.sign, other.sign) { (_, NoSign) => {} (NoSign, _) => self.clone_from(other), @@ -318,7 +318,7 @@ fn bitxor_pos_neg(a: &mut Vec, b: &[BigDigit]) { debug_assert!(b.len() > a.len() || carry_b == 0); match Ord::cmp(&a.len(), &b.len()) { Greater => { - for ai in a[b.len()..].iter_mut() { + for ai in &mut a[b.len()..] { let twos_b = !0; *ai = negate_carry(*ai ^ twos_b, &mut carry_xor); } @@ -351,7 +351,7 @@ fn bitxor_neg_pos(a: &mut Vec, b: &[BigDigit]) { debug_assert!(a.len() > b.len() || carry_a == 0); match Ord::cmp(&a.len(), &b.len()) { Greater => { - for ai in a[b.len()..].iter_mut() { + for ai in &mut a[b.len()..] { let twos_a = negate_carry(*ai, &mut carry_a); *ai = negate_carry(twos_a, &mut carry_xor); } @@ -386,7 +386,7 @@ fn bitxor_neg_neg(a: &mut Vec, b: &[BigDigit]) { debug_assert!(b.len() > a.len() || carry_b == 0); match Ord::cmp(&a.len(), &b.len()) { Greater => { - for ai in a[b.len()..].iter_mut() { + for ai in &mut a[b.len()..] { let twos_a = negate_carry(*ai, &mut carry_a); let twos_b = !0; *ai = twos_a ^ twos_b; @@ -408,11 +408,11 @@ fn bitxor_neg_neg(a: &mut Vec, b: &[BigDigit]) { forward_all_binop_to_val_ref_commutative!(impl BitXor for BigInt, bitxor); -impl BitXor<&BigInt> for BigInt { - type Output = BigInt; +impl BitXor<&Self> for BigInt { + type Output = Self; #[inline] - fn bitxor(mut self, other: &BigInt) -> BigInt { + fn bitxor(mut self, other: &Self) -> Self { self ^= other; self } @@ -420,8 +420,8 @@ impl BitXor<&BigInt> for BigInt { forward_val_assign!(impl BitXorAssign for BigInt, bitxor_assign); -impl BitXorAssign<&BigInt> for BigInt { - fn bitxor_assign(&mut self, other: &BigInt) { +impl BitXorAssign<&Self> for BigInt { + fn bitxor_assign(&mut self, other: &Self) { match (self.sign, other.sign) { (_, NoSign) => {} (NoSign, _) => self.clone_from(other), diff --git a/src/bigint/convert.rs b/src/bigint/convert.rs index d0e28b67..8f5a1da1 100644 --- a/src/bigint/convert.rs +++ b/src/bigint/convert.rs @@ -14,8 +14,8 @@ impl FromStr for BigInt { type Err = ParseBigIntError; #[inline] - fn from_str(s: &str) -> Result { - BigInt::from_str_radix(s, 10) + fn from_str(s: &str) -> Result { + Self::from_str_radix(s, 10) } } @@ -24,17 +24,15 @@ impl Num for BigInt { /// Creates and initializes a [`BigInt`]. #[inline] - fn from_str_radix(mut s: &str, radix: u32) -> Result { - let sign = if let Some(tail) = s.strip_prefix('-') { + fn from_str_radix(mut s: &str, radix: u32) -> Result { + let sign = s.strip_prefix('-').map_or(Plus, |tail| { if !tail.starts_with('+') { - s = tail + s = tail; } Minus - } else { - Plus - }; + }); let bu = BigUint::from_str_radix(s, radix)?; - Ok(BigInt::from_biguint(sign, bu)) + Ok(Self::from_biguint(sign, bu)) } } @@ -142,32 +140,32 @@ impl_try_from_bigint!(i128, ToPrimitive::to_i128); impl FromPrimitive for BigInt { #[inline] - fn from_i64(n: i64) -> Option { - Some(BigInt::from(n)) + fn from_i64(n: i64) -> Option { + Some(Self::from(n)) } #[inline] - fn from_i128(n: i128) -> Option { - Some(BigInt::from(n)) + fn from_i128(n: i128) -> Option { + Some(Self::from(n)) } #[inline] - fn from_u64(n: u64) -> Option { - Some(BigInt::from(n)) + fn from_u64(n: u64) -> Option { + Some(Self::from(n)) } #[inline] - fn from_u128(n: u128) -> Option { - Some(BigInt::from(n)) + fn from_u128(n: u128) -> Option { + Some(Self::from(n)) } #[inline] - fn from_f64(n: f64) -> Option { + fn from_f64(n: f64) -> Option { if n >= 0.0 { - BigUint::from_f64(n).map(BigInt::from) + BigUint::from_f64(n).map(Self::from) } else { let x = BigUint::from_f64(-n)?; - Some(-BigInt::from(x)) + Some(-Self::from(x)) } } } @@ -176,10 +174,10 @@ impl From for BigInt { #[inline] fn from(n: i64) -> Self { if n >= 0 { - BigInt::from(n as u64) + Self::from(n as u64) } else { let u = u64::MAX - (n as u64) + 1; - BigInt { + Self { sign: Minus, data: BigUint::from(u), } @@ -191,10 +189,10 @@ impl From for BigInt { #[inline] fn from(n: i128) -> Self { if n >= 0 { - BigInt::from(n as u128) + Self::from(n as u128) } else { let u = u128::MAX - (n as u128) + 1; - BigInt { + Self { sign: Minus, data: BigUint::from(u), } @@ -222,7 +220,7 @@ impl From for BigInt { #[inline] fn from(n: u64) -> Self { if n > 0 { - BigInt { + Self { sign: Plus, data: BigUint::from(n), } @@ -236,7 +234,7 @@ impl From for BigInt { #[inline] fn from(n: u128) -> Self { if n > 0 { - BigInt { + Self { sign: Plus, data: BigUint::from(n), } @@ -268,7 +266,7 @@ impl From for BigInt { if n.is_zero() { Self::ZERO } else { - BigInt { + Self { sign: Plus, data: n, } @@ -312,7 +310,7 @@ impl TryFrom<&BigInt> for BigUint { type Error = TryFromBigIntError<()>; #[inline] - fn try_from(value: &BigInt) -> Result> { + fn try_from(value: &BigInt) -> Result> { value .to_biguint() .ok_or_else(|| TryFromBigIntError::new(())) @@ -323,7 +321,7 @@ impl TryFrom for BigUint { type Error = TryFromBigIntError; #[inline] - fn try_from(value: BigInt) -> Result> { + fn try_from(value: BigInt) -> Result> { if value.sign() == Sign::Minus { Err(TryFromBigIntError::new(value)) } else { @@ -409,7 +407,7 @@ pub(super) fn from_signed_bytes_le(digits: &[u8]) -> BigInt { #[inline] pub(super) fn to_signed_bytes_be(x: &BigInt) -> Vec { let mut bytes = x.data.to_bytes_be(); - let first_byte = bytes.first().cloned().unwrap_or(0); + let first_byte = bytes.first().copied().unwrap_or(0); if first_byte > 0x7f && !(first_byte == 0x80 && bytes.iter().skip(1).all(Zero::is_zero) && x.sign == Sign::Minus) { @@ -425,7 +423,7 @@ pub(super) fn to_signed_bytes_be(x: &BigInt) -> Vec { #[inline] pub(super) fn to_signed_bytes_le(x: &BigInt) -> Vec { let mut bytes = x.data.to_bytes_le(); - let last_byte = bytes.last().cloned().unwrap_or(0); + let last_byte = bytes.last().copied().unwrap_or(0); if last_byte > 0x7f && !(last_byte == 0x80 && bytes.iter().rev().skip(1).all(Zero::is_zero) @@ -444,14 +442,14 @@ pub(super) fn to_signed_bytes_le(x: &BigInt) -> Vec { /// in little-endian byte order. #[inline] fn twos_complement_le(digits: &mut [u8]) { - twos_complement(digits) + twos_complement(digits); } /// Perform in-place two's complement of the given binary representation /// in big-endian byte order. #[inline] fn twos_complement_be(digits: &mut [u8]) { - twos_complement(digits.iter_mut().rev()) + twos_complement(digits.iter_mut().rev()); } /// Perform in-place two's complement of the given digit iterator diff --git a/src/bigint/division.rs b/src/bigint/division.rs index 0d4d23f3..3b14f126 100644 --- a/src/bigint/division.rs +++ b/src/bigint/division.rs @@ -20,9 +20,9 @@ impl Div<&BigInt> for &BigInt { } } -impl DivAssign<&BigInt> for BigInt { +impl DivAssign<&Self> for BigInt { #[inline] - fn div_assign(&mut self, other: &BigInt) { + fn div_assign(&mut self, other: &Self) { *self = &*self / other; } } @@ -35,11 +35,11 @@ forward_all_scalar_binop_to_val_val!(impl Div for BigInt, div); forward_all_scalar_binop_to_val_val!(impl Div for BigInt, div); impl Div for BigInt { - type Output = BigInt; + type Output = Self; #[inline] - fn div(self, other: u32) -> BigInt { - BigInt::from_biguint(self.sign, self.data / other) + fn div(self, other: u32) -> Self { + Self::from_biguint(self.sign, self.data / other) } } @@ -63,11 +63,11 @@ impl Div for u32 { } impl Div for BigInt { - type Output = BigInt; + type Output = Self; #[inline] - fn div(self, other: u64) -> BigInt { - BigInt::from_biguint(self.sign, self.data / other) + fn div(self, other: u64) -> Self { + Self::from_biguint(self.sign, self.data / other) } } @@ -91,11 +91,11 @@ impl Div for u64 { } impl Div for BigInt { - type Output = BigInt; + type Output = Self; #[inline] - fn div(self, other: u128) -> BigInt { - BigInt::from_biguint(self.sign, self.data / other) + fn div(self, other: u128) -> Self { + Self::from_biguint(self.sign, self.data / other) } } @@ -123,10 +123,10 @@ forward_all_scalar_binop_to_val_val!(impl Div for BigInt, div); forward_all_scalar_binop_to_val_val!(impl Div for BigInt, div); impl Div for BigInt { - type Output = BigInt; + type Output = Self; #[inline] - fn div(self, other: i32) -> BigInt { + fn div(self, other: i32) -> Self { match other.checked_uabs() { Positive(u) => self / u, Negative(u) => -self / u, @@ -160,10 +160,10 @@ impl Div for i32 { } impl Div for BigInt { - type Output = BigInt; + type Output = Self; #[inline] - fn div(self, other: i64) -> BigInt { + fn div(self, other: i64) -> Self { match other.checked_uabs() { Positive(u) => self / u, Negative(u) => -self / u, @@ -197,10 +197,10 @@ impl Div for i64 { } impl Div for BigInt { - type Output = BigInt; + type Output = Self; #[inline] - fn div(self, other: i128) -> BigInt { + fn div(self, other: i128) -> Self { match other.checked_uabs() { Positive(u) => self / u, Negative(u) => -self / u, @@ -240,20 +240,24 @@ impl Rem<&BigInt> for &BigInt { #[inline] fn rem(self, other: &BigInt) -> BigInt { - if let Some(other) = other.to_u32() { - self % other - } else if let Some(other) = other.to_i32() { - self % other - } else { - let (_, r) = self.div_rem(other); - r - } + other.to_u32().map_or_else( + || { + other.to_i32().map_or_else( + || { + let (_, r) = self.div_rem(other); + r + }, + |other| self % other, + ) + }, + |other| self % other, + ) } } -impl RemAssign<&BigInt> for BigInt { +impl RemAssign<&Self> for BigInt { #[inline] - fn rem_assign(&mut self, other: &BigInt) { + fn rem_assign(&mut self, other: &Self) { *self = &*self % other; } } @@ -266,11 +270,11 @@ forward_all_scalar_binop_to_val_val!(impl Rem for BigInt, rem); forward_all_scalar_binop_to_val_val!(impl Rem for BigInt, rem); impl Rem for BigInt { - type Output = BigInt; + type Output = Self; #[inline] - fn rem(self, other: u32) -> BigInt { - BigInt::from_biguint(self.sign, self.data % other) + fn rem(self, other: u32) -> Self { + Self::from_biguint(self.sign, self.data % other) } } @@ -294,11 +298,11 @@ impl Rem for u32 { } impl Rem for BigInt { - type Output = BigInt; + type Output = Self; #[inline] - fn rem(self, other: u64) -> BigInt { - BigInt::from_biguint(self.sign, self.data % other) + fn rem(self, other: u64) -> Self { + Self::from_biguint(self.sign, self.data % other) } } @@ -322,11 +326,11 @@ impl Rem for u64 { } impl Rem for BigInt { - type Output = BigInt; + type Output = Self; #[inline] - fn rem(self, other: u128) -> BigInt { - BigInt::from_biguint(self.sign, self.data % other) + fn rem(self, other: u128) -> Self { + Self::from_biguint(self.sign, self.data % other) } } @@ -354,10 +358,10 @@ forward_all_scalar_binop_to_val_val!(impl Rem for BigInt, rem); forward_all_scalar_binop_to_val_val!(impl Rem for BigInt, rem); impl Rem for BigInt { - type Output = BigInt; + type Output = Self; #[inline] - fn rem(self, other: i32) -> BigInt { + fn rem(self, other: i32) -> Self { self % other.unsigned_abs() } } @@ -382,10 +386,10 @@ impl Rem for i32 { } impl Rem for BigInt { - type Output = BigInt; + type Output = Self; #[inline] - fn rem(self, other: i64) -> BigInt { + fn rem(self, other: i64) -> Self { self % other.unsigned_abs() } } @@ -410,10 +414,10 @@ impl Rem for i64 { } impl Rem for BigInt { - type Output = BigInt; + type Output = Self; #[inline] - fn rem(self, other: i128) -> BigInt { + fn rem(self, other: i128) -> Self { self % other.unsigned_abs() } } @@ -439,7 +443,7 @@ impl Rem for i128 { impl CheckedDiv for BigInt { #[inline] - fn checked_div(&self, v: &BigInt) -> Option { + fn checked_div(&self, v: &Self) -> Option { if v.is_zero() { return None; } @@ -449,7 +453,7 @@ impl CheckedDiv for BigInt { impl CheckedEuclid for BigInt { #[inline] - fn checked_div_euclid(&self, v: &BigInt) -> Option { + fn checked_div_euclid(&self, v: &Self) -> Option { if v.is_zero() { return None; } @@ -457,7 +461,7 @@ impl CheckedEuclid for BigInt { } #[inline] - fn checked_rem_euclid(&self, v: &BigInt) -> Option { + fn checked_rem_euclid(&self, v: &Self) -> Option { if v.is_zero() { return None; } @@ -471,7 +475,7 @@ impl CheckedEuclid for BigInt { impl Euclid for BigInt { #[inline] - fn div_euclid(&self, v: &BigInt) -> BigInt { + fn div_euclid(&self, v: &Self) -> Self { let (q, r) = self.div_rem(v); if r.is_negative() { if v.is_positive() { @@ -485,7 +489,7 @@ impl Euclid for BigInt { } #[inline] - fn rem_euclid(&self, v: &BigInt) -> BigInt { + fn rem_euclid(&self, v: &Self) -> Self { let r = self % v; if r.is_negative() { if v.is_positive() { diff --git a/src/bigint/multiplication.rs b/src/bigint/multiplication.rs index 82e64c28..44558f01 100644 --- a/src/bigint/multiplication.rs +++ b/src/bigint/multiplication.rs @@ -8,11 +8,11 @@ use core::iter::Product; use core::ops::{Mul, MulAssign}; use num_traits::{CheckedMul, One, Zero}; -impl Mul for Sign { - type Output = Sign; +impl Mul for Sign { + type Output = Self; #[inline] - fn mul(self, other: Sign) -> Sign { + fn mul(self, other: Self) -> Self { match (self, other) { (NoSign, _) | (_, NoSign) => NoSign, (Plus, Plus) | (Minus, Minus) => Plus, @@ -72,11 +72,11 @@ forward_all_scalar_binop_to_val_val_commutative!(impl Mul for BigInt, mul); forward_all_scalar_binop_to_val_val_commutative!(impl Mul for BigInt, mul); impl Mul for BigInt { - type Output = BigInt; + type Output = Self; #[inline] - fn mul(self, other: u32) -> BigInt { - BigInt::from_biguint(self.sign, self.data * other) + fn mul(self, other: u32) -> Self { + Self::from_biguint(self.sign, self.data * other) } } @@ -91,11 +91,11 @@ impl MulAssign for BigInt { } impl Mul for BigInt { - type Output = BigInt; + type Output = Self; #[inline] - fn mul(self, other: u64) -> BigInt { - BigInt::from_biguint(self.sign, self.data * other) + fn mul(self, other: u64) -> Self { + Self::from_biguint(self.sign, self.data * other) } } @@ -110,11 +110,11 @@ impl MulAssign for BigInt { } impl Mul for BigInt { - type Output = BigInt; + type Output = Self; #[inline] - fn mul(self, other: u128) -> BigInt { - BigInt::from_biguint(self.sign, self.data * other) + fn mul(self, other: u128) -> Self { + Self::from_biguint(self.sign, self.data * other) } } @@ -133,10 +133,10 @@ forward_all_scalar_binop_to_val_val_commutative!(impl Mul for BigInt, mul); forward_all_scalar_binop_to_val_val_commutative!(impl Mul for BigInt, mul); impl Mul for BigInt { - type Output = BigInt; + type Output = Self; #[inline] - fn mul(self, other: i32) -> BigInt { + fn mul(self, other: i32) -> Self { match other.checked_uabs() { Positive(u) => self * u, Negative(u) => -self * u, @@ -158,10 +158,10 @@ impl MulAssign for BigInt { } impl Mul for BigInt { - type Output = BigInt; + type Output = Self; #[inline] - fn mul(self, other: i64) -> BigInt { + fn mul(self, other: i64) -> Self { match other.checked_uabs() { Positive(u) => self * u, Negative(u) => -self * u, @@ -183,10 +183,10 @@ impl MulAssign for BigInt { } impl Mul for BigInt { - type Output = BigInt; + type Output = Self; #[inline] - fn mul(self, other: i128) -> BigInt { + fn mul(self, other: i128) -> Self { match other.checked_uabs() { Positive(u) => self * u, Negative(u) => -self * u, @@ -209,7 +209,7 @@ impl MulAssign for BigInt { impl CheckedMul for BigInt { #[inline] - fn checked_mul(&self, v: &BigInt) -> Option { + fn checked_mul(&self, v: &Self) -> Option { Some(self.mul(v)) } } diff --git a/src/bigint/shift.rs b/src/bigint/shift.rs index 22bb7443..5b18af6f 100644 --- a/src/bigint/shift.rs +++ b/src/bigint/shift.rs @@ -100,7 +100,7 @@ impl_shift! { i8, i16, i32, i64, i128, isize } fn shr_round_down(i: &BigInt, shift: T) -> bool { if i.is_negative() { let zeros = i.trailing_zeros().expect("negative values are non-zero"); - shift > T::zero() && shift.to_u64().map(|shift| zeros < shift).unwrap_or(true) + shift > T::zero() && shift.to_u64().map_or(true, |shift| zeros < shift) } else { false } diff --git a/src/bigint/subtraction.rs b/src/bigint/subtraction.rs index ef778549..cacb4fcc 100644 --- a/src/bigint/subtraction.rs +++ b/src/bigint/subtraction.rs @@ -54,27 +54,27 @@ impl Sub for &BigInt { } } -impl Sub<&BigInt> for BigInt { - type Output = BigInt; +impl Sub<&Self> for BigInt { + type Output = Self; #[inline] - fn sub(self, other: &BigInt) -> BigInt { + fn sub(self, other: &Self) -> Self { bigint_sub!(self, self, self.data, other, other.clone(), &other.data) } } -impl Sub for BigInt { - type Output = BigInt; +impl Sub for BigInt { + type Output = Self; #[inline] - fn sub(self, other: BigInt) -> BigInt { + fn sub(self, other: Self) -> Self { bigint_sub!(self, self, self.data, other, other, other.data) } } -impl SubAssign<&BigInt> for BigInt { +impl SubAssign<&Self> for BigInt { #[inline] - fn sub_assign(&mut self, other: &BigInt) { + fn sub_assign(&mut self, other: &Self) { let n = mem::replace(self, Self::ZERO); *self = n - other; } @@ -88,17 +88,17 @@ forward_all_scalar_binop_to_val_val!(impl Sub for BigInt, sub); forward_all_scalar_binop_to_val_val!(impl Sub for BigInt, sub); impl Sub for BigInt { - type Output = BigInt; + type Output = Self; #[inline] - fn sub(self, other: u32) -> BigInt { + fn sub(self, other: u32) -> Self { match self.sign { - NoSign => -BigInt::from(other), - Minus => -BigInt::from(self.data + other), + NoSign => -Self::from(other), + Minus => -Self::from(self.data + other), Plus => match self.data.cmp(&From::from(other)) { Equal => Self::ZERO, - Greater => BigInt::from(self.data - other), - Less => -BigInt::from(other - self.data), + Greater => Self::from(self.data - other), + Less => -Self::from(other - self.data), }, } } @@ -139,17 +139,17 @@ impl Sub for u128 { } impl Sub for BigInt { - type Output = BigInt; + type Output = Self; #[inline] - fn sub(self, other: u64) -> BigInt { + fn sub(self, other: u64) -> Self { match self.sign { - NoSign => -BigInt::from(other), - Minus => -BigInt::from(self.data + other), + NoSign => -Self::from(other), + Minus => -Self::from(self.data + other), Plus => match self.data.cmp(&From::from(other)) { Equal => Self::ZERO, - Greater => BigInt::from(self.data - other), - Less => -BigInt::from(other - self.data), + Greater => Self::from(self.data - other), + Less => -Self::from(other - self.data), }, } } @@ -164,17 +164,17 @@ impl SubAssign for BigInt { } impl Sub for BigInt { - type Output = BigInt; + type Output = Self; #[inline] - fn sub(self, other: u128) -> BigInt { + fn sub(self, other: u128) -> Self { match self.sign { - NoSign => -BigInt::from(other), - Minus => -BigInt::from(self.data + other), + NoSign => -Self::from(other), + Minus => -Self::from(self.data + other), Plus => match self.data.cmp(&From::from(other)) { Equal => Self::ZERO, - Greater => BigInt::from(self.data - other), - Less => -BigInt::from(other - self.data), + Greater => Self::from(self.data - other), + Less => -Self::from(other - self.data), }, } } @@ -193,10 +193,10 @@ forward_all_scalar_binop_to_val_val!(impl Sub for BigInt, sub); forward_all_scalar_binop_to_val_val!(impl Sub for BigInt, sub); impl Sub for BigInt { - type Output = BigInt; + type Output = Self; #[inline] - fn sub(self, other: i32) -> BigInt { + fn sub(self, other: i32) -> Self { match other.checked_uabs() { Positive(u) => self - u, Negative(u) => self + u, @@ -226,10 +226,10 @@ impl Sub for i32 { } impl Sub for BigInt { - type Output = BigInt; + type Output = Self; #[inline] - fn sub(self, other: i64) -> BigInt { + fn sub(self, other: i64) -> Self { match other.checked_uabs() { Positive(u) => self - u, Negative(u) => self + u, @@ -259,10 +259,10 @@ impl Sub for i64 { } impl Sub for BigInt { - type Output = BigInt; + type Output = Self; #[inline] - fn sub(self, other: i128) -> BigInt { + fn sub(self, other: i128) -> Self { match other.checked_uabs() { Positive(u) => self - u, Negative(u) => self + u, @@ -294,7 +294,7 @@ impl Sub for i128 { impl CheckedSub for BigInt { #[inline] - fn checked_sub(&self, v: &BigInt) -> Option { + fn checked_sub(&self, v: &Self) -> Option { Some(self.sub(v)) } } diff --git a/src/bigrand.rs b/src/bigrand.rs index e5cbacdb..f93a624b 100644 --- a/src/bigrand.rs +++ b/src/bigrand.rs @@ -2,12 +2,12 @@ #![cfg(feature = "rand")] #![cfg_attr(docsrs, doc(cfg(feature = "rand")))] -use rand::distributions::uniform::{SampleBorrow, SampleUniform, UniformSampler}; +use rand::distr::uniform::{Error as RandError, SampleBorrow, SampleUniform, UniformSampler}; use rand::prelude::*; use crate::BigInt; use crate::BigUint; -use crate::Sign::*; +use crate::Sign::{Minus, NoSign, Plus}; use crate::biguint::biguint_from_vec; @@ -19,28 +19,28 @@ use num_traits::{ToPrimitive, Zero}; /// The `rand` feature must be enabled to use this. See crate-level documentation for details. pub trait RandBigInt { /// Generate a random [`BigUint`] of the given bit size. - fn gen_biguint(&mut self, bit_size: u64) -> BigUint; + fn random_biguint(&mut self, bit_size: u64) -> BigUint; - /// Generate a random [ BigInt`] of the given bit size. - fn gen_bigint(&mut self, bit_size: u64) -> BigInt; + /// Generate a random [`BigInt`] of the given bit size. + fn random_bigint(&mut self, bit_size: u64) -> BigInt; /// Generate a random [`BigUint`] less than the given bound. Fails /// when the bound is zero. - fn gen_biguint_below(&mut self, bound: &BigUint) -> BigUint; + fn random_biguint_below(&mut self, bound: &BigUint) -> BigUint; /// Generate a random [`BigUint`] within the given range. The lower /// bound is inclusive; the upper bound is exclusive. Fails when /// the upper bound is not greater than the lower bound. - fn gen_biguint_range(&mut self, lbound: &BigUint, ubound: &BigUint) -> BigUint; + fn random_biguint_range(&mut self, lbound: &BigUint, ubound: &BigUint) -> BigUint; /// Generate a random [`BigInt`] within the given range. The lower /// bound is inclusive; the upper bound is exclusive. Fails when /// the upper bound is not greater than the lower bound. - fn gen_bigint_range(&mut self, lbound: &BigInt, ubound: &BigInt) -> BigInt; + fn random_bigint_range(&mut self, lbound: &BigInt, ubound: &BigInt) -> BigInt; } -fn gen_bits(rng: &mut R, data: &mut [u32], rem: u64) { - // `fill` is faster than many `gen::` calls +fn random_bits(rng: &mut R, data: &mut [u32], rem: u64) { + // `fill` is faster than many `random::` calls rng.fill(data); if rem > 0 { let last = data.len() - 1; @@ -48,23 +48,23 @@ fn gen_bits(rng: &mut R, data: &mut [u32], rem: u64) { } } -impl RandBigInt for R { +impl RandBigInt for R { cfg_digit!( - fn gen_biguint(&mut self, bit_size: u64) -> BigUint { + fn random_biguint(&mut self, bit_size: u64) -> BigUint { let (digits, rem) = bit_size.div_rem(&32); let len = (digits + (rem > 0) as u64) .to_usize() .expect("capacity overflow"); let mut data = vec![0u32; len]; - gen_bits(self, &mut data, rem); + random_bits(self, &mut data, rem); biguint_from_vec(data) } - fn gen_biguint(&mut self, bit_size: u64) -> BigUint { + fn random_biguint(&mut self, bit_size: u64) -> BigUint { use core::slice; let (digits, rem) = bit_size.div_rem(&32); - let len = (digits + (rem > 0) as u64) + let len = (digits + u64::from(rem > 0)) .to_usize() .expect("capacity overflow"); let native_digits = Integer::div_ceil(&bit_size, &64); @@ -72,10 +72,10 @@ impl RandBigInt for R { let mut data = vec![0u64; native_len]; unsafe { // Generate bits in a `&mut [u32]` slice for value stability - let ptr = data.as_mut_ptr() as *mut u32; + let ptr = data.as_mut_ptr().cast::(); debug_assert!(native_len * 2 >= len); let data = slice::from_raw_parts_mut(ptr, len); - gen_bits(self, data, rem); + random_bits(self, data, rem); } #[cfg(target_endian = "big")] for digit in &mut data { @@ -86,22 +86,21 @@ impl RandBigInt for R { } ); - fn gen_bigint(&mut self, bit_size: u64) -> BigInt { + fn random_bigint(&mut self, bit_size: u64) -> BigInt { loop { // Generate a random BigUint... - let biguint = self.gen_biguint(bit_size); + let biguint = self.random_biguint(bit_size); // ...and then randomly assign it a Sign... let sign = if biguint.is_zero() { // ...except that if the BigUint is zero, we need to try // again with probability 0.5. This is because otherwise, // the probability of generating a zero BigInt would be // double that of any other number. - if self.gen() { + if self.random() { continue; - } else { - NoSign } - } else if self.gen() { + NoSign + } else if self.random() { Plus } else { Minus @@ -110,35 +109,35 @@ impl RandBigInt for R { } } - fn gen_biguint_below(&mut self, bound: &BigUint) -> BigUint { + fn random_biguint_below(&mut self, bound: &BigUint) -> BigUint { assert!(!bound.is_zero()); let bits = bound.bits(); loop { - let n = self.gen_biguint(bits); + let n = self.random_biguint(bits); if n < *bound { return n; } } } - fn gen_biguint_range(&mut self, lbound: &BigUint, ubound: &BigUint) -> BigUint { + fn random_biguint_range(&mut self, lbound: &BigUint, ubound: &BigUint) -> BigUint { assert!(*lbound < *ubound); if lbound.is_zero() { - self.gen_biguint_below(ubound) + self.random_biguint_below(ubound) } else { - lbound + self.gen_biguint_below(&(ubound - lbound)) + lbound + self.random_biguint_below(&(ubound - lbound)) } } - fn gen_bigint_range(&mut self, lbound: &BigInt, ubound: &BigInt) -> BigInt { + fn random_bigint_range(&mut self, lbound: &BigInt, ubound: &BigInt) -> BigInt { assert!(*lbound < *ubound); if lbound.is_zero() { - BigInt::from(self.gen_biguint_below(ubound.magnitude())) + BigInt::from(self.random_biguint_below(ubound.magnitude())) } else if ubound.is_zero() { - lbound + BigInt::from(self.gen_biguint_below(lbound.magnitude())) + lbound + BigInt::from(self.random_biguint_below(lbound.magnitude())) } else { let delta = ubound - lbound; - lbound + BigInt::from(self.gen_biguint_below(delta.magnitude())) + lbound + BigInt::from(self.random_biguint_below(delta.magnitude())) } } } @@ -154,44 +153,54 @@ impl UniformSampler for UniformBigUint { type X = BigUint; #[inline] - fn new(low_b: B1, high_b: B2) -> Self + fn new(low_b: B1, high_b: B2) -> Result where B1: SampleBorrow + Sized, B2: SampleBorrow + Sized, { let low = low_b.borrow(); let high = high_b.borrow(); - assert!(low < high); - UniformBigUint { - len: high - low, - base: low.clone(), + if low < high { + Ok(Self { + len: high - low, + base: low.clone(), + }) + } else { + Err(RandError::EmptyRange) } } #[inline] - fn new_inclusive(low_b: B1, high_b: B2) -> Self + fn new_inclusive(low_b: B1, high_b: B2) -> Result where B1: SampleBorrow + Sized, B2: SampleBorrow + Sized, { let low = low_b.borrow(); let high = high_b.borrow(); - assert!(low <= high); - Self::new(low, high + 1u32) + if low <= high { + Self::new(low, high + 1u32) + } else { + Err(RandError::EmptyRange) + } } #[inline] fn sample(&self, rng: &mut R) -> Self::X { - &self.base + rng.gen_biguint_below(&self.len) + &self.base + rng.random_biguint_below(&self.len) } #[inline] - fn sample_single(low: B1, high: B2, rng: &mut R) -> Self::X + fn sample_single( + low: B1, + high: B2, + rng: &mut R, + ) -> Result where B1: SampleBorrow + Sized, B2: SampleBorrow + Sized, { - rng.gen_biguint_range(low.borrow(), high.borrow()) + Ok(rng.random_biguint_range(low.borrow(), high.borrow())) } } @@ -210,44 +219,54 @@ impl UniformSampler for UniformBigInt { type X = BigInt; #[inline] - fn new(low_b: B1, high_b: B2) -> Self + fn new(low_b: B1, high_b: B2) -> Result where B1: SampleBorrow + Sized, B2: SampleBorrow + Sized, { let low = low_b.borrow(); let high = high_b.borrow(); - assert!(low < high); - UniformBigInt { - len: (high - low).into_parts().1, - base: low.clone(), + if low < high { + Ok(Self { + len: (high - low).into_parts().1, + base: low.clone(), + }) + } else { + Err(RandError::EmptyRange) } } #[inline] - fn new_inclusive(low_b: B1, high_b: B2) -> Self + fn new_inclusive(low_b: B1, high_b: B2) -> Result where B1: SampleBorrow + Sized, B2: SampleBorrow + Sized, { let low = low_b.borrow(); let high = high_b.borrow(); - assert!(low <= high); - Self::new(low, high + 1u32) + if low <= high { + Self::new(low, high + 1u32) + } else { + Err(RandError::EmptyRange) + } } #[inline] fn sample(&self, rng: &mut R) -> Self::X { - &self.base + BigInt::from(rng.gen_biguint_below(&self.len)) + &self.base + BigInt::from(rng.random_biguint_below(&self.len)) } #[inline] - fn sample_single(low: B1, high: B2, rng: &mut R) -> Self::X + fn sample_single( + low: B1, + high: B2, + rng: &mut R, + ) -> Result where B1: SampleBorrow + Sized, B2: SampleBorrow + Sized, { - rng.gen_bigint_range(low.borrow(), high.borrow()) + Ok(rng.random_bigint_range(low.borrow(), high.borrow())) } } @@ -264,22 +283,48 @@ pub struct RandomBits { } impl RandomBits { + #[must_use] #[inline] - pub fn new(bits: u64) -> RandomBits { - RandomBits { bits } + pub const fn new(bits: u64) -> Self { + Self { bits } } } impl Distribution for RandomBits { #[inline] fn sample(&self, rng: &mut R) -> BigUint { - rng.gen_biguint(self.bits) + rng.random_biguint(self.bits) } } impl Distribution for RandomBits { #[inline] fn sample(&self, rng: &mut R) -> BigInt { - rng.gen_bigint(self.bits) + rng.random_bigint(self.bits) + } +} + +#[cfg(test)] +mod test { + use super::*; + + #[test] + fn test_rand_biguint_range_works() { + let mut rng = rand::rng(); + let minval = BigUint::zero(); + let maxval = BigUint::from(420u16); + let a_random_biguint = rng.random_biguint_range(&minval, &maxval); + assert!(a_random_biguint >= minval); + assert!(a_random_biguint < maxval); + } + + #[test] + fn test_rand_bigint_range_works() { + let mut rng = rand::rng(); + let minval = BigInt::from(-420i16); + let maxval = BigInt::from(420i16); + let a_random_bigint = rng.random_bigint_range(&minval, &maxval); + assert!(a_random_bigint >= minval); + assert!(a_random_bigint < maxval); } } diff --git a/src/biguint.rs b/src/biguint.rs index 196fa323..b44e3470 100644 --- a/src/biguint.rs +++ b/src/biguint.rs @@ -96,7 +96,7 @@ fn cmp_slice(a: &[BigDigit], b: &[BigDigit]) -> Ordering { impl Default for BigUint { #[inline] - fn default() -> BigUint { + fn default() -> Self { Self::ZERO } } @@ -141,7 +141,7 @@ impl fmt::Octal for BigUint { impl Zero for BigUint { #[inline] - fn zero() -> BigUint { + fn zero() -> Self { Self::ZERO } @@ -163,8 +163,8 @@ impl ConstZero for BigUint { impl One for BigUint { #[inline] - fn one() -> BigUint { - BigUint { data: vec![1] } + fn one() -> Self { + Self { data: vec![1] } } #[inline] @@ -183,29 +183,29 @@ impl Unsigned for BigUint {} impl Integer for BigUint { #[inline] - fn div_rem(&self, other: &BigUint) -> (BigUint, BigUint) { + fn div_rem(&self, other: &Self) -> (Self, Self) { division::div_rem_ref(self, other) } #[inline] - fn div_floor(&self, other: &BigUint) -> BigUint { + fn div_floor(&self, other: &Self) -> Self { let (d, _) = division::div_rem_ref(self, other); d } #[inline] - fn mod_floor(&self, other: &BigUint) -> BigUint { + fn mod_floor(&self, other: &Self) -> Self { let (_, m) = division::div_rem_ref(self, other); m } #[inline] - fn div_mod_floor(&self, other: &BigUint) -> (BigUint, BigUint) { + fn div_mod_floor(&self, other: &Self) -> (Self, Self) { division::div_rem_ref(self, other) } #[inline] - fn div_ceil(&self, other: &BigUint) -> BigUint { + fn div_ceil(&self, other: &Self) -> Self { let (d, m) = division::div_rem_ref(self, other); if m.is_zero() { d @@ -244,7 +244,7 @@ impl Integer for BigUint { while !m.is_zero() { m >>= twos(&m); if n > m { - mem::swap(&mut n, &mut m) + mem::swap(&mut n, &mut m); } m -= &n; } @@ -254,7 +254,7 @@ impl Integer for BigUint { /// Calculates the Lowest Common Multiple (LCM) of the number and `other`. #[inline] - fn lcm(&self, other: &BigUint) -> BigUint { + fn lcm(&self, other: &Self) -> Self { if self.is_zero() && other.is_zero() { Self::ZERO } else { @@ -277,13 +277,13 @@ impl Integer for BigUint { /// Deprecated, use `is_multiple_of` instead. #[inline] - fn divides(&self, other: &BigUint) -> bool { + fn divides(&self, other: &Self) -> bool { self.is_multiple_of(other) } /// Returns `true` if the number is a multiple of `other`. #[inline] - fn is_multiple_of(&self, other: &BigUint) -> bool { + fn is_multiple_of(&self, other: &Self) -> bool { if other.is_zero() { return self.is_zero(); } @@ -294,10 +294,9 @@ impl Integer for BigUint { #[inline] fn is_even(&self) -> bool { // Considering only the last digit. - match self.data.first() { - Some(x) => x.is_even(), - None => true, - } + self.data + .first() + .map_or(true, num_integer::Integer::is_even) } /// Returns `true` if the number is not divisible by `2`. @@ -385,7 +384,7 @@ impl Roots for BigUint { let bits = self.bits(); let n64 = u64::from(n); if bits <= n64 { - return BigUint::one(); + return Self::one(); } // If we fit in `u64`, compute the root that way. @@ -401,7 +400,7 @@ impl Roots for BigUint { use num_traits::FromPrimitive; // We fit in `f64` (lossy), so get a better initial guess from that. - BigUint::from_f64((f.ln() / f64::from(n)).exp()).unwrap() + Self::from_f64((f.ln() / f64::from(n)).exp()).unwrap() } _ => { // Try to guess by scaling down such that it does fit in `f64`. @@ -412,13 +411,13 @@ impl Roots for BigUint { if scale < bits && bits - scale > n64 { (self >> scale).nth_root(n) << root_scale } else { - BigUint::one() << max_bits + Self::one() << max_bits } } }; #[cfg(not(feature = "std"))] - let guess = BigUint::one() << max_bits; + let guess = Self::one() << max_bits; let n_min_1 = n - 1; fixpoint(guess, max_bits, move |s| { @@ -449,7 +448,7 @@ impl Roots for BigUint { use num_traits::FromPrimitive; // We fit in `f64` (lossy), so get a better initial guess from that. - BigUint::from_f64(f.sqrt()).unwrap() + Self::from_f64(f.sqrt()).unwrap() } _ => { // Try to guess by scaling down such that it does fit in `f64`. @@ -462,7 +461,7 @@ impl Roots for BigUint { }; #[cfg(not(feature = "std"))] - let guess = BigUint::one() << max_bits; + let guess = Self::one() << max_bits; fixpoint(guess, max_bits, move |s| { let q = self / s; @@ -490,7 +489,7 @@ impl Roots for BigUint { use num_traits::FromPrimitive; // We fit in `f64` (lossy), so get a better initial guess from that. - BigUint::from_f64(f.cbrt()).unwrap() + Self::from_f64(f.cbrt()).unwrap() } _ => { // Try to guess by scaling down such that it does fit in `f64`. @@ -503,7 +502,7 @@ impl Roots for BigUint { }; #[cfg(not(feature = "std"))] - let guess = BigUint::one() << max_bits; + let guess = Self::one() << max_bits; fixpoint(guess, max_bits, move |s| { let q = self / (s * s); @@ -529,13 +528,14 @@ pub(crate) fn biguint_from_vec(digits: Vec) -> BigUint { impl BigUint { /// A constant `BigUint` with value 0, useful for static initialization. - pub const ZERO: Self = BigUint { data: Vec::new() }; + pub const ZERO: Self = Self { data: Vec::new() }; /// Creates and initializes a [`BigUint`]. /// /// The base 232 digits are ordered least significant digit first. + #[must_use] #[inline] - pub fn new(digits: Vec) -> BigUint { + pub fn new(digits: Vec) -> Self { let mut big = Self::ZERO; cfg_digit_expr!( @@ -552,8 +552,9 @@ impl BigUint { /// Creates and initializes a [`BigUint`]. /// /// The base 232 digits are ordered least significant digit first. + #[must_use] #[inline] - pub fn from_slice(slice: &[u32]) -> BigUint { + pub fn from_slice(slice: &[u32]) -> Self { let mut big = Self::ZERO; big.assign_from_slice(slice); big @@ -592,22 +593,24 @@ impl BigUint { /// assert_eq!(BigUint::from_bytes_be(b"Hello world!"), /// BigUint::parse_bytes(b"22405534230753963835153736737", 10).unwrap()); /// ``` + #[must_use] #[inline] - pub fn from_bytes_be(bytes: &[u8]) -> BigUint { + pub fn from_bytes_be(bytes: &[u8]) -> Self { if bytes.is_empty() { Self::ZERO } else { let mut v = bytes.to_vec(); v.reverse(); - BigUint::from_bytes_le(&v) + Self::from_bytes_le(&v) } } /// Creates and initializes a [`BigUint`]. /// /// The bytes are in little-endian byte order. + #[must_use] #[inline] - pub fn from_bytes_le(bytes: &[u8]) -> BigUint { + pub fn from_bytes_le(bytes: &[u8]) -> Self { if bytes.is_empty() { Self::ZERO } else { @@ -631,10 +634,11 @@ impl BigUint { /// assert_eq!(BigUint::parse_bytes(b"ABCD", 16), ToBigUint::to_biguint(&0xABCD)); /// assert_eq!(BigUint::parse_bytes(b"G", 16), None); /// ``` + #[must_use] #[inline] - pub fn parse_bytes(buf: &[u8], radix: u32) -> Option { + pub fn parse_bytes(buf: &[u8], radix: u32) -> Option { let s = str::from_utf8(buf).ok()?; - BigUint::from_str_radix(s, radix).ok() + Self::from_str_radix(s, radix).ok() } /// Creates and initializes a [`BigUint`]. Each `u8` of the input slice is @@ -653,7 +657,8 @@ impl BigUint { /// let a = BigUint::from_radix_be(inbase190, 190).unwrap(); /// assert_eq!(a.to_radix_be(190), inbase190); /// ``` - pub fn from_radix_be(buf: &[u8], radix: u32) -> Option { + #[must_use] + pub fn from_radix_be(buf: &[u8], radix: u32) -> Option { convert::from_radix_be(buf, radix) } @@ -673,7 +678,8 @@ impl BigUint { /// let a = BigUint::from_radix_be(inbase190, 190).unwrap(); /// assert_eq!(a.to_radix_be(190), inbase190); /// ``` - pub fn from_radix_le(buf: &[u8], radix: u32) -> Option { + #[must_use] + pub fn from_radix_le(buf: &[u8], radix: u32) -> Option { convert::from_radix_le(buf, radix) } @@ -687,6 +693,7 @@ impl BigUint { /// let i = BigUint::parse_bytes(b"1125", 10).unwrap(); /// assert_eq!(i.to_bytes_be(), vec![4, 101]); /// ``` + #[must_use] #[inline] pub fn to_bytes_be(&self) -> Vec { let mut v = self.to_bytes_le(); @@ -704,6 +711,7 @@ impl BigUint { /// let i = BigUint::parse_bytes(b"1125", 10).unwrap(); /// assert_eq!(i.to_bytes_le(), vec![101, 4]); /// ``` + #[must_use] #[inline] pub fn to_bytes_le(&self) -> Vec { if self.is_zero() { @@ -726,6 +734,7 @@ impl BigUint { /// assert_eq!(BigUint::from(4294967296u64).to_u32_digits(), vec![0, 1]); /// assert_eq!(BigUint::from(112500000000u64).to_u32_digits(), vec![830850304, 26]); /// ``` + #[must_use] #[inline] pub fn to_u32_digits(&self) -> Vec { self.iter_u32_digits().collect() @@ -745,6 +754,7 @@ impl BigUint { /// assert_eq!(BigUint::from(112500000000u64).to_u64_digits(), vec![112500000000]); /// assert_eq!(BigUint::from(1u128 << 64).to_u64_digits(), vec![0, 1]); /// ``` + #[must_use] #[inline] pub fn to_u64_digits(&self) -> Vec { self.iter_u64_digits().collect() @@ -763,6 +773,7 @@ impl BigUint { /// assert_eq!(BigUint::from(4294967296u64).iter_u32_digits().collect::>(), vec![0, 1]); /// assert_eq!(BigUint::from(112500000000u64).iter_u32_digits().collect::>(), vec![830850304, 26]); /// ``` + #[must_use] #[inline] pub fn iter_u32_digits(&self) -> U32Digits<'_> { U32Digits::new(self.data.as_slice()) @@ -782,6 +793,7 @@ impl BigUint { /// assert_eq!(BigUint::from(112500000000u64).iter_u64_digits().collect::>(), vec![112500000000]); /// assert_eq!(BigUint::from(1u128 << 64).iter_u64_digits().collect::>(), vec![0, 1]); /// ``` + #[must_use] #[inline] pub fn iter_u64_digits(&self) -> U64Digits<'_> { U64Digits::new(self.data.as_slice()) @@ -798,6 +810,7 @@ impl BigUint { /// let i = BigUint::parse_bytes(b"ff", 16).unwrap(); /// assert_eq!(i.to_str_radix(16), "ff"); /// ``` + #[must_use] #[inline] pub fn to_str_radix(&self, radix: u32) -> String { let mut v = to_str_radix_reversed(self, radix); @@ -819,6 +832,7 @@ impl BigUint { /// vec![2, 94, 27]); /// // 0xFFFF = 65535 = 2*(159^2) + 94*159 + 27 /// ``` + #[must_use] #[inline] pub fn to_radix_be(&self, radix: u32) -> Vec { let mut v = convert::to_radix_le(self, radix); @@ -840,12 +854,17 @@ impl BigUint { /// vec![27, 94, 2]); /// // 0xFFFF = 65535 = 27 + 94*159 + 2*(159^2) /// ``` + #[must_use] #[inline] pub fn to_radix_le(&self, radix: u32) -> Vec { convert::to_radix_le(self, radix) } /// Determines the fewest bits necessary to express the [`BigUint`]. + /// + /// # Panics + /// - if there is not at least one u64 in the data vector + #[must_use] #[inline] pub fn bits(&self) -> u64 { if self.is_zero() { @@ -859,7 +878,7 @@ impl BigUint { /// be nonzero. #[inline] fn normalize(&mut self) { - if let Some(&0) = self.data.last() { + if self.data.last() == Some(&0) { let len = self.data.iter().rposition(|&d| d != 0).map_or(0, |i| i + 1); self.data.truncate(len); } @@ -870,12 +889,13 @@ impl BigUint { /// Returns a normalized [`BigUint`]. #[inline] - fn normalized(mut self) -> BigUint { + fn normalized(mut self) -> Self { self.normalize(); self } /// Returns `self ^ exponent`. + #[must_use] pub fn pow(&self, exponent: u32) -> Self { Pow::pow(self, exponent) } @@ -883,6 +903,7 @@ impl BigUint { /// Returns `(self ^ exponent) % modulus`. /// /// Panics if the modulus is zero. + #[must_use] pub fn modpow(&self, exponent: &Self, modulus: &Self) -> Self { power::modpow(self, exponent, modulus) } @@ -910,6 +931,7 @@ impl BigUint { /// assert_eq!(x.modinv(&m).unwrap(), a); /// assert!((a * x % m).is_one()); /// ``` + #[must_use] pub fn modinv(&self, modulus: &Self) -> Option { // Based on the inverse pseudocode listed here: // https://en.wikipedia.org/wiki/Extended_Euclidean_algorithm#Modular_integers @@ -933,17 +955,17 @@ impl BigUint { return None; } else if r1.is_one() { return Some(r1); - } else { - let (q, r2) = modulus.div_rem(&r1); - if r2.is_zero() { - return None; - } - r0 = r1; - r1 = r2; - t0 = Self::one(); - t1 = modulus - q; } + let (q, r2) = modulus.div_rem(&r1); + if r2.is_zero() { + return None; + } + r0 = r1; + r1 = r2; + t0 = Self::one(); + t1 = modulus - q; + while !r1.is_zero() { let (q, r2) = r0.div_rem(&r1); r0 = r1; @@ -969,24 +991,28 @@ impl BigUint { /// Returns the truncated principal square root of `self` -- /// see [Roots::sqrt](https://docs.rs/num-integer/0.1/num_integer/trait.Roots.html#method.sqrt) + #[must_use] pub fn sqrt(&self) -> Self { Roots::sqrt(self) } /// Returns the truncated principal cube root of `self` -- /// see [Roots::cbrt](https://docs.rs/num-integer/0.1/num_integer/trait.Roots.html#method.cbrt). + #[must_use] pub fn cbrt(&self) -> Self { Roots::cbrt(self) } /// Returns the truncated principal `n`th root of `self` -- /// see [Roots::nth_root](https://docs.rs/num-integer/0.1/num_integer/trait.Roots.html#tymethod.nth_root). + #[must_use] pub fn nth_root(&self, n: u32) -> Self { Roots::nth_root(self, n) } /// Returns the number of least-significant bits that are zero, /// or `None` if the entire number is zero. + #[must_use] pub fn trailing_zeros(&self) -> Option { let i = self.data.iter().position(|&digit| digit != 0)?; let zeros: u64 = self.data[i].trailing_zeros().into(); @@ -994,21 +1020,25 @@ impl BigUint { } /// Returns the number of least-significant bits that are ones. + #[must_use] pub fn trailing_ones(&self) -> u64 { - if let Some(i) = self.data.iter().position(|&digit| !digit != 0) { - let ones: u64 = self.data[i].trailing_ones().into(); - i as u64 * u64::from(big_digit::BITS) + ones - } else { - self.data.len() as u64 * u64::from(big_digit::BITS) - } + self.data.iter().position(|&digit| !digit != 0).map_or_else( + || self.data.len() as u64 * u64::from(big_digit::BITS), + |i| { + let ones: u64 = self.data[i].trailing_ones().into(); + i as u64 * u64::from(big_digit::BITS) + ones + }, + ) } /// Returns the number of one bits. + #[must_use] pub fn count_ones(&self) -> u64 { self.data.iter().map(|&d| u64::from(d.count_ones())).sum() } /// Returns whether the bit in the given position is set + #[must_use] pub fn bit(&self, bit: u64) -> bool { let bits_per_digit = u64::from(big_digit::BITS); if let Some(digit_index) = (bit / bits_per_digit).to_usize() { @@ -1103,9 +1133,9 @@ impl IntDigits for BigUint { #[inline] fn u32_chunk_to_u64(chunk: &[u32]) -> u64 { // raw could have odd length - let mut digit = chunk[0] as u64; + let mut digit = u64::from(chunk[0]); if let Some(&hi) = chunk.get(1) { - digit |= (hi as u64) << 32; + digit |= u64::from(hi) << 32; } digit } @@ -1121,7 +1151,7 @@ cfg_32_or_test!( cfg_32_or_test!( /// Split a single `u128` into four `u32`. #[inline] - fn u32_from_u128(n: u128) -> (u32, u32, u32, u32) { + const fn u32_from_u128(n: u128) -> (u32, u32, u32, u32) { ( (n >> 96) as u32, (n >> 64) as u32, @@ -1151,9 +1181,7 @@ cfg_digit!( assert_eq!( BigUint::from_slice(slice).data, data, - "from {:?}, to {:?}", - slice, - data + "from {slice:?}, to {data:?}" ); } check(&[1], &[1]); @@ -1162,7 +1190,7 @@ cfg_digit!( check(&[1, 2, 0, 0], &[8_589_934_593]); check(&[0, 0, 1, 2], &[0, 8_589_934_593]); check(&[0, 0, 1, 2, 0, 0], &[0, 8_589_934_593]); - check(&[-1i32 as u32], &[(-1i32 as u32) as BigDigit]); + check(&[-1i32 as u32], &[BigDigit::from(-1i32 as u32)]); } ); @@ -1174,12 +1202,15 @@ fn test_u32_u128() { (u32::MAX, u32::MAX, u32::MAX, u32::MAX) ); - assert_eq!(u32_from_u128(u32::MAX as u128), (0, 0, 0, u32::MAX)); + assert_eq!(u32_from_u128(u128::from(u32::MAX)), (0, 0, 0, u32::MAX)); - assert_eq!(u32_from_u128(u64::MAX as u128), (0, 0, u32::MAX, u32::MAX)); + assert_eq!( + u32_from_u128(u128::from(u64::MAX)), + (0, 0, u32::MAX, u32::MAX) + ); assert_eq!( - u32_from_u128((u64::MAX as u128) + u32::MAX as u128), + u32_from_u128(u128::from(u64::MAX) + u128::from(u32::MAX)), (0, 1, 0, u32::MAX - 1) ); @@ -1192,10 +1223,10 @@ fn test_u128_u32_roundtrip() { let values = vec![ 0u128, 1u128, - u64::MAX as u128 * 3, - u32::MAX as u128, - u64::MAX as u128, - (u64::MAX as u128) + u32::MAX as u128, + u128::from(u64::MAX) * 3, + u128::from(u32::MAX), + u128::from(u64::MAX), + u128::from(u64::MAX) + u128::from(u32::MAX), u128::MAX, ]; diff --git a/src/biguint/addition.rs b/src/biguint/addition.rs index b6711314..f752e225 100644 --- a/src/biguint/addition.rs +++ b/src/biguint/addition.rs @@ -78,7 +78,7 @@ pub(super) fn __add2(a: &mut [BigDigit], b: &[BigDigit]) -> BigDigit { /// a += b /// /// The caller _must_ ensure that a is big enough to store the result - typically this means -/// resizing a to max(a.len(), b.len()) + 1, to fit a possible carry. +/// resizing a to `max(a.len(), b.len())` + 1, to fit a possible carry. pub(super) fn add2(a: &mut [BigDigit], b: &[BigDigit]) { let carry = __add2(a, b); @@ -88,17 +88,17 @@ pub(super) fn add2(a: &mut [BigDigit], b: &[BigDigit]) { forward_all_binop_to_val_ref_commutative!(impl Add for BigUint, add); forward_val_assign!(impl AddAssign for BigUint, add_assign); -impl Add<&BigUint> for BigUint { - type Output = BigUint; +impl Add<&Self> for BigUint { + type Output = Self; - fn add(mut self, other: &BigUint) -> BigUint { + fn add(mut self, other: &Self) -> Self { self += other; self } } -impl AddAssign<&BigUint> for BigUint { +impl AddAssign<&Self> for BigUint { #[inline] - fn add_assign(&mut self, other: &BigUint) { + fn add_assign(&mut self, other: &Self) { let self_len = self.data.len(); let carry = if self_len < other.data.len() { let lo_carry = __add2(&mut self.data[..], &other.data[..self_len]); @@ -120,10 +120,10 @@ forward_all_scalar_binop_to_val_val_commutative!(impl Add for BigUint, add) forward_all_scalar_binop_to_val_val_commutative!(impl Add for BigUint, add); impl Add for BigUint { - type Output = BigUint; + type Output = Self; #[inline] - fn add(mut self, other: u32) -> BigUint { + fn add(mut self, other: u32) -> Self { self += other; self } @@ -146,10 +146,10 @@ impl AddAssign for BigUint { } impl Add for BigUint { - type Output = BigUint; + type Output = Self; #[inline] - fn add(mut self, other: u64) -> BigUint { + fn add(mut self, other: u64) -> Self { self += other; self } @@ -191,10 +191,10 @@ impl AddAssign for BigUint { } impl Add for BigUint { - type Output = BigUint; + type Output = Self; #[inline] - fn add(mut self, other: u128) -> BigUint { + fn add(mut self, other: u128) -> Self { self += other; self } @@ -248,7 +248,7 @@ impl AddAssign for BigUint { impl CheckedAdd for BigUint { #[inline] - fn checked_add(&self, v: &BigUint) -> Option { + fn checked_add(&self, v: &Self) -> Option { Some(self.add(v)) } } diff --git a/src/biguint/bits.rs b/src/biguint/bits.rs index 42d7ec0c..2fbff6d5 100644 --- a/src/biguint/bits.rs +++ b/src/biguint/bits.rs @@ -23,18 +23,18 @@ impl BitAnd<&BigUint> for &BigUint { forward_val_assign!(impl BitAndAssign for BigUint, bitand_assign); -impl BitAnd<&BigUint> for BigUint { - type Output = BigUint; +impl BitAnd<&Self> for BigUint { + type Output = Self; #[inline] - fn bitand(mut self, other: &BigUint) -> BigUint { + fn bitand(mut self, other: &Self) -> Self { self &= other; self } } -impl BitAndAssign<&BigUint> for BigUint { +impl BitAndAssign<&Self> for BigUint { #[inline] - fn bitand_assign(&mut self, other: &BigUint) { + fn bitand_assign(&mut self, other: &Self) { for (ai, &bi) in self.data.iter_mut().zip(other.data.iter()) { *ai &= bi; } @@ -46,23 +46,23 @@ impl BitAndAssign<&BigUint> for BigUint { forward_all_binop_to_val_ref_commutative!(impl BitOr for BigUint, bitor); forward_val_assign!(impl BitOrAssign for BigUint, bitor_assign); -impl BitOr<&BigUint> for BigUint { - type Output = BigUint; +impl BitOr<&Self> for BigUint { + type Output = Self; - fn bitor(mut self, other: &BigUint) -> BigUint { + fn bitor(mut self, other: &Self) -> Self { self |= other; self } } -impl BitOrAssign<&BigUint> for BigUint { +impl BitOrAssign<&Self> for BigUint { #[inline] - fn bitor_assign(&mut self, other: &BigUint) { + fn bitor_assign(&mut self, other: &Self) { for (ai, &bi) in self.data.iter_mut().zip(other.data.iter()) { *ai |= bi; } if other.data.len() > self.data.len() { let extra = &other.data[self.data.len()..]; - self.data.extend(extra.iter().cloned()); + self.data.extend(extra.iter().copied()); } } } @@ -70,23 +70,23 @@ impl BitOrAssign<&BigUint> for BigUint { forward_all_binop_to_val_ref_commutative!(impl BitXor for BigUint, bitxor); forward_val_assign!(impl BitXorAssign for BigUint, bitxor_assign); -impl BitXor<&BigUint> for BigUint { - type Output = BigUint; +impl BitXor<&Self> for BigUint { + type Output = Self; - fn bitxor(mut self, other: &BigUint) -> BigUint { + fn bitxor(mut self, other: &Self) -> Self { self ^= other; self } } -impl BitXorAssign<&BigUint> for BigUint { +impl BitXorAssign<&Self> for BigUint { #[inline] - fn bitxor_assign(&mut self, other: &BigUint) { + fn bitxor_assign(&mut self, other: &Self) { for (ai, &bi) in self.data.iter_mut().zip(other.data.iter()) { *ai ^= bi; } if other.data.len() > self.data.len() { let extra = &other.data[self.data.len()..]; - self.data.extend(extra.iter().cloned()); + self.data.extend(extra.iter().copied()); } self.normalize(); } diff --git a/src/biguint/convert.rs b/src/biguint/convert.rs index 3daf3dcb..f5fb6cad 100644 --- a/src/biguint/convert.rs +++ b/src/biguint/convert.rs @@ -223,7 +223,7 @@ impl Num for BigUint { let mut s = s; if let Some(tail) = s.strip_prefix('+') { if !tail.starts_with('+') { - s = tail + s = tail; } } @@ -307,7 +307,7 @@ fn high_bits_to_u64(v: &BigUint) -> u64 { // XXX Conversion is useless if already 64-bit. #[allow(clippy::useless_conversion)] let masked = u64::from(*d) << (64 - (digit_bits - bits_want) as u32); - ret |= (masked != 0) as u64; + ret |= u64::from(masked != 0); } ret_bits += bits_want; @@ -336,7 +336,7 @@ impl ToPrimitive for BigUint { let mut ret: u64 = 0; let mut bits = 0; - for i in self.data.iter() { + for i in &self.data { if bits >= 64 { return None; } @@ -354,7 +354,7 @@ impl ToPrimitive for BigUint { let mut ret: u128 = 0; let mut bits = 0; - for i in self.data.iter() { + for i in &self.data { if bits >= 128 { return None; } @@ -429,35 +429,35 @@ impl_try_from_biguint!(i128, ToPrimitive::to_i128); impl FromPrimitive for BigUint { #[inline] - fn from_i64(n: i64) -> Option { + fn from_i64(n: i64) -> Option { if n >= 0 { - Some(BigUint::from(n as u64)) + Some(Self::from(n as u64)) } else { None } } #[inline] - fn from_i128(n: i128) -> Option { + fn from_i128(n: i128) -> Option { if n >= 0 { - Some(BigUint::from(n as u128)) + Some(Self::from(n as u128)) } else { None } } #[inline] - fn from_u64(n: u64) -> Option { - Some(BigUint::from(n)) + fn from_u64(n: u64) -> Option { + Some(Self::from(n)) } #[inline] - fn from_u128(n: u128) -> Option { - Some(BigUint::from(n)) + fn from_u128(n: u128) -> Option { + Some(Self::from(n)) } #[inline] - fn from_f64(mut n: f64) -> Option { + fn from_f64(mut n: f64) -> Option { // handle NAN, INFINITY, NEG_INFINITY if !n.is_finite() { return None; @@ -477,7 +477,7 @@ impl FromPrimitive for BigUint { return None; } - let mut ret = BigUint::from(mantissa); + let mut ret = Self::from(mantissa); match exponent.cmp(&0) { Greater => ret <<= exponent as usize, Equal => {} @@ -490,7 +490,7 @@ impl FromPrimitive for BigUint { impl From for BigUint { #[inline] fn from(mut n: u64) -> Self { - let mut ret: BigUint = Self::ZERO; + let mut ret: Self = Self::ZERO; while n != 0 { ret.data.push(n as BigDigit); @@ -505,7 +505,7 @@ impl From for BigUint { impl From for BigUint { #[inline] fn from(mut n: u128) -> Self { - let mut ret: BigUint = Self::ZERO; + let mut ret: Self = Self::ZERO; while n != 0 { ret.data.push(n as BigDigit); @@ -609,7 +609,7 @@ pub(super) fn to_bitwise_digits_le(u: &BigUint, bits: u8) -> Vec { .unwrap_or(usize::MAX); let mut res = Vec::with_capacity(digits); - for mut r in u.data[..last_i].iter().cloned() { + for mut r in u.data[..last_i].iter().copied() { for _ in 0..digits_per_big_digit { res.push((r & mask) as u8); r >>= bits; @@ -659,7 +659,7 @@ fn to_inexact_bitwise_digits_le(u: &BigUint, bits: u8) -> Vec { res.push(r as u8); } - while let Some(&0) = res.last() { + while res.last() == Some(&0) { res.pop(); } @@ -831,7 +831,7 @@ const fn generate_radix_bases(max: BigDigit) -> [(BigDigit, usize); 257] { base = b; power += 1; } - bases[radix as usize] = (base, power) + bases[radix as usize] = (base, power); } radix += 1; } diff --git a/src/biguint/division.rs b/src/biguint/division.rs index 3dfb0bbb..0c1b462e 100644 --- a/src/biguint/division.rs +++ b/src/biguint/division.rs @@ -83,9 +83,7 @@ fn div_half(rem: BigDigit, digit: BigDigit, divisor: BigDigit) -> (BigDigit, Big #[inline] pub(super) fn div_rem_digit(mut a: BigUint, b: BigDigit) -> (BigUint, BigDigit) { - if b == 0 { - panic!("attempt to divide by zero") - } + assert!((b != 0), "attempt to divide by zero"); let mut rem = 0; @@ -108,9 +106,7 @@ pub(super) fn div_rem_digit(mut a: BigUint, b: BigDigit) -> (BigUint, BigDigit) #[inline] fn rem_digit(a: &BigUint, b: BigDigit) -> BigDigit { - if b == 0 { - panic!("attempt to divide by zero") - } + assert!((b != 0), "attempt to divide by zero"); let mut rem = 0; @@ -159,9 +155,7 @@ fn sub_mul_digit_same_len(a: &mut [BigDigit], b: &[BigDigit], c: BigDigit) -> Bi } fn div_rem(mut u: BigUint, mut d: BigUint) -> (BigUint, BigUint) { - if d.is_zero() { - panic!("attempt to divide by zero") - } + assert!(!d.is_zero(), "attempt to divide by zero"); if u.is_zero() { return (BigUint::ZERO, BigUint::ZERO); } @@ -206,9 +200,7 @@ fn div_rem(mut u: BigUint, mut d: BigUint) -> (BigUint, BigUint) { } pub(super) fn div_rem_ref(u: &BigUint, d: &BigUint) -> (BigUint, BigUint) { - if d.is_zero() { - panic!("attempt to divide by zero") - } + assert!(!d.is_zero(), "attempt to divide by zero"); if u.is_zero() { return (BigUint::ZERO, BigUint::ZERO); } @@ -346,11 +338,11 @@ forward_val_ref_binop!(impl Div for BigUint, div); forward_ref_val_binop!(impl Div for BigUint, div); forward_val_assign!(impl DivAssign for BigUint, div_assign); -impl Div for BigUint { - type Output = BigUint; +impl Div for BigUint { + type Output = Self; #[inline] - fn div(self, other: BigUint) -> BigUint { + fn div(self, other: Self) -> Self { let (q, _) = div_rem(self, other); q } @@ -365,9 +357,9 @@ impl Div<&BigUint> for &BigUint { q } } -impl DivAssign<&BigUint> for BigUint { +impl DivAssign<&Self> for BigUint { #[inline] - fn div_assign(&mut self, other: &BigUint) { + fn div_assign(&mut self, other: &Self) { *self = &*self / other; } } @@ -379,10 +371,10 @@ forward_all_scalar_binop_to_val_val!(impl Div for BigUint, div); forward_all_scalar_binop_to_val_val!(impl Div for BigUint, div); impl Div for BigUint { - type Output = BigUint; + type Output = Self; #[inline] - fn div(self, other: u32) -> BigUint { + fn div(self, other: u32) -> Self { let (q, _) = div_rem_digit(self, other as BigDigit); q } @@ -408,10 +400,10 @@ impl Div for u32 { } impl Div for BigUint { - type Output = BigUint; + type Output = Self; #[inline] - fn div(self, other: u64) -> BigUint { + fn div(self, other: u64) -> Self { let (q, _) = div_rem(self, From::from(other)); q } @@ -451,10 +443,10 @@ impl Div for u64 { } impl Div for BigUint { - type Output = BigUint; + type Output = Self; #[inline] - fn div(self, other: u128) -> BigUint { + fn div(self, other: u128) -> Self { let (q, _) = div_rem(self, From::from(other)); q } @@ -504,11 +496,11 @@ forward_val_ref_binop!(impl Rem for BigUint, rem); forward_ref_val_binop!(impl Rem for BigUint, rem); forward_val_assign!(impl RemAssign for BigUint, rem_assign); -impl Rem for BigUint { - type Output = BigUint; +impl Rem for BigUint { + type Output = Self; #[inline] - fn rem(self, other: BigUint) -> BigUint { + fn rem(self, other: Self) -> Self { if let Some(other) = other.to_u32() { &self % other } else { @@ -523,17 +515,18 @@ impl Rem<&BigUint> for &BigUint { #[inline] fn rem(self, other: &BigUint) -> BigUint { - if let Some(other) = other.to_u32() { - self % other - } else { - let (_, r) = self.div_rem(other); - r - } + other.to_u32().map_or_else( + || { + let (_, r) = self.div_rem(other); + r + }, + |other| self % other, + ) } } -impl RemAssign<&BigUint> for BigUint { +impl RemAssign<&Self> for BigUint { #[inline] - fn rem_assign(&mut self, other: &BigUint) { + fn rem_assign(&mut self, other: &Self) { *self = &*self % other; } } @@ -600,10 +593,10 @@ impl_rem_assign_scalar!(i16, to_i16); impl_rem_assign_scalar!(i8, to_i8); impl Rem for BigUint { - type Output = BigUint; + type Output = Self; #[inline] - fn rem(self, other: u64) -> BigUint { + fn rem(self, other: u64) -> Self { let (_, r) = div_rem(self, From::from(other)); r } @@ -626,10 +619,10 @@ impl Rem for u64 { } impl Rem for BigUint { - type Output = BigUint; + type Output = Self; #[inline] - fn rem(self, other: u128) -> BigUint { + fn rem(self, other: u128) -> Self { let (_, r) = div_rem(self, From::from(other)); r } @@ -654,7 +647,7 @@ impl Rem for u128 { impl CheckedDiv for BigUint { #[inline] - fn checked_div(&self, v: &BigUint) -> Option { + fn checked_div(&self, v: &Self) -> Option { if v.is_zero() { return None; } @@ -664,7 +657,7 @@ impl CheckedDiv for BigUint { impl CheckedEuclid for BigUint { #[inline] - fn checked_div_euclid(&self, v: &BigUint) -> Option { + fn checked_div_euclid(&self, v: &Self) -> Option { if v.is_zero() { return None; } @@ -672,7 +665,7 @@ impl CheckedEuclid for BigUint { } #[inline] - fn checked_rem_euclid(&self, v: &BigUint) -> Option { + fn checked_rem_euclid(&self, v: &Self) -> Option { if v.is_zero() { return None; } @@ -686,13 +679,13 @@ impl CheckedEuclid for BigUint { impl Euclid for BigUint { #[inline] - fn div_euclid(&self, v: &BigUint) -> BigUint { + fn div_euclid(&self, v: &Self) -> Self { // trivially same as regular division self / v } #[inline] - fn rem_euclid(&self, v: &BigUint) -> BigUint { + fn rem_euclid(&self, v: &Self) -> Self { // trivially same as regular remainder self % v } diff --git a/src/biguint/iter.rs b/src/biguint/iter.rs index 066c9c1e..5b051a88 100644 --- a/src/biguint/iter.rs +++ b/src/biguint/iter.rs @@ -71,13 +71,10 @@ cfg_digit!( impl<'a> U32Digits<'a> { #[inline] pub(super) fn new(data: &'a [u64]) -> Self { - let last_hi_is_zero = data - .last() - .map(|&last| { - let last_hi = (last >> 32) as u32; - last_hi == 0 - }) - .unwrap_or(false); + let last_hi_is_zero = data.last().map_or(false, |&last| { + let last_hi = (last >> 32) as u32; + last_hi == 0 + }); U32Digits { data, next_is_lo: true, @@ -235,7 +232,7 @@ cfg_digit!( type Item = u64; #[inline] fn next(&mut self) -> Option { - self.it.next().cloned() + self.it.next().copied() } #[inline] @@ -245,12 +242,12 @@ cfg_digit!( #[inline] fn nth(&mut self, n: usize) -> Option { - self.it.nth(n).cloned() + self.it.nth(n).copied() } #[inline] fn last(self) -> Option { - self.it.last().cloned() + self.it.last().copied() } #[inline] @@ -261,7 +258,7 @@ cfg_digit!( impl DoubleEndedIterator for U64Digits<'_> { fn next_back(&mut self) -> Option { - self.it.next_back().cloned() + self.it.next_back().copied() } } }; @@ -287,10 +284,10 @@ fn test_iter_u32_digits() { assert_eq!(it.len(), 0); assert_eq!(it.next(), None); - let n = super::BigUint::from(112500000000u64); + let n = super::BigUint::from(112_500_000_000_u64); let mut it = n.iter_u32_digits(); assert_eq!(it.len(), 2); - assert_eq!(it.next(), Some(830850304)); + assert_eq!(it.next(), Some(830_850_304)); assert_eq!(it.len(), 1); assert_eq!(it.next(), Some(26)); assert_eq!(it.len(), 0); @@ -329,10 +326,10 @@ fn test_iter_u32_digits_be() { assert_eq!(it.len(), 0); assert_eq!(it.next(), None); - let n = super::BigUint::from(112500000000u64); + let n = super::BigUint::from(112_500_000_000_u64); let mut it = n.iter_u32_digits(); assert_eq!(it.len(), 2); - assert_eq!(it.next(), Some(830850304)); + assert_eq!(it.next(), Some(830_850_304)); assert_eq!(it.len(), 1); assert_eq!(it.next(), Some(26)); assert_eq!(it.len(), 0); diff --git a/src/biguint/monty.rs b/src/biguint/monty.rs index a0b26b54..7ad7260b 100644 --- a/src/biguint/monty.rs +++ b/src/biguint/monty.rs @@ -50,11 +50,7 @@ fn montgomery(x: &BigUint, y: &BigUint, m: &BigUint, k: BigDigit, n: usize) -> B // or else the result will not be properly reduced. assert!( x.data.len() == n && y.data.len() == n && m.data.len() == n, - "{:?} {:?} {:?} {}", - x, - y, - m, - n + "{x:?} {y:?} {m:?} {n}" ); let mut z = BigUint::ZERO; @@ -109,7 +105,7 @@ fn sub_vv(z: &mut [BigDigit], x: &[BigDigit], y: &[BigDigit]) -> BigDigit { let zi = xi.wrapping_sub(*yi).wrapping_sub(c); z[i] = zi; // see "Hacker's Delight", section 2-12 (overflow detection) - c = ((yi & !xi) | ((yi | !xi) & zi)) >> (big_digit::BITS - 1) + c = ((yi & !xi) | ((yi | !xi) & zi)) >> (big_digit::BITS - 1); } c @@ -117,7 +113,7 @@ fn sub_vv(z: &mut [BigDigit], x: &[BigDigit], y: &[BigDigit]) -> BigDigit { /// z1<<_W + z0 = x+y+c, with c == 0 or 1 #[inline(always)] -fn add_ww(x: BigDigit, y: BigDigit, c: BigDigit) -> (BigDigit, BigDigit) { +const fn add_ww(x: BigDigit, y: BigDigit, c: BigDigit) -> (BigDigit, BigDigit) { let yc = y.wrapping_add(c); let z0 = x.wrapping_add(yc); let z1 = if z0 < x || yc < y { 1 } else { 0 }; @@ -127,7 +123,7 @@ fn add_ww(x: BigDigit, y: BigDigit, c: BigDigit) -> (BigDigit, BigDigit) { /// z1 << _W + z0 = x * y + c #[inline(always)] -fn mul_add_www(x: BigDigit, y: BigDigit, c: BigDigit) -> (BigDigit, BigDigit) { +const fn mul_add_www(x: BigDigit, y: BigDigit, c: BigDigit) -> (BigDigit, BigDigit) { let z = x as DoubleBigDigit * y as DoubleBigDigit + c as DoubleBigDigit; ((z >> big_digit::BITS) as BigDigit, z as BigDigit) } diff --git a/src/biguint/multiplication.rs b/src/biguint/multiplication.rs index e9d21384..9c9de879 100644 --- a/src/biguint/multiplication.rs +++ b/src/biguint/multiplication.rs @@ -424,7 +424,7 @@ fn scalar_mul(a: &mut BigUint, b: BigDigit) { *a <<= b.trailing_zeros(); } else { let mut carry = 0; - for a in a.data.iter_mut() { + for a in &mut a.data { *a = mul_with_carry(*a, b, &mut carry); } if carry != 0 { @@ -437,10 +437,10 @@ fn scalar_mul(a: &mut BigUint, b: BigDigit) { fn sub_sign(mut a: &[BigDigit], mut b: &[BigDigit]) -> (Sign, BigUint) { // Normalize: - if let Some(&0) = a.last() { + if a.last() == Some(&0) { a = &a[..a.iter().rposition(|&x| x != 0).map_or(0, |i| i + 1)]; } - if let Some(&0) = b.last() { + if b.last() == Some(&0) { b = &b[..b.iter().rposition(|&x| x != 0).map_or(0, |i| i + 1)]; } @@ -517,10 +517,10 @@ forward_all_scalar_binop_to_val_val_commutative!(impl Mul for BigUint, mul) forward_all_scalar_binop_to_val_val_commutative!(impl Mul for BigUint, mul); impl Mul for BigUint { - type Output = BigUint; + type Output = Self; #[inline] - fn mul(mut self, other: u32) -> BigUint { + fn mul(mut self, other: u32) -> Self { self *= other; self } @@ -533,10 +533,10 @@ impl MulAssign for BigUint { } impl Mul for BigUint { - type Output = BigUint; + type Output = Self; #[inline] - fn mul(mut self, other: u64) -> BigUint { + fn mul(mut self, other: u64) -> Self { self *= other; self } @@ -561,10 +561,10 @@ impl MulAssign for BigUint { } impl Mul for BigUint { - type Output = BigUint; + type Output = Self; #[inline] - fn mul(mut self, other: u128) -> BigUint { + fn mul(mut self, other: u128) -> Self { self *= other; self } @@ -599,7 +599,7 @@ impl MulAssign for BigUint { impl CheckedMul for BigUint { #[inline] - fn checked_mul(&self, v: &BigUint) -> Option { + fn checked_mul(&self, v: &Self) -> Option { Some(self.mul(v)) } } diff --git a/src/biguint/power.rs b/src/biguint/power.rs index fa1c4926..bf972ea5 100644 --- a/src/biguint/power.rs +++ b/src/biguint/power.rs @@ -6,13 +6,13 @@ use crate::big_digit::{self, BigDigit}; use num_integer::Integer; use num_traits::{One, Pow, ToPrimitive, Zero}; -impl Pow<&BigUint> for BigUint { - type Output = BigUint; +impl Pow<&Self> for BigUint { + type Output = Self; #[inline] - fn pow(self, exp: &BigUint) -> BigUint { + fn pow(self, exp: &Self) -> Self { if self.is_one() || exp.is_zero() { - BigUint::one() + Self::one() } else if self.is_zero() { Self::ZERO } else if let Some(exp) = exp.to_u64() { @@ -27,11 +27,11 @@ impl Pow<&BigUint> for BigUint { } } -impl Pow for BigUint { - type Output = BigUint; +impl Pow for BigUint { + type Output = Self; #[inline] - fn pow(self, exp: BigUint) -> BigUint { + fn pow(self, exp: Self) -> Self { Pow::pow(self, &exp) } } @@ -232,9 +232,9 @@ fn test_plain_modpow() { two.pow(0b10_00000000_u32) % &modulus, plain_modpow(two, &exp, &modulus) ); - let exp = vec![0, 0b110010]; + let exp = vec![0, 0b11_0010]; assert_eq!( - two.pow(0b110010_00000000_u32) % &modulus, + two.pow(0b11_0010_0000_0000_u32) % &modulus, plain_modpow(two, &exp, &modulus) ); let exp = vec![0b1, 0b1]; diff --git a/src/biguint/shift.rs b/src/biguint/shift.rs index 51483cd0..28ce3b22 100644 --- a/src/biguint/shift.rs +++ b/src/biguint/shift.rs @@ -10,9 +10,7 @@ use num_traits::{PrimInt, Zero}; #[inline] fn biguint_shl(n: Cow<'_, BigUint>, shift: T) -> BigUint { - if shift < T::zero() { - panic!("attempt to shift left with negative"); - } + assert!((shift >= T::zero()), "attempt to shift left with negative"); if n.is_zero() { return n.into_owned(); } @@ -23,21 +21,20 @@ fn biguint_shl(n: Cow<'_, BigUint>, shift: T) -> BigUint { } fn biguint_shl2(n: Cow<'_, BigUint>, digits: usize, shift: u8) -> BigUint { - let mut data = match digits { - 0 => n.into_owned().data, - _ => { - let len = digits.saturating_add(n.data.len() + 1); - let mut data = Vec::with_capacity(len); - data.resize(digits, 0); - data.extend(n.data.iter()); - data - } + let mut data = if digits == 0 { + n.into_owned().data + } else { + let len = digits.saturating_add(n.data.len() + 1); + let mut data = Vec::with_capacity(len); + data.resize(digits, 0); + data.extend(n.data.iter()); + data }; if shift > 0 { let mut carry = 0; let carry_shift = big_digit::BITS - shift; - for elem in data[digits..].iter_mut() { + for elem in &mut data[digits..] { let new_carry = *elem >> carry_shift; *elem = (*elem << shift) | carry; carry = new_carry; @@ -52,9 +49,7 @@ fn biguint_shl2(n: Cow<'_, BigUint>, digits: usize, shift: u8) -> BigUint { #[inline] fn biguint_shr(n: Cow<'_, BigUint>, shift: T) -> BigUint { - if shift < T::zero() { - panic!("attempt to shift right with negative"); - } + assert!((shift >= T::zero()), "attempt to shift right with negative"); if n.is_zero() { return n.into_owned(); } diff --git a/src/biguint/subtraction.rs b/src/biguint/subtraction.rs index 47a5015f..cc9c6583 100644 --- a/src/biguint/subtraction.rs +++ b/src/biguint/subtraction.rs @@ -108,16 +108,16 @@ forward_val_val_binop!(impl Sub for BigUint, sub); forward_ref_ref_binop!(impl Sub for BigUint, sub); forward_val_assign!(impl SubAssign for BigUint, sub_assign); -impl Sub<&BigUint> for BigUint { - type Output = BigUint; +impl Sub<&Self> for BigUint { + type Output = Self; - fn sub(mut self, other: &BigUint) -> BigUint { + fn sub(mut self, other: &Self) -> Self { self -= other; self } } -impl SubAssign<&BigUint> for BigUint { - fn sub_assign(&mut self, other: &BigUint) { +impl SubAssign<&Self> for BigUint { + fn sub_assign(&mut self, other: &Self) { sub2(&mut self.data[..], &other.data[..]); self.normalize(); } @@ -132,7 +132,7 @@ impl Sub for &BigUint { let lo_borrow = __sub2rev(&self.data[..other_len], &mut other.data); other.data.extend_from_slice(&self.data[other_len..]); if lo_borrow != 0 { - sub2(&mut other.data[other_len..], &[1]) + sub2(&mut other.data[other_len..], &[1]); } } else { sub2rev(&self.data[..], &mut other.data[..]); @@ -148,10 +148,10 @@ forward_all_scalar_binop_to_val_val!(impl Sub for BigUint, sub); forward_all_scalar_binop_to_val_val!(impl Sub for BigUint, sub); impl Sub for BigUint { - type Output = BigUint; + type Output = Self; #[inline] - fn sub(mut self, other: u32) -> BigUint { + fn sub(mut self, other: u32) -> Self { self -= other; self } @@ -191,10 +191,10 @@ impl Sub for u32 { } impl Sub for BigUint { - type Output = BigUint; + type Output = Self; #[inline] - fn sub(mut self, other: u64) -> BigUint { + fn sub(mut self, other: u64) -> Self { self -= other; self } @@ -245,10 +245,10 @@ impl Sub for u64 { } impl Sub for BigUint { - type Output = BigUint; + type Output = Self; #[inline] - fn sub(mut self, other: u128) -> BigUint { + fn sub(mut self, other: u128) -> Self { self -= other; self } @@ -302,7 +302,7 @@ impl Sub for u128 { impl CheckedSub for BigUint { #[inline] - fn checked_sub(&self, v: &BigUint) -> Option { + fn checked_sub(&self, v: &Self) -> Option { match self.cmp(v) { Less => None, Equal => Some(Self::ZERO), diff --git a/src/lib.rs b/src/lib.rs index 6e47479d..314dc89c 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -137,22 +137,22 @@ enum BigIntErrorKind { } impl ParseBigIntError { - fn __description(&self) -> &str { - use crate::BigIntErrorKind::*; + const fn __description(&self) -> &'static str { + use crate::BigIntErrorKind::{Empty, InvalidDigit}; match self.kind { Empty => "cannot parse integer from empty string", InvalidDigit => "invalid digit found in string", } } - fn empty() -> Self { - ParseBigIntError { + const fn empty() -> Self { + Self { kind: BigIntErrorKind::Empty, } } - fn invalid() -> Self { - ParseBigIntError { + const fn invalid() -> Self { + Self { kind: BigIntErrorKind::InvalidDigit, } } @@ -179,11 +179,11 @@ pub struct TryFromBigIntError { } impl TryFromBigIntError { - fn new(original: T) -> Self { - TryFromBigIntError { original } + const fn new(original: T) -> Self { + Self { original } } - fn __description(&self) -> &str { + const fn __description(&self) -> &'static str { "out of range conversion regarding big integer attempted" } @@ -246,17 +246,17 @@ mod big_digit { const LO_MASK: DoubleBigDigit = MAX as DoubleBigDigit; #[inline] - fn get_hi(n: DoubleBigDigit) -> BigDigit { + const fn get_hi(n: DoubleBigDigit) -> BigDigit { (n >> BITS) as BigDigit } #[inline] - fn get_lo(n: DoubleBigDigit) -> BigDigit { + const fn get_lo(n: DoubleBigDigit) -> BigDigit { (n & LO_MASK) as BigDigit } /// Split one [`DoubleBigDigit`] into two [`BigDigit`]s. #[inline] - pub(crate) fn from_doublebigdigit(n: DoubleBigDigit) -> (BigDigit, BigDigit) { + pub(crate) const fn from_doublebigdigit(n: DoubleBigDigit) -> (BigDigit, BigDigit) { (get_hi(n), get_lo(n)) } diff --git a/src/macros.rs b/src/macros.rs index f2e21e3b..d6e81902 100644 --- a/src/macros.rs +++ b/src/macros.rs @@ -160,7 +160,7 @@ macro_rules! forward_val_assign_scalar { }; } -/// use this if val_val_binop is already implemented and the reversed order is required +/// use this if `val_val_binop` is already implemented and the reversed order is required macro_rules! forward_scalar_val_val_binop_commutative { (impl $imp:ident < $scalar:ty > for $res:ty, $method:ident) => { impl $imp<$res> for $scalar { diff --git a/tests/bigint.rs b/tests/bigint.rs index fea5232e..6f575ae0 100644 --- a/tests/bigint.rs +++ b/tests/bigint.rs @@ -105,7 +105,7 @@ fn test_to_signed_bytes_le() { check("-100", vec![156]); check("-8388608", vec![0, 0, 0x80]); check("-192", vec![0x40, 0xff]); - check("128", vec![0x80, 0]) + check("128", vec![0x80, 0]); } #[test] @@ -187,10 +187,10 @@ fn test_cmp() { let vs: [&[u32]; 4] = [&[2_u32], &[1, 1], &[2, 1], &[1, 1, 1]]; let mut nums = Vec::new(); for s in vs.iter().rev() { - nums.push(BigInt::from_slice(Minus, *s)); + nums.push(BigInt::from_slice(Minus, s)); } nums.push(Zero::zero()); - nums.extend(vs.iter().map(|s| BigInt::from_slice(Plus, *s))); + nums.extend(vs.iter().map(|s| BigInt::from_slice(Plus, s))); for (i, ni) in nums.iter().enumerate() { for (j0, nj) in nums[i..].iter().enumerate() { @@ -199,26 +199,26 @@ fn test_cmp() { assert_eq!(ni.cmp(nj), Equal); assert_eq!(nj.cmp(ni), Equal); assert_eq!(ni, nj); - assert!(!(ni != nj)); + assert!((ni == nj)); assert!(ni <= nj); assert!(ni >= nj); - assert!(!(ni < nj)); - assert!(!(ni > nj)); + assert!((ni >= nj)); + assert!((ni <= nj)); } else { assert_eq!(ni.cmp(nj), Less); assert_eq!(nj.cmp(ni), Greater); - assert!(!(ni == nj)); + assert!((ni != nj)); assert!(ni != nj); assert!(ni <= nj); - assert!(!(ni >= nj)); + assert!((ni < nj)); assert!(ni < nj); - assert!(!(ni > nj)); + assert!((ni <= nj)); - assert!(!(nj <= ni)); + assert!((nj > ni)); assert!(nj >= ni); - assert!(!(nj < ni)); + assert!((nj >= ni)); assert!(nj > ni); } } @@ -386,7 +386,7 @@ fn test_convert_f32() { check(&(BigInt::from((1u64 << 24) - 1) << (128 - 24)), f32::MAX); // keeping all 24 digits with the bits at different offsets to the BigDigits - let x: u32 = 0b00000000101111011111011011011101; + let x: u32 = 0b0000_0000_1011_1101_1111_0110_1101_1101; let mut f = x as f32; let mut b = BigInt::from(x); for _ in 0..64 { @@ -396,7 +396,8 @@ fn test_convert_f32() { } // this number when rounded to f64 then f32 isn't the same as when rounded straight to f32 - let mut n: i64 = 0b0000000000111111111111111111111111011111111111111111111111111111; + let mut n: i64 = + 0b0000_0000_0011_1111_1111_1111_1111_1111_1101_1111_1111_1111_1111_1111_1111_1111; assert!((n as f64) as f32 != n as f32); assert_eq!(BigInt::from(n).to_f32(), Some(n as f32)); n = -n; @@ -491,7 +492,7 @@ fn test_convert_f64() { check(&(BigInt::from((1u64 << 53) - 1) << (1024 - 53)), f64::MAX); // keeping all 53 digits with the bits at different offsets to the BigDigits - let x: u64 = 0b0000000000011110111110110111111101110111101111011111011011011101; + let x: u64 = 0b0000_0000_0001_1110_1111_1011_0111_1111_0111_0111_1011_1101_1111_0110_1101_1101; let mut f = x as f64; let mut b = BigInt::from(x); for _ in 0..128 { @@ -590,8 +591,8 @@ fn test_convert_from_uint() { }; } - check!(u8, BigInt::from_slice(Plus, &[u8::MAX as u32])); - check!(u16, BigInt::from_slice(Plus, &[u16::MAX as u32])); + check!(u8, BigInt::from_slice(Plus, &[u32::from(u8::MAX)])); + check!(u16, BigInt::from_slice(Plus, &[u32::from(u16::MAX)])); check!(u32, BigInt::from_slice(Plus, &[u32::MAX])); check!(u64, BigInt::from_slice(Plus, &[u32::MAX, u32::MAX])); check!( @@ -659,7 +660,7 @@ fn test_convert_from_biguint() { #[test] fn test_add() { - for elm in SUM_TRIPLES.iter() { + for elm in SUM_TRIPLES { let (a_vec, b_vec, c_vec) = *elm; let a = BigInt::from_slice(Plus, a_vec); let b = BigInt::from_slice(Plus, b_vec); @@ -688,7 +689,7 @@ fn test_add() { #[test] fn test_sub() { - for elm in SUM_TRIPLES.iter() { + for elm in SUM_TRIPLES { let (a_vec, b_vec, c_vec) = *elm; let a = BigInt::from_slice(Plus, a_vec); let b = BigInt::from_slice(Plus, b_vec); @@ -717,7 +718,7 @@ fn test_sub() { #[test] fn test_mul() { - for elm in MUL_TRIPLES.iter() { + for elm in MUL_TRIPLES { let (a_vec, b_vec, c_vec) = *elm; let a = BigInt::from_slice(Plus, a_vec); let b = BigInt::from_slice(Plus, b_vec); @@ -739,7 +740,7 @@ fn test_mul() { assert_assign_op!(nb *= a == nc); } - for elm in DIV_REM_QUADRUPLES.iter() { + for elm in DIV_REM_QUADRUPLES { let (a_vec, b_vec, c_vec, d_vec) = *elm; let a = BigInt::from_slice(Plus, a_vec); let b = BigInt::from_slice(Plus, b_vec); @@ -781,7 +782,7 @@ fn test_div_mod_floor() { } } - for elm in MUL_TRIPLES.iter() { + for elm in MUL_TRIPLES { let (a_vec, b_vec, c_vec) = *elm; let a = BigInt::from_slice(Plus, a_vec); let b = BigInt::from_slice(Plus, b_vec); @@ -795,7 +796,7 @@ fn test_div_mod_floor() { } } - for elm in DIV_REM_QUADRUPLES.iter() { + for elm in DIV_REM_QUADRUPLES { let (a_vec, b_vec, c_vec, d_vec) = *elm; let a = BigInt::from_slice(Plus, a_vec); let b = BigInt::from_slice(Plus, b_vec); @@ -833,7 +834,7 @@ fn test_div_rem() { check_sub(&a.neg(), b, &q.neg(), &r.neg()); check_sub(&a.neg(), &b.neg(), q, &r.neg()); } - for elm in MUL_TRIPLES.iter() { + for elm in MUL_TRIPLES { let (a_vec, b_vec, c_vec) = *elm; let a = BigInt::from_slice(Plus, a_vec); let b = BigInt::from_slice(Plus, b_vec); @@ -847,7 +848,7 @@ fn test_div_rem() { } } - for elm in DIV_REM_QUADRUPLES.iter() { + for elm in DIV_REM_QUADRUPLES { let (a_vec, b_vec, c_vec, d_vec) = *elm; let a = BigInt::from_slice(Plus, a_vec); let b = BigInt::from_slice(Plus, b_vec); @@ -880,7 +881,7 @@ fn test_div_ceil() { } } - for elm in MUL_TRIPLES.iter() { + for elm in MUL_TRIPLES { let (a_vec, b_vec, c_vec) = *elm; let a = BigInt::from_slice(Plus, a_vec); let b = BigInt::from_slice(Plus, b_vec); @@ -894,7 +895,7 @@ fn test_div_ceil() { } } - for elm in DIV_REM_QUADRUPLES.iter() { + for elm in DIV_REM_QUADRUPLES { let (a_vec, b_vec, c_vec, d_vec) = *elm; let a = BigInt::from_slice(Plus, a_vec); let b = BigInt::from_slice(Plus, b_vec); @@ -910,7 +911,7 @@ fn test_div_ceil() { #[test] fn test_div_rem_euclid() { fn check_sub(a: &BigInt, b: &BigInt, ans_d: &BigInt, ans_m: &BigInt) { - eprintln!("{} {} {} {}", a, b, ans_d, ans_m); + eprintln!("{a} {b} {ans_d} {ans_m}"); assert_eq!(a.div_euclid(b), *ans_d); assert_eq!(a.rem_euclid(b), *ans_m); assert!(*ans_m >= BigInt::zero()); @@ -932,7 +933,7 @@ fn test_div_rem_euclid() { } } - for elm in MUL_TRIPLES.iter() { + for elm in MUL_TRIPLES { let (a_vec, b_vec, c_vec) = *elm; let a = BigInt::from_slice(Plus, a_vec); let b = BigInt::from_slice(Plus, b_vec); @@ -946,7 +947,7 @@ fn test_div_rem_euclid() { } } - for elm in DIV_REM_QUADRUPLES.iter() { + for elm in DIV_REM_QUADRUPLES { let (a_vec, b_vec, c_vec, d_vec) = *elm; let a = BigInt::from_slice(Plus, a_vec); let b = BigInt::from_slice(Plus, b_vec); @@ -961,7 +962,7 @@ fn test_div_rem_euclid() { #[test] fn test_checked_add() { - for elm in SUM_TRIPLES.iter() { + for elm in SUM_TRIPLES { let (a_vec, b_vec, c_vec) = *elm; let a = BigInt::from_slice(Plus, a_vec); let b = BigInt::from_slice(Plus, b_vec); @@ -980,7 +981,7 @@ fn test_checked_add() { #[test] fn test_checked_sub() { - for elm in SUM_TRIPLES.iter() { + for elm in SUM_TRIPLES { let (a_vec, b_vec, c_vec) = *elm; let a = BigInt::from_slice(Plus, a_vec); let b = BigInt::from_slice(Plus, b_vec); @@ -999,7 +1000,7 @@ fn test_checked_sub() { #[test] fn test_checked_mul() { - for elm in MUL_TRIPLES.iter() { + for elm in MUL_TRIPLES { let (a_vec, b_vec, c_vec) = *elm; let a = BigInt::from_slice(Plus, a_vec); let b = BigInt::from_slice(Plus, b_vec); @@ -1012,7 +1013,7 @@ fn test_checked_mul() { assert!((-&b).checked_mul(&a).unwrap() == -&c); } - for elm in DIV_REM_QUADRUPLES.iter() { + for elm in DIV_REM_QUADRUPLES { let (a_vec, b_vec, c_vec, d_vec) = *elm; let a = BigInt::from_slice(Plus, a_vec); let b = BigInt::from_slice(Plus, b_vec); @@ -1025,7 +1026,7 @@ fn test_checked_mul() { } #[test] fn test_checked_div() { - for elm in MUL_TRIPLES.iter() { + for elm in MUL_TRIPLES { let (a_vec, b_vec, c_vec) = *elm; let a = BigInt::from_slice(Plus, a_vec); let b = BigInt::from_slice(Plus, b_vec); @@ -1217,9 +1218,7 @@ fn test_from_str_radix() { // issue 10522, this hit an edge case that caused it to // attempt to allocate a vector of size (-1u) == huge. - let x: BigInt = format!("1{}", repeat("0").take(36).collect::()) - .parse() - .unwrap(); + let x: BigInt = format!("1{}", "0".repeat(36)).parse().unwrap(); let _y = x.to_string(); } @@ -1228,9 +1227,9 @@ fn test_lower_hex() { let a = BigInt::parse_bytes(b"A", 16).unwrap(); let hello = BigInt::parse_bytes(b"-22405534230753963835153736737", 10).unwrap(); - assert_eq!(format!("{:x}", a), "a"); - assert_eq!(format!("{:x}", hello), "-48656c6c6f20776f726c6421"); - assert_eq!(format!("{:♥>+#8x}", a), "♥♥♥♥+0xa"); + assert_eq!(format!("{a:x}"), "a"); + assert_eq!(format!("{hello:x}"), "-48656c6c6f20776f726c6421"); + assert_eq!(format!("{a:♥>+#8x}"), "♥♥♥♥+0xa"); } #[test] @@ -1238,9 +1237,9 @@ fn test_upper_hex() { let a = BigInt::parse_bytes(b"A", 16).unwrap(); let hello = BigInt::parse_bytes(b"-22405534230753963835153736737", 10).unwrap(); - assert_eq!(format!("{:X}", a), "A"); - assert_eq!(format!("{:X}", hello), "-48656C6C6F20776F726C6421"); - assert_eq!(format!("{:♥>+#8X}", a), "♥♥♥♥+0xA"); + assert_eq!(format!("{a:X}"), "A"); + assert_eq!(format!("{hello:X}"), "-48656C6C6F20776F726C6421"); + assert_eq!(format!("{a:♥>+#8X}"), "♥♥♥♥+0xA"); } #[test] @@ -1248,12 +1247,12 @@ fn test_binary() { let a = BigInt::parse_bytes(b"A", 16).unwrap(); let hello = BigInt::parse_bytes(b"-224055342307539", 10).unwrap(); - assert_eq!(format!("{:b}", a), "1010"); + assert_eq!(format!("{a:b}"), "1010"); assert_eq!( - format!("{:b}", hello), + format!("{hello:b}"), "-110010111100011011110011000101101001100011010011" ); - assert_eq!(format!("{:♥>+#8b}", a), "♥+0b1010"); + assert_eq!(format!("{a:♥>+#8b}"), "♥+0b1010"); } #[test] @@ -1261,9 +1260,9 @@ fn test_octal() { let a = BigInt::parse_bytes(b"A", 16).unwrap(); let hello = BigInt::parse_bytes(b"-22405534230753963835153736737", 10).unwrap(); - assert_eq!(format!("{:o}", a), "12"); - assert_eq!(format!("{:o}", hello), "-22062554330674403566756233062041"); - assert_eq!(format!("{:♥>+#8o}", a), "♥♥♥+0o12"); + assert_eq!(format!("{a:o}"), "12"); + assert_eq!(format!("{hello:o}"), "-22062554330674403566756233062041"); + assert_eq!(format!("{a:♥>+#8o}"), "♥♥♥+0o12"); } #[test] @@ -1271,9 +1270,9 @@ fn test_display() { let a = BigInt::parse_bytes(b"A", 16).unwrap(); let hello = BigInt::parse_bytes(b"-22405534230753963835153736737", 10).unwrap(); - assert_eq!(format!("{}", a), "10"); - assert_eq!(format!("{}", hello), "-22405534230753963835153736737"); - assert_eq!(format!("{:♥>+#8}", a), "♥♥♥♥♥+10"); + assert_eq!(format!("{a}"), "10"); + assert_eq!(format!("{hello}"), "-22405534230753963835153736737"); + assert_eq!(format!("{a:♥>+#8}"), "♥♥♥♥♥+10"); } #[test] @@ -1294,10 +1293,10 @@ fn test_negative_shr() { #[test] fn test_iter_sum() { - let result: BigInt = FromPrimitive::from_isize(-1234567).unwrap(); + let result: BigInt = FromPrimitive::from_isize(-1_234_567).unwrap(); let data: Vec = vec![ - FromPrimitive::from_i32(-1000000).unwrap(), - FromPrimitive::from_i32(-200000).unwrap(), + FromPrimitive::from_i32(-1_000_000).unwrap(), + FromPrimitive::from_i32(-200_000).unwrap(), FromPrimitive::from_i32(-30000).unwrap(), FromPrimitive::from_i32(-4000).unwrap(), FromPrimitive::from_i32(-500).unwrap(), @@ -1318,7 +1317,7 @@ fn test_iter_product() { FromPrimitive::from_i32(-1004).unwrap(), FromPrimitive::from_i32(1005).unwrap(), ]; - let result = data.get(0).unwrap() + let result = data.first().unwrap() * data.get(1).unwrap() * data.get(2).unwrap() * data.get(3).unwrap() @@ -1330,8 +1329,8 @@ fn test_iter_product() { #[test] fn test_iter_sum_generic() { - let result: BigInt = FromPrimitive::from_isize(-1234567).unwrap(); - let data = vec![-1000000, -200000, -30000, -4000, -500, -60, -7]; + let result: BigInt = FromPrimitive::from_isize(-1_234_567).unwrap(); + let data = vec![-1_000_000, -200_000, -30000, -4000, -500, -60, -7]; assert_eq!(result, data.iter().sum::()); assert_eq!(result, data.into_iter().sum::()); diff --git a/tests/bigint_bitwise.rs b/tests/bigint_bitwise.rs index 94d92e1d..9ddefffa 100644 --- a/tests/bigint_bitwise.rs +++ b/tests/bigint_bitwise.rs @@ -11,10 +11,10 @@ use crate::ValueVec::*; impl ToBigInt for ValueVec { fn to_bigint(&self) -> Option { - match self { - &N => Some(BigInt::from_slice(Sign::NoSign, &[])), - &P(s) => Some(BigInt::from_slice(Sign::Plus, s)), - &M(s) => Some(BigInt::from_slice(Sign::Minus, s)), + match *self { + N => Some(BigInt::from_slice(Sign::NoSign, &[])), + P(s) => Some(BigInt::from_slice(Sign::Plus, s)), + M(s) => Some(BigInt::from_slice(Sign::Minus, s)), } } } @@ -106,7 +106,7 @@ const I64_VALUES: &[i64] = &[ #[test] fn test_not() { - for &(ref a, ref not) in NOT_VALUES.iter() { + for (a, not) in NOT_VALUES { let a = a.to_bigint().unwrap(); let not = not.to_bigint().unwrap(); @@ -115,23 +115,23 @@ fn test_not() { assert_eq!(!prim_a, prim_not); } - assert_eq!(!a.clone(), not, "!{:x}", a); - assert_eq!(!not.clone(), a, "!{:x}", not); + assert_eq!(!a.clone(), not, "!{a:x}"); + assert_eq!(!not.clone(), a, "!{not:x}"); } } #[test] fn test_not_i64() { - for &prim_a in I64_VALUES.iter() { + for &prim_a in I64_VALUES { let a = prim_a.to_bigint().unwrap(); let not = (!prim_a).to_bigint().unwrap(); - assert_eq!(!a.clone(), not, "!{:x}", a); + assert_eq!(!a.clone(), not, "!{a:x}"); } } #[test] fn test_bitwise() { - for &(ref a, ref b, ref and, ref or, ref xor) in BITWISE_VALUES.iter() { + for (a, b, and, or, xor) in BITWISE_VALUES { let a = a.to_bigint().unwrap(); let b = b.to_bigint().unwrap(); let and = and.to_bigint().unwrap(); @@ -151,27 +151,27 @@ fn test_bitwise() { } } - assert_eq!(a.clone() & &b, and, "{:x} & {:x}", a, b); - assert_eq!(b.clone() & &a, and, "{:x} & {:x}", b, a); - assert_eq!(a.clone() | &b, or, "{:x} | {:x}", a, b); - assert_eq!(b.clone() | &a, or, "{:x} | {:x}", b, a); - assert_eq!(a.clone() ^ &b, xor, "{:x} ^ {:x}", a, b); - assert_eq!(b.clone() ^ &a, xor, "{:x} ^ {:x}", b, a); + assert_eq!(a.clone() & &b, and, "{a:x} & {b:x}"); + assert_eq!(b.clone() & &a, and, "{b:x} & {a:x}"); + assert_eq!(a.clone() | &b, or, "{a:x} | {b:x}"); + assert_eq!(b.clone() | &a, or, "{b:x} | {a:x}"); + assert_eq!(a.clone() ^ &b, xor, "{a:x} ^ {b:x}"); + assert_eq!(b.clone() ^ &a, xor, "{b:x} ^ {a:x}"); } } #[test] fn test_bitwise_i64() { - for &prim_a in I64_VALUES.iter() { + for &prim_a in I64_VALUES { let a = prim_a.to_bigint().unwrap(); - for &prim_b in I64_VALUES.iter() { + for &prim_b in I64_VALUES { let b = prim_b.to_bigint().unwrap(); let and = (prim_a & prim_b).to_bigint().unwrap(); let or = (prim_a | prim_b).to_bigint().unwrap(); let xor = (prim_a ^ prim_b).to_bigint().unwrap(); - assert_eq!(a.clone() & &b, and, "{:x} & {:x}", a, b); - assert_eq!(a.clone() | &b, or, "{:x} | {:x}", a, b); - assert_eq!(a.clone() ^ &b, xor, "{:x} ^ {:x}", a, b); + assert_eq!(a.clone() & &b, and, "{a:x} & {b:x}"); + assert_eq!(a.clone() | &b, or, "{a:x} | {b:x}"); + assert_eq!(a.clone() ^ &b, xor, "{a:x} ^ {b:x}"); } } } diff --git a/tests/bigint_scalar.rs b/tests/bigint_scalar.rs index 2a19fafb..17982b68 100644 --- a/tests/bigint_scalar.rs +++ b/tests/bigint_scalar.rs @@ -19,7 +19,7 @@ fn test_scalar_add() { assert_signed_scalar_assign_op!(x += y == z); } - for elm in SUM_TRIPLES.iter() { + for elm in SUM_TRIPLES { let (a_vec, b_vec, c_vec) = *elm; let a = BigInt::from_slice(Plus, a_vec); let b = BigInt::from_slice(Plus, b_vec); @@ -45,7 +45,7 @@ fn test_scalar_sub() { assert_signed_scalar_assign_op!(x -= y == z); } - for elm in SUM_TRIPLES.iter() { + for elm in SUM_TRIPLES { let (a_vec, b_vec, c_vec) = *elm; let a = BigInt::from_slice(Plus, a_vec); let b = BigInt::from_slice(Plus, b_vec); @@ -71,7 +71,7 @@ fn test_scalar_mul() { assert_signed_scalar_assign_op!(x *= y == z); } - for elm in MUL_TRIPLES.iter() { + for elm in MUL_TRIPLES { let (a_vec, b_vec, c_vec) = *elm; let a = BigInt::from_slice(Plus, a_vec); let b = BigInt::from_slice(Plus, b_vec); @@ -100,7 +100,9 @@ fn test_scalar_div_rem() { assert!(r == *ans_r); let b = BigInt::from(b); - let (a, ans_q, ans_r) = (a.clone(), ans_q.clone(), ans_r.clone()); + let a = a.clone(); + let ans_q = ans_q.clone(); + let ans_r = ans_r.clone(); assert_signed_scalar_op!(a / b == ans_q); assert_signed_scalar_op!(a % b == ans_r); assert_signed_scalar_assign_op!(a /= b == ans_q); @@ -118,7 +120,7 @@ fn test_scalar_div_rem() { check_sub(&a.neg(), b, &q.neg(), &r.neg()); } - for elm in MUL_TRIPLES.iter() { + for elm in MUL_TRIPLES { let (a_vec, b_vec, c_vec) = *elm; let a = BigInt::from_slice(Plus, a_vec); let b = BigInt::from_slice(Plus, b_vec); @@ -135,7 +137,7 @@ fn test_scalar_div_rem() { } } - for elm in DIV_REM_QUADRUPLES.iter() { + for elm in DIV_REM_QUADRUPLES { let (a_vec, b_vec, c_vec, d_vec) = *elm; let a = BigInt::from_slice(Plus, a_vec); let c = BigInt::from_slice(Plus, c_vec); diff --git a/tests/biguint.rs b/tests/biguint.rs index 4e2c6259..ee24c67b 100644 --- a/tests/biguint.rs +++ b/tests/biguint.rs @@ -90,7 +90,7 @@ fn test_to_bytes_le() { #[test] fn test_cmp() { let data: [&[_]; 7] = [&[], &[1], &[2], &[!0], &[0, 1], &[2, 1], &[1, 1, 1]]; - let data: Vec = data.iter().map(|v| BigUint::from_slice(*v)).collect(); + let data: Vec = data.iter().map(|v| BigUint::from_slice(v)).collect(); for (i, ni) in data.iter().enumerate() { for (j0, nj) in data[i..].iter().enumerate() { let j = j0 + i; @@ -98,26 +98,26 @@ fn test_cmp() { assert_eq!(ni.cmp(nj), Equal); assert_eq!(nj.cmp(ni), Equal); assert_eq!(ni, nj); - assert!(!(ni != nj)); + assert!((ni == nj)); assert!(ni <= nj); assert!(ni >= nj); - assert!(!(ni < nj)); - assert!(!(ni > nj)); + assert!((ni >= nj)); + assert!((ni <= nj)); } else { assert_eq!(ni.cmp(nj), Less); assert_eq!(nj.cmp(ni), Greater); - assert!(!(ni == nj)); + assert!((ni != nj)); assert!(ni != nj); assert!(ni <= nj); - assert!(!(ni >= nj)); + assert!((ni < nj)); assert!(ni < nj); - assert!(!(ni > nj)); + assert!((ni <= nj)); - assert!(!(nj <= ni)); + assert!((nj > ni)); assert!(nj >= ni); - assert!(!(nj < ni)); + assert!((nj >= ni)); assert!(nj > ni); } } @@ -146,6 +146,7 @@ fn test_hash() { } // LEFT, RIGHT, AND, OR, XOR +#[allow(clippy::type_complexity)] const BIT_TESTS: &[(&[u32], &[u32], &[u32], &[u32], &[u32])] = &[ (&[], &[], &[], &[], &[]), (&[1, 0, 1], &[1, 1], &[1], &[1, 1, 1], &[0, 1, 1]), @@ -620,7 +621,7 @@ fn test_convert_f32() { check(&(BigUint::from((1u64 << 24) - 1) << (128 - 24)), f32::MAX); // keeping all 24 digits with the bits at different offsets to the BigDigits - let x: u32 = 0b00000000101111011111011011011101; + let x: u32 = 0b0000_0000_1011_1101_1111_0110_1101_1101; let mut f = x as f32; let mut b = BigUint::from(x); for _ in 0..64 { @@ -630,7 +631,7 @@ fn test_convert_f32() { } // this number when rounded to f64 then f32 isn't the same as when rounded straight to f32 - let n: u64 = 0b0000000000111111111111111111111111011111111111111111111111111111; + let n: u64 = 0b0000_0000_0011_1111_1111_1111_1111_1111_1101_1111_1111_1111_1111_1111_1111_1111; assert!((n as f64) as f32 != n as f32); assert_eq!(BigUint::from(n).to_f32(), Some(n as f32)); @@ -708,7 +709,7 @@ fn test_convert_f64() { check(&(BigUint::from((1u64 << 53) - 1) << (1024 - 53)), f64::MAX); // keeping all 53 digits with the bits at different offsets to the BigDigits - let x: u64 = 0b0000000000011110111110110111111101110111101111011111011011011101; + let x: u64 = 0b0000_0000_0001_1110_1111_1011_0111_1111_0111_0111_1011_1101_1111_0110_1101_1101; let mut f = x as f64; let mut b = BigUint::from(x); for _ in 0..128 { @@ -793,8 +794,8 @@ fn test_convert_from_uint() { }; } - check!(u8, BigUint::from_slice(&[u8::MAX as u32])); - check!(u16, BigUint::from_slice(&[u16::MAX as u32])); + check!(u8, BigUint::from_slice(&[u32::from(u8::MAX)])); + check!(u16, BigUint::from_slice(&[u32::from(u16::MAX)])); check!(u32, BigUint::from_slice(&[u32::MAX])); check!(u64, BigUint::from_slice(&[u32::MAX, u32::MAX])); check!( @@ -806,7 +807,7 @@ fn test_convert_from_uint() { #[test] fn test_add() { - for elm in SUM_TRIPLES.iter() { + for elm in SUM_TRIPLES { let (a_vec, b_vec, c_vec) = *elm; let a = BigUint::from_slice(a_vec); let b = BigUint::from_slice(b_vec); @@ -821,7 +822,7 @@ fn test_add() { #[test] fn test_sub() { - for elm in SUM_TRIPLES.iter() { + for elm in SUM_TRIPLES { let (a_vec, b_vec, c_vec) = *elm; let a = BigUint::from_slice(a_vec); let b = BigUint::from_slice(b_vec); @@ -843,7 +844,7 @@ fn test_sub_fail_on_underflow() { #[test] fn test_mul() { - for elm in MUL_TRIPLES.iter() { + for elm in MUL_TRIPLES { let (a_vec, b_vec, c_vec) = *elm; let a = BigUint::from_slice(a_vec); let b = BigUint::from_slice(b_vec); @@ -855,7 +856,7 @@ fn test_mul() { assert_assign_op!(b *= a == c); } - for elm in DIV_REM_QUADRUPLES.iter() { + for elm in DIV_REM_QUADRUPLES { let (a_vec, b_vec, c_vec, d_vec) = *elm; let a = BigUint::from_slice(a_vec); let b = BigUint::from_slice(b_vec); @@ -869,7 +870,7 @@ fn test_mul() { #[test] fn test_div_rem() { - for elm in MUL_TRIPLES.iter() { + for elm in MUL_TRIPLES { let (a_vec, b_vec, c_vec) = *elm; let a = BigUint::from_slice(a_vec); let b = BigUint::from_slice(b_vec); @@ -891,7 +892,7 @@ fn test_div_rem() { } } - for elm in DIV_REM_QUADRUPLES.iter() { + for elm in DIV_REM_QUADRUPLES { let (a_vec, b_vec, c_vec, d_vec) = *elm; let a = BigUint::from_slice(a_vec); let b = BigUint::from_slice(b_vec); @@ -932,7 +933,7 @@ fn test_div_ceil() { } } - for elm in MUL_TRIPLES.iter() { + for elm in MUL_TRIPLES { let (a_vec, b_vec, c_vec) = *elm; let a = BigUint::from_slice(a_vec); let b = BigUint::from_slice(b_vec); @@ -946,7 +947,7 @@ fn test_div_ceil() { } } - for elm in DIV_REM_QUADRUPLES.iter() { + for elm in DIV_REM_QUADRUPLES { let (a_vec, b_vec, c_vec, d_vec) = *elm; let a = BigUint::from_slice(a_vec); let b = BigUint::from_slice(b_vec); @@ -966,7 +967,7 @@ fn test_div_rem_euclid() { assert_eq!(a.rem_euclid(b), *m); } - for elm in MUL_TRIPLES.iter() { + for elm in MUL_TRIPLES { let (a_vec, b_vec, c_vec) = *elm; let a = BigUint::from_slice(a_vec); let b = BigUint::from_slice(b_vec); @@ -980,7 +981,7 @@ fn test_div_rem_euclid() { } } - for elm in DIV_REM_QUADRUPLES.iter() { + for elm in DIV_REM_QUADRUPLES { let (a_vec, b_vec, c_vec, d_vec) = *elm; let a = BigUint::from_slice(a_vec); let b = BigUint::from_slice(b_vec); @@ -995,7 +996,7 @@ fn test_div_rem_euclid() { #[test] fn test_checked_add() { - for elm in SUM_TRIPLES.iter() { + for elm in SUM_TRIPLES { let (a_vec, b_vec, c_vec) = *elm; let a = BigUint::from_slice(a_vec); let b = BigUint::from_slice(b_vec); @@ -1008,7 +1009,7 @@ fn test_checked_add() { #[test] fn test_checked_sub() { - for elm in SUM_TRIPLES.iter() { + for elm in SUM_TRIPLES { let (a_vec, b_vec, c_vec) = *elm; let a = BigUint::from_slice(a_vec); let b = BigUint::from_slice(b_vec); @@ -1028,7 +1029,7 @@ fn test_checked_sub() { #[test] fn test_checked_mul() { - for elm in MUL_TRIPLES.iter() { + for elm in MUL_TRIPLES { let (a_vec, b_vec, c_vec) = *elm; let a = BigUint::from_slice(a_vec); let b = BigUint::from_slice(b_vec); @@ -1038,7 +1039,7 @@ fn test_checked_mul() { assert!(b.checked_mul(&a).unwrap() == c); } - for elm in DIV_REM_QUADRUPLES.iter() { + for elm in DIV_REM_QUADRUPLES { let (a_vec, b_vec, c_vec, d_vec) = *elm; let a = BigUint::from_slice(a_vec); let b = BigUint::from_slice(b_vec); @@ -1075,7 +1076,7 @@ fn test_mul_overflow_2() { #[test] fn test_checked_div() { - for elm in MUL_TRIPLES.iter() { + for elm in MUL_TRIPLES { let (a_vec, b_vec, c_vec) = *elm; let a = BigUint::from_slice(a_vec); let b = BigUint::from_slice(b_vec); @@ -1220,14 +1221,8 @@ fn to_str_pairs() -> Vec<(BigUint, Vec<(u32, String)>)> { ( BigUint::from_slice(&[1, 2]), vec![ - ( - 2, - format!("10{}1", repeat("0").take(bits - 1).collect::()), - ), - ( - 4, - format!("2{}1", repeat("0").take(bits / 2 - 1).collect::()), - ), + (2, format!("10{}1", "0".repeat(bits - 1))), + (4, format!("2{}1", "0".repeat(bits / 2 - 1))), ( 10, match bits { @@ -1237,10 +1232,7 @@ fn to_str_pairs() -> Vec<(BigUint, Vec<(u32, String)>)> { _ => panic!(), }, ), - ( - 16, - format!("2{}1", repeat("0").take(bits / 4 - 1).collect::()), - ), + (16, format!("2{}1", "0".repeat(bits / 4 - 1))), ], ), ( @@ -1248,18 +1240,14 @@ fn to_str_pairs() -> Vec<(BigUint, Vec<(u32, String)>)> { vec![ ( 2, - format!( - "11{}10{}1", - repeat("0").take(bits - 2).collect::(), - repeat("0").take(bits - 1).collect::() - ), + format!("11{}10{}1", "0".repeat(bits - 2), "0".repeat(bits - 1)), ), ( 4, format!( "3{}2{}1", - repeat("0").take(bits / 2 - 1).collect::(), - repeat("0").take(bits / 2 - 1).collect::() + "0".repeat(bits / 2 - 1), + "0".repeat(bits / 2 - 1) ), ), ( @@ -1284,8 +1272,8 @@ fn to_str_pairs() -> Vec<(BigUint, Vec<(u32, String)>)> { 16, format!( "3{}2{}1", - repeat("0").take(bits / 4 - 1).collect::(), - repeat("0").take(bits / 4 - 1).collect::() + "0".repeat(bits / 4 - 1), + "0".repeat(bits / 4 - 1) ), ), ], @@ -1296,10 +1284,10 @@ fn to_str_pairs() -> Vec<(BigUint, Vec<(u32, String)>)> { #[test] fn test_to_str_radix() { let r = to_str_pairs(); - for num_pair in r.iter() { - let &(ref n, ref rs) = num_pair; - for str_pair in rs.iter() { - let &(ref radix, ref str) = str_pair; + for num_pair in r { + let (n, rs) = num_pair; + for str_pair in &rs { + let (radix, str) = str_pair; assert_eq!(n.to_str_radix(*radix), *str); } } @@ -1630,9 +1618,9 @@ fn test_from_and_to_radix() { fn test_from_str_radix() { let r = to_str_pairs(); for num_pair in r.iter() { - let &(ref n, ref rs) = num_pair; + let (n, rs) = num_pair; for str_pair in rs.iter() { - let &(ref radix, ref str) = str_pair; + let (radix, str) = str_pair; assert_eq!(n, &BigUint::from_str_radix(str, *radix).unwrap()); } } @@ -1686,9 +1674,9 @@ fn test_lower_hex() { let a = BigUint::parse_bytes(b"A", 16).unwrap(); let hello = BigUint::parse_bytes(b"22405534230753963835153736737", 10).unwrap(); - assert_eq!(format!("{:x}", a), "a"); - assert_eq!(format!("{:x}", hello), "48656c6c6f20776f726c6421"); - assert_eq!(format!("{:♥>+#8x}", a), "♥♥♥♥+0xa"); + assert_eq!(format!("{a:x}"), "a"); + assert_eq!(format!("{hello:x}"), "48656c6c6f20776f726c6421"); + assert_eq!(format!("{a:♥>+#8x}"), "♥♥♥♥+0xa"); } #[test] @@ -1696,9 +1684,9 @@ fn test_upper_hex() { let a = BigUint::parse_bytes(b"A", 16).unwrap(); let hello = BigUint::parse_bytes(b"22405534230753963835153736737", 10).unwrap(); - assert_eq!(format!("{:X}", a), "A"); - assert_eq!(format!("{:X}", hello), "48656C6C6F20776F726C6421"); - assert_eq!(format!("{:♥>+#8X}", a), "♥♥♥♥+0xA"); + assert_eq!(format!("{a:X}"), "A"); + assert_eq!(format!("{hello:X}"), "48656C6C6F20776F726C6421"); + assert_eq!(format!("{a:♥>+#8X}"), "♥♥♥♥+0xA"); } #[test] @@ -1706,12 +1694,12 @@ fn test_binary() { let a = BigUint::parse_bytes(b"A", 16).unwrap(); let hello = BigUint::parse_bytes(b"224055342307539", 10).unwrap(); - assert_eq!(format!("{:b}", a), "1010"); + assert_eq!(format!("{a:b}"), "1010"); assert_eq!( - format!("{:b}", hello), + format!("{hello:b}"), "110010111100011011110011000101101001100011010011" ); - assert_eq!(format!("{:♥>+#8b}", a), "♥+0b1010"); + assert_eq!(format!("{a:♥>+#8b}"), "♥+0b1010"); } #[test] @@ -1719,9 +1707,9 @@ fn test_octal() { let a = BigUint::parse_bytes(b"A", 16).unwrap(); let hello = BigUint::parse_bytes(b"22405534230753963835153736737", 10).unwrap(); - assert_eq!(format!("{:o}", a), "12"); - assert_eq!(format!("{:o}", hello), "22062554330674403566756233062041"); - assert_eq!(format!("{:♥>+#8o}", a), "♥♥♥+0o12"); + assert_eq!(format!("{a:o}"), "12"); + assert_eq!(format!("{hello:o}"), "22062554330674403566756233062041"); + assert_eq!(format!("{a:♥>+#8o}"), "♥♥♥+0o12"); } #[test] @@ -1729,9 +1717,9 @@ fn test_display() { let a = BigUint::parse_bytes(b"A", 16).unwrap(); let hello = BigUint::parse_bytes(b"22405534230753963835153736737", 10).unwrap(); - assert_eq!(format!("{}", a), "10"); - assert_eq!(format!("{}", hello), "22405534230753963835153736737"); - assert_eq!(format!("{:♥>+#8}", a), "♥♥♥♥♥+10"); + assert_eq!(format!("{a}"), "10"); + assert_eq!(format!("{hello}"), "22405534230753963835153736737"); + assert_eq!(format!("{a:♥>+#8}"), "♥♥♥♥♥+10"); } #[test] @@ -1776,10 +1764,10 @@ fn test_bits() { #[test] fn test_iter_sum() { - let result: BigUint = FromPrimitive::from_isize(1234567).unwrap(); + let result: BigUint = FromPrimitive::from_isize(1_234_567).unwrap(); let data: Vec = vec![ - FromPrimitive::from_u32(1000000).unwrap(), - FromPrimitive::from_u32(200000).unwrap(), + FromPrimitive::from_u32(1_000_000).unwrap(), + FromPrimitive::from_u32(200_000).unwrap(), FromPrimitive::from_u32(30000).unwrap(), FromPrimitive::from_u32(4000).unwrap(), FromPrimitive::from_u32(500).unwrap(), @@ -1800,7 +1788,7 @@ fn test_iter_product() { FromPrimitive::from_u32(1004).unwrap(), FromPrimitive::from_u32(1005).unwrap(), ]; - let result = data.get(0).unwrap() + let result = data.first().unwrap() * data.get(1).unwrap() * data.get(2).unwrap() * data.get(3).unwrap() diff --git a/tests/biguint_scalar.rs b/tests/biguint_scalar.rs index 7c34f7ef..a6325e08 100644 --- a/tests/biguint_scalar.rs +++ b/tests/biguint_scalar.rs @@ -17,7 +17,7 @@ fn test_scalar_add() { assert_unsigned_scalar_assign_op!(x += y == z); } - for elm in SUM_TRIPLES.iter() { + for elm in SUM_TRIPLES { let (a_vec, b_vec, c_vec) = *elm; let a = BigUint::from_slice(a_vec); let b = BigUint::from_slice(b_vec); @@ -36,7 +36,7 @@ fn test_scalar_sub() { assert_unsigned_scalar_assign_op!(x -= y == z); } - for elm in SUM_TRIPLES.iter() { + for elm in SUM_TRIPLES { let (a_vec, b_vec, c_vec) = *elm; let a = BigUint::from_slice(a_vec); let b = BigUint::from_slice(b_vec); @@ -55,7 +55,7 @@ fn test_scalar_mul() { assert_unsigned_scalar_assign_op!(x *= y == z); } - for elm in MUL_TRIPLES.iter() { + for elm in MUL_TRIPLES { let (a_vec, b_vec, c_vec) = *elm; let a = BigUint::from_slice(a_vec); let b = BigUint::from_slice(b_vec); @@ -82,7 +82,7 @@ fn test_scalar_div_rem() { assert_unsigned_scalar_assign_op!(x %= y == r); } - for elm in MUL_TRIPLES.iter() { + for elm in MUL_TRIPLES { let (a_vec, b_vec, c_vec) = *elm; let a = BigUint::from_slice(a_vec); let b = BigUint::from_slice(b_vec); @@ -97,7 +97,7 @@ fn test_scalar_div_rem() { } } - for elm in DIV_REM_QUADRUPLES.iter() { + for elm in DIV_REM_QUADRUPLES { let (a_vec, b_vec, c_vec, d_vec) = *elm; let a = BigUint::from_slice(a_vec); let b = BigUint::from_slice(b_vec); diff --git a/tests/consts/mod.rs b/tests/consts/mod.rs index 457fbd36..33ed5203 100644 --- a/tests/consts/mod.rs +++ b/tests/consts/mod.rs @@ -41,6 +41,7 @@ pub const MUL_TRIPLES: &[(&[u32], &[u32], &[u32])] = &[ (&[0, 0, 1], &[0, 0, 0, 1], &[0, 0, 0, 0, 0, 1]), ]; +#[allow(clippy::type_complexity)] pub const DIV_REM_QUADRUPLES: &[(&[u32], &[u32], &[u32], &[u32])] = &[ (&[1], &[2], &[], &[1]), (&[3], &[2], &[1], &[1]), diff --git a/tests/modpow.rs b/tests/modpow.rs index d7a247b0..5cf84cef 100644 --- a/tests/modpow.rs +++ b/tests/modpow.rs @@ -115,7 +115,7 @@ mod bigint { fn check_modpow>(b: T, e: T, m: T, r: T) { fn check(b: &BigInt, e: &BigInt, m: &BigInt, r: &BigInt) { - assert_eq!(&b.modpow(e, m), r, "{} ** {} (mod {}) != {}", b, e, m, r); + assert_eq!(&b.modpow(e, m), r, "{b} ** {e} (mod {m}) != {r}"); let even_m = m << 1u8; let even_modpow = b.modpow(e, m); diff --git a/tests/roots.rs b/tests/roots.rs index 7110adf9..f9fd51f5 100644 --- a/tests/roots.rs +++ b/tests/roots.rs @@ -5,12 +5,12 @@ mod biguint { fn check>(x: T, n: u32) { let x: BigUint = x.into(); let root = x.nth_root(n); - println!("check {}.nth_root({}) = {}", x, n, root); + println!("check {x}.nth_root({n}) = {root}"); if n == 2 { - assert_eq!(root, x.sqrt()) + assert_eq!(root, x.sqrt()); } else if n == 3 { - assert_eq!(root, x.cbrt()) + assert_eq!(root, x.cbrt()); } let lo = root.pow(n); @@ -120,9 +120,9 @@ mod bigint { let res = big_x.nth_root(n); if n == 2 { - assert_eq!(&res, &big_x.sqrt()) + assert_eq!(&res, &big_x.sqrt()); } else if n == 3 { - assert_eq!(&res, &big_x.cbrt()) + assert_eq!(&res, &big_x.cbrt()); } if big_x.is_negative() {