diff options
Diffstat (limited to 'src/common/uint128.h')
| -rw-r--r-- | src/common/uint128.h | 20 |
1 files changed, 20 insertions, 0 deletions
diff --git a/src/common/uint128.h b/src/common/uint128.h index 83560a9ce..4780b2f9d 100644 --- a/src/common/uint128.h +++ b/src/common/uint128.h | |||
| @@ -98,4 +98,24 @@ namespace Common { | |||
| 98 | #endif | 98 | #endif |
| 99 | } | 99 | } |
| 100 | 100 | ||
| 101 | // This function divides a u128 by a u32 value and produces two u64 values: | ||
| 102 | // the result of division and the remainder | ||
| 103 | [[nodiscard]] static inline std::pair<u64, u64> Divide128On32(u128 dividend, u32 divisor) { | ||
| 104 | u64 remainder = dividend[0] % divisor; | ||
| 105 | u64 accum = dividend[0] / divisor; | ||
| 106 | if (dividend[1] == 0) | ||
| 107 | return {accum, remainder}; | ||
| 108 | // We ignore dividend[1] / divisor as that overflows | ||
| 109 | const u64 first_segment = (dividend[1] % divisor) << 32; | ||
| 110 | accum += (first_segment / divisor) << 32; | ||
| 111 | const u64 second_segment = (first_segment % divisor) << 32; | ||
| 112 | accum += (second_segment / divisor); | ||
| 113 | remainder += second_segment % divisor; | ||
| 114 | if (remainder >= divisor) { | ||
| 115 | accum++; | ||
| 116 | remainder -= divisor; | ||
| 117 | } | ||
| 118 | return {accum, remainder}; | ||
| 119 | } | ||
| 120 | |||
| 101 | } // namespace Common | 121 | } // namespace Common |