Skip to content

Commit 8b7d103

Browse files
simplify Int::wrapping_mul
simplify Int::wrapping_mul and add test Signed-off-by: Andrew Whitehead <cywolf@gmail.com>
1 parent 8c63b02 commit 8b7d103

File tree

1 file changed

+44
-5
lines changed

1 file changed

+44
-5
lines changed

src/int/mul.rs

Lines changed: 44 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -93,10 +93,12 @@ impl<const LIMBS: usize> Int<LIMBS> {
9393
/// Multiply `self` by `rhs`, wrapping the result in case of overflow.
9494
/// This is equivalent to `(self * rhs) % (Uint::<LIMBS>::MAX + 1)`.
9595
pub const fn wrapping_mul<const RHS_LIMBS: usize>(&self, rhs: &Int<RHS_LIMBS>) -> Self {
96-
let (abs_lhs, lhs_sgn) = self.abs_sign();
97-
let (abs_rhs, rhs_sgn) = rhs.abs_sign();
98-
let lo = Self(abs_lhs.wrapping_mul(&abs_rhs));
99-
lo.wrapping_neg_if(lhs_sgn.xor(rhs_sgn))
96+
if RHS_LIMBS >= LIMBS {
97+
Self(self.0.wrapping_mul(&rhs.0))
98+
} else {
99+
let (abs_rhs, rhs_sgn) = rhs.abs_sign();
100+
Self(self.0.wrapping_mul(&abs_rhs).wrapping_neg_if(rhs_sgn))
101+
}
100102
}
101103
}
102104

@@ -198,7 +200,7 @@ impl<const LIMBS: usize> MulAssign<&Checked<Int<LIMBS>>> for Checked<Int<LIMBS>>
198200

199201
#[cfg(test)]
200202
mod tests {
201-
use crate::{ConstChoice, I64, I128, I256, Int, U128, U256};
203+
use crate::{ConstChoice, I64, I128, I256, Int, U64, U128, U256};
202204

203205
#[test]
204206
#[allow(clippy::init_numbered_fields)]
@@ -343,6 +345,43 @@ mod tests {
343345
);
344346
}
345347

348+
#[test]
349+
fn test_wrapping_mul_mixed() {
350+
let a = U64::from_u64(0x0011223344556677);
351+
let b = U128::from_u128(0x8899aabbccddeeff_8899aabbccddeeff);
352+
let expected = a.as_int().concatenating_mul(b.as_int());
353+
assert_eq!(a.as_int().wrapping_mul(b.as_int()), expected.resize());
354+
assert_eq!(b.as_int().wrapping_mul(a.as_int()), expected.resize());
355+
assert_eq!(
356+
a.as_int().wrapping_neg().wrapping_mul(b.as_int()),
357+
expected.wrapping_neg().resize()
358+
);
359+
assert_eq!(
360+
a.as_int().wrapping_mul(&b.as_int().wrapping_neg()),
361+
expected.wrapping_neg().resize()
362+
);
363+
assert_eq!(
364+
b.as_int().wrapping_neg().wrapping_mul(a.as_int()),
365+
expected.wrapping_neg().resize()
366+
);
367+
assert_eq!(
368+
b.as_int().wrapping_mul(&a.as_int().wrapping_neg()),
369+
expected.wrapping_neg().resize()
370+
);
371+
assert_eq!(
372+
a.as_int()
373+
.wrapping_neg()
374+
.wrapping_mul(&b.as_int().wrapping_neg()),
375+
expected.resize()
376+
);
377+
assert_eq!(
378+
b.as_int()
379+
.wrapping_neg()
380+
.wrapping_mul(&a.as_int().wrapping_neg()),
381+
expected.resize()
382+
);
383+
}
384+
346385
#[test]
347386
fn test_saturating_mul() {
348387
// wrapping

0 commit comments

Comments
 (0)