Skip to content

Commit 9b24a1f

Browse files
authored
Rollup merge of #101995 - scottmcm:carrying-mul-example, r=Mark-Simulacrum
Add another example for `uN::carrying_mul` The prose talks about doing this, so might as well add a simple code example of it too.
2 parents 5377c31 + 690aaef commit 9b24a1f

File tree

1 file changed

+30
-0
lines changed

1 file changed

+30
-0
lines changed

library/core/src/num/mod.rs

+30
Original file line numberDiff line numberDiff line change
@@ -113,6 +113,9 @@ macro_rules! widening_impl {
113113
/// This returns the low-order (wrapping) bits and the high-order (overflow) bits
114114
/// of the result as two separate values, in that order.
115115
///
116+
/// If you also need to add a carry to the wide result, then you want
117+
/// [`Self::carrying_mul`] instead.
118+
///
116119
/// # Examples
117120
///
118121
/// Basic usage:
@@ -148,6 +151,8 @@ macro_rules! widening_impl {
148151
/// additional amount of overflow. This allows for chaining together multiple
149152
/// multiplications to create "big integers" which represent larger values.
150153
///
154+
/// If you don't need the `carry`, then you can use [`Self::widening_mul`] instead.
155+
///
151156
/// # Examples
152157
///
153158
/// Basic usage:
@@ -167,6 +172,31 @@ macro_rules! widening_impl {
167172
)]
168173
/// ```
169174
///
175+
/// This is the core operation needed for scalar multiplication when
176+
/// implementing it for wider-than-native types.
177+
///
178+
/// ```
179+
/// #![feature(bigint_helper_methods)]
180+
/// fn scalar_mul_eq(little_endian_digits: &mut Vec<u16>, multiplicand: u16) {
181+
/// let mut carry = 0;
182+
/// for d in little_endian_digits.iter_mut() {
183+
/// (*d, carry) = d.carrying_mul(multiplicand, carry);
184+
/// }
185+
/// if carry != 0 {
186+
/// little_endian_digits.push(carry);
187+
/// }
188+
/// }
189+
///
190+
/// let mut v = vec![10, 20];
191+
/// scalar_mul_eq(&mut v, 3);
192+
/// assert_eq!(v, [30, 60]);
193+
///
194+
/// assert_eq!(0x87654321_u64 * 0xFEED, 0x86D3D159E38D);
195+
/// let mut v = vec![0x4321, 0x8765];
196+
/// scalar_mul_eq(&mut v, 0xFEED);
197+
/// assert_eq!(v, [0xE38D, 0xD159, 0x86D3]);
198+
/// ```
199+
///
170200
/// If `carry` is zero, this is similar to [`overflowing_mul`](Self::overflowing_mul),
171201
/// except that it gives the value of the overflow instead of just whether one happened:
172202
///

0 commit comments

Comments
 (0)