Skip to content

Commit 6c41997

Browse files
authored
Unrolled build for rust-lang#135750
Rollup merge of rust-lang#135750 - scottmcm:cma-example, r=cuviper Add an example of using `carrying_mul_add` to write wider multiplication Just the basic quadratic version that you wouldn't actually use for really-big integers, but it's nice and short so is useful as for a demonstration of why you might find `carrying_mul_add` useful :) cc rust-lang#85532 ``````@clarfonthey``````
2 parents a24bdc6 + b2b12ae commit 6c41997

File tree

1 file changed

+31
-2
lines changed

1 file changed

+31
-2
lines changed

library/core/src/num/uint_macros.rs

+31-2
Original file line numberDiff line numberDiff line change
@@ -2663,8 +2663,8 @@ macro_rules! uint_impl {
26632663
///
26642664
/// Basic usage:
26652665
///
2666-
/// Please note that this example is shared between integer types.
2667-
/// Which explains why `u32` is used here.
2666+
/// Please note that this example is shared between integer types,
2667+
/// which explains why `u32` is used here.
26682668
///
26692669
/// ```
26702670
/// #![feature(bigint_helper_methods)]
@@ -2677,6 +2677,35 @@ macro_rules! uint_impl {
26772677
"(", stringify!($SelfT), "::MAX, ", stringify!($SelfT), "::MAX));"
26782678
)]
26792679
/// ```
2680+
///
2681+
/// This is the core per-digit operation for "grade school" O(n²) multiplication.
2682+
///
2683+
/// Please note that this example is shared between integer types,
2684+
/// using `u8` for simplicity of the demonstration.
2685+
///
2686+
/// ```
2687+
/// #![feature(bigint_helper_methods)]
2688+
///
2689+
/// fn quadratic_mul<const N: usize>(a: [u8; N], b: [u8; N]) -> [u8; N] {
2690+
/// let mut out = [0; N];
2691+
/// for j in 0..N {
2692+
/// let mut carry = 0;
2693+
/// for i in 0..(N - j) {
2694+
/// (out[j + i], carry) = u8::carrying_mul_add(a[i], b[j], out[j + i], carry);
2695+
/// }
2696+
/// }
2697+
/// out
2698+
/// }
2699+
///
2700+
/// // -1 * -1 == 1
2701+
/// assert_eq!(quadratic_mul([0xFF; 3], [0xFF; 3]), [1, 0, 0]);
2702+
///
2703+
/// assert_eq!(u32::wrapping_mul(0x9e3779b9, 0x7f4a7c15), 0xCFFC982D);
2704+
/// assert_eq!(
2705+
/// quadratic_mul(u32::to_le_bytes(0x9e3779b9), u32::to_le_bytes(0x7f4a7c15)),
2706+
/// u32::to_le_bytes(0xCFFC982D)
2707+
/// );
2708+
/// ```
26802709
#[unstable(feature = "bigint_helper_methods", issue = "85532")]
26812710
#[rustc_const_unstable(feature = "bigint_helper_methods", issue = "85532")]
26822711
#[must_use = "this returns the result of the operation, \

0 commit comments

Comments
 (0)