1//! Fast multiplication routines.
23use crate::num::{as_cast, UnsignedInteger};
45/// Multiply two unsigned, integral values, and return the hi and lo product.
6///
7/// The `full` type is the full type size, while the `half` type is the type
8/// with exactly half the bits.
9#[inline(always)]
10pub fn mul<Full, Half>(x: Full, y: Full) -> (Full, Full)
11where
12Full: UnsignedInteger,
13 Half: UnsignedInteger,
14{
15// Extract high-and-low masks.
16let x1 = x >> Half::BITS as i32;
17let x0 = x & as_cast(Half::MAX);
18let y1 = y >> Half::BITS as i32;
19let y0 = y & as_cast(Half::MAX);
2021let w0 = x0 * y0;
22let tmp = (x1 * y0) + (w0 >> Half::BITS as i32);
23let w1 = tmp & as_cast(Half::MAX);
24let w2 = tmp >> Half::BITS as i32;
25let w1 = w1 + x0 * y1;
26let hi = (x1 * y1) + w2 + (w1 >> Half::BITS as i32);
27let lo = x.wrapping_mul(y);
2829 (hi, lo)
30}
3132/// Multiply two unsigned, integral values, and return the hi product.
33///
34/// The `full` type is the full type size, while the `half` type is the type
35/// with exactly half the bits.
36#[inline(always)]
37pub fn mulhi<Full, Half>(x: Full, y: Full) -> Full
38where
39Full: UnsignedInteger,
40 Half: UnsignedInteger,
41{
42// Extract high-and-low masks.
43let x1 = x >> Half::BITS as i32;
44let x0 = x & as_cast(Half::MAX);
45let y1 = y >> Half::BITS as i32;
46let y0 = y & as_cast(Half::MAX);
4748let w0 = x0 * y0;
49let m = (x0 * y1) + (w0 >> Half::BITS as i32);
50let w1 = m & as_cast(Half::MAX);
51let w2 = m >> Half::BITS as i32;
5253let w3 = (x1 * y0 + w1) >> Half::BITS as i32;
5455 x1 * y1 + w2 + w3
56}