Skip to main content

cupcake/integer_arith/
util.rs

1// Copyright (c) Facebook, Inc. and its affiliates.
2//
3// This source code is licensed under the MIT license found in the
4// LICENSE file in the root directory of this source tree.
5
6/// computes floor(a*b/pow(2,64))
7pub fn mul_high_word(a: u64, b:u64) -> u64{
8    ((a as u128 * b as u128) >> 64) as u64
9}
10
11/// computes floor(w*pow(2,64)/q)
12pub fn compute_harvey_ratio(w: u64, q: u64) -> u64{
13    (((w as u128) << 64 )/ q as u128) as u64
14}
15
16pub fn mul_low_word(a: u64, b: u64) -> u64 {
17    let res = (a as u128) * (b as u128);
18    (res >> 64) as u64
19}
20
21#[cfg(test)]
22mod tests {
23  use super::*;
24
25  #[test]
26  fn test_mul_high_word(){
27    assert_eq!(mul_high_word(1,1), 0);
28    assert_eq!(mul_high_word(1u64 << 63,0), 0);
29    assert_eq!(mul_high_word(1u64 << 63,2), 1);
30    assert_eq!(mul_high_word(1u64 << 63,1u64 << 63), 1u64 << 62);
31  }
32
33  #[test]
34  fn test_compute_harvey_ratio(){
35    assert_eq!(compute_harvey_ratio(0,100), 0);
36    assert_eq!(compute_harvey_ratio(1,100), 184467440737095516);
37  }
38}