| 1 |
#include <pbcopper/utility/FastMod.h> |
| 2 |
|
| 3 |
namespace PacBio { |
| 4 |
namespace Utility { |
| 5 |
|
| 6 |
__uint128_t ComputeMultInverse64(uint64_t d) noexcept { return (__uint128_t(-1) / d) + 1; } |
| 7 |
|
| 8 |
uint64_t Mul128Hi(__uint128_t lowbits, uint64_t d) noexcept |
| 9 |
{ |
| 10 |
__uint128_t bottomHalf = (lowbits & UINT64_C(0xFFFFFFFFFFFFFFFF)) * d; // Won't overflow |
| 11 |
bottomHalf >>= 64; // Only need the top 64 bits, as we'll shift the lower half away; |
| 12 |
__uint128_t topHalf = (lowbits >> 64) * d; |
| 13 |
__uint128_t bothHalves = bottomHalf + topHalf; // Both halves are already shifted down by 64 |
| 14 |
return bothHalves >> 64; // Get top half of bothHalves |
| 15 |
} |
| 16 |
|
| 17 |
uint64_t FastDivide64(uint64_t a, __uint128_t multiplicativeInverse) noexcept |
| 18 |
{ |
| 19 |
return Mul128Hi(multiplicativeInverse, a); |
| 20 |
} |
| 21 |
|
| 22 |
uint64_t FastModulus64(uint64_t a, __uint128_t multiplicativeInverse, uint64_t d) noexcept |
| 23 |
{ |
| 24 |
return Mul128Hi(multiplicativeInverse * a, d); |
| 25 |
} |
| 26 |
|
| 27 |
uint64_t ComputeMultInverse32(uint32_t d) noexcept { return UINT64_C(0xFFFFFFFFFFFFFFFF) / d + 1; } |
| 28 |
|
| 29 |
uint64_t Mul64By32(uint64_t lowbits, uint32_t d) noexcept |
| 30 |
{ |
| 31 |
return (static_cast<__uint128_t>(lowbits) * d) >> 64; |
| 32 |
} |
| 33 |
|
| 34 |
uint32_t FastModulus32(uint32_t a, uint64_t multiplicativeInverse, uint32_t d) noexcept |
| 35 |
{ |
| 36 |
uint64_t lowbits = multiplicativeInverse * a; |
| 37 |
return Mul64By32(lowbits, d); |
| 38 |
} |
| 39 |
|
| 40 |
uint32_t FastDivide32(uint32_t a, uint64_t multiplicativeInverse) noexcept |
| 41 |
{ |
| 42 |
return Mul64By32(multiplicativeInverse, a); |
| 43 |
} |
| 44 |
|
| 45 |
} // namespace Utility |
| 46 |
} // namespace PacBio |