avoid extra check from compiler during math ops

Signed-off-by: Uncle Fatso <uncle.fatso@ghostchain.io>
This commit is contained in:
Uncle Fatso 2026-03-26 14:08:05 +03:00
parent 5e09c9d417
commit 9a6bc55e62
Signed by: f4ts0
GPG Key ID: 565F4F2860226EBB

View File

@ -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;
@ -46,4 +53,5 @@ library FullMath {
require(h < d, "FullMath: FULLDIV_OVERFLOW");
return fullDiv(l, h, d);
}
}
}