Skip to content
Merged
Show file tree
Hide file tree
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
13 changes: 13 additions & 0 deletions src/libs/UIntMath.sol
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,9 @@ library UIntMath {
/// @notice Emitted when a passed value is greater than the maximum value of uint16.
error InvalidUInt16();

/// @notice Emitted when a passed value is greater than the maximum value of uint32.
error InvalidUInt32();

/// @notice Emitted when a passed value is greater than the maximum value of uint40.
error InvalidUInt40();

Expand Down Expand Up @@ -39,6 +42,16 @@ library UIntMath {
return uint16(n);
}

/**
* @notice Casts a uint256 value to a uint32, ensuring that it is less than or equal to the maximum uint32 value.
* @param n The value to cast.
* @return The value casted to uint32.
*/
function safe32(uint256 n) internal pure returns (uint32) {
if (n > type(uint32).max) revert InvalidUInt32();
return uint32(n);
}

/**
* @notice Casts a uint256 value to a uint40, ensuring that it is less than or equal to the maximum uint40 value.
* @param n The value to cast.
Expand Down
7 changes: 7 additions & 0 deletions test/UIntMath.t.sol
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,13 @@ contract UIntMathTests is Test {
_uintMath.safe16(uint256(type(uint16).max) + 1);
}

function test_safe32() external {
assertEq(_uintMath.safe32(uint256(type(uint32).max)), type(uint32).max);

vm.expectRevert(UIntMath.InvalidUInt32.selector);
_uintMath.safe32(uint256(type(uint32).max) + 1);
}

function test_safe40() external {
assertEq(_uintMath.safe40(uint256(type(uint40).max)), type(uint40).max);

Expand Down
4 changes: 4 additions & 0 deletions test/utils/UIntMathHarness.sol
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,10 @@ contract UIntMathHarness {
return UIntMath.safe16(n);
}

function safe32(uint256 n) external pure returns (uint32) {
return UIntMath.safe32(n);
}

function safe40(uint256 n) external pure returns (uint40) {
return UIntMath.safe40(n);
}
Expand Down