lexical_util/
mul.rs

1//! Fast multiplication routines.
2
3use crate::num::{as_cast, UnsignedInteger};
4
5/// 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
12    Full: UnsignedInteger,
13    Half: UnsignedInteger,
14{
15    // Extract high-and-low masks.
16    let x1 = x >> Half::BITS as i32;
17    let x0 = x & as_cast(Half::MAX);
18    let y1 = y >> Half::BITS as i32;
19    let y0 = y & as_cast(Half::MAX);
20
21    let w0 = x0 * y0;
22    let tmp = (x1 * y0) + (w0 >> Half::BITS as i32);
23    let w1 = tmp & as_cast(Half::MAX);
24    let w2 = tmp >> Half::BITS as i32;
25    let w1 = w1 + x0 * y1;
26    let hi = (x1 * y1) + w2 + (w1 >> Half::BITS as i32);
27    let lo = x.wrapping_mul(y);
28
29    (hi, lo)
30}
31
32/// 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
39    Full: UnsignedInteger,
40    Half: UnsignedInteger,
41{
42    // Extract high-and-low masks.
43    let x1 = x >> Half::BITS as i32;
44    let x0 = x & as_cast(Half::MAX);
45    let y1 = y >> Half::BITS as i32;
46    let y0 = y & as_cast(Half::MAX);
47
48    let w0 = x0 * y0;
49    let m = (x0 * y1) + (w0 >> Half::BITS as i32);
50    let w1 = m & as_cast(Half::MAX);
51    let w2 = m >> Half::BITS as i32;
52
53    let w3 = (x1 * y0 + w1) >> Half::BITS as i32;
54
55    x1 * y1 + w2 + w3
56}