avoid extra check from compiler during math ops
Signed-off-by: Uncle Fatso <uncle.fatso@ghostchain.io>
This commit is contained in:
parent
5e09c9d417
commit
9a6bc55e62
@ -3,17 +3,20 @@ pragma solidity ^0.8.20;
|
||||
|
||||
library FullMath {
|
||||
function fullMul(uint256 x, uint256 y) private pure returns (uint256 l, uint256 h) {
|
||||
unchecked {
|
||||
uint256 mm = mulmod(x, y, type(uint256).max);
|
||||
l = x * y;
|
||||
h = mm - l;
|
||||
if (mm < l) h -= 1;
|
||||
}
|
||||
}
|
||||
|
||||
function fullDiv(
|
||||
uint256 l,
|
||||
uint256 h,
|
||||
uint256 d
|
||||
) private pure returns (uint256) {
|
||||
unchecked {
|
||||
uint256 pow2 = d & (~d + 1);
|
||||
d /= pow2;
|
||||
l /= pow2;
|
||||
@ -29,15 +32,19 @@ library FullMath {
|
||||
r *= 2 - d * r;
|
||||
return l * r;
|
||||
}
|
||||
}
|
||||
|
||||
function mulDiv(
|
||||
uint256 x,
|
||||
uint256 y,
|
||||
uint256 d
|
||||
) internal pure returns (uint256) {
|
||||
(uint256 l, uint256 h) = fullMul(x, y);
|
||||
if (d == 0) revert("FullMath: DIVISION_BY_ZERO");
|
||||
|
||||
unchecked {
|
||||
(uint256 l, uint256 h) = fullMul(x, y);
|
||||
uint256 mm = mulmod(x, y, d);
|
||||
|
||||
if (mm > l) h -= 1;
|
||||
l -= mm;
|
||||
|
||||
@ -47,3 +54,4 @@ library FullMath {
|
||||
return fullDiv(l, h, d);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
Loading…
Reference in New Issue
Block a user