Skip to content

opt: branchless MathUtils.add(uint,int) #641

@DhairyaSethi

Description

@DhairyaSethi

/**
* @notice Adds a signed integer to an unsigned integer.
* @dev Reverts on underflow.
* @param a The unsigned integer.
* @param b The signed integer.
* @return The result of the addition.
*/
function add(uint256 a, int256 b) internal pure returns (uint256) {
if (b >= 0) return a + uint256(b);
return a - uint256(-b);
}

This can be optimised to be written branchless-ly. See min implementation above or oz for inspiration.

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions