Skip to content
Merged
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Prev Previous commit
Next Next commit
branchless rounding
  • Loading branch information
Amxx committed Feb 6, 2024
commit 45bbe87e054fec4348143775c18a2552c4baef8d
14 changes: 5 additions & 9 deletions contracts/utils/math/Math.sol
Original file line number Diff line number Diff line change
Expand Up @@ -210,11 +210,7 @@ library Math {
* @dev Calculates x * y / denominator with full precision, following the selected rounding direction.
*/
function mulDiv(uint256 x, uint256 y, uint256 denominator, Rounding rounding) internal pure returns (uint256) {
uint256 result = mulDiv(x, y, denominator);
if (unsignedRoundsUp(rounding) && mulmod(x, y, denominator) > 0) {
result += 1;
}
return result;
return mulDiv(x, y, denominator) + boolToUint(unsignedRoundsUp(rounding) && mulmod(x, y, denominator) > 0);
}

/**
Expand Down Expand Up @@ -383,7 +379,7 @@ library Math {
function sqrt(uint256 a, Rounding rounding) internal pure returns (uint256) {
unchecked {
uint256 result = sqrt(a);
return result + (unsignedRoundsUp(rounding) && result * result < a ? 1 : 0);
return result + boolToUint(unsignedRoundsUp(rounding) && result * result < a);
}
}

Expand Down Expand Up @@ -436,7 +432,7 @@ library Math {
function log2(uint256 value, Rounding rounding) internal pure returns (uint256) {
unchecked {
uint256 result = log2(value);
return result + (unsignedRoundsUp(rounding) && 1 << result < value ? 1 : 0);
return result + boolToUint(unsignedRoundsUp(rounding) && 1 << result < value);
}
}

Expand Down Expand Up @@ -485,7 +481,7 @@ library Math {
function log10(uint256 value, Rounding rounding) internal pure returns (uint256) {
unchecked {
uint256 result = log10(value);
return result + (unsignedRoundsUp(rounding) && 10 ** result < value ? 1 : 0);
return result + boolToUint(unsignedRoundsUp(rounding) && 10 ** result < value);
}
}

Expand Down Expand Up @@ -528,7 +524,7 @@ library Math {
function log256(uint256 value, Rounding rounding) internal pure returns (uint256) {
unchecked {
uint256 result = log256(value);
return result + (unsignedRoundsUp(rounding) && 1 << (result << 3) < value ? 1 : 0);
return result + boolToUint(unsignedRoundsUp(rounding) && 1 << (result << 3) < value);
}
}

Expand Down