Skip to content

Commit

Permalink
✨ Add toUint256 (#512)
Browse files Browse the repository at this point in the history
  • Loading branch information
Vectorized authored Jul 24, 2023
1 parent dac54a8 commit 30558f5
Show file tree
Hide file tree
Showing 3 changed files with 18 additions and 3 deletions.
5 changes: 3 additions & 2 deletions .gas-snapshot
Original file line number Diff line number Diff line change
Expand Up @@ -748,9 +748,10 @@ SafeCastLibTest:testSafeCastToInt(int256) (runs: 256, μ: 4384, ~: 3415)
SafeCastLibTest:testSafeCastToInt256(uint256) (runs: 256, μ: 931, ~: 390)
SafeCastLibTest:testSafeCastToIntBench() (gas: 383456)
SafeCastLibTest:testSafeCastToUint() (gas: 10560)
SafeCastLibTest:testSafeCastToUint(uint256) (runs: 256, μ: 4118, ~: 3351)
SafeCastLibTest:testSafeCastToUint(uint256) (runs: 256, μ: 4198, ~: 3351)
SafeCastLibTest:testSafeCastToUint256(int256) (runs: 256, μ: 1285, ~: 432)
SafeCastLibTest:testSafeCastToUintBench() (gas: 326306)
SafeCastLibTest:test__codesize() (gas: 15816)
SafeCastLibTest:test__codesize() (gas: 16001)
SafeTransferLibTest:testApproveWithGarbageReverts(address,uint256) (runs: 256, μ: 108262, ~: 123396)
SafeTransferLibTest:testApproveWithMissingReturn() (gas: 31988)
SafeTransferLibTest:testApproveWithMissingReturn(address,uint256) (runs: 256, μ: 31292, ~: 32148)
Expand Down
7 changes: 6 additions & 1 deletion src/utils/SafeCastLib.sol
Original file line number Diff line number Diff line change
Expand Up @@ -361,14 +361,19 @@ library SafeCastLib {
}

/*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
/* UNSIGNED TO SIGNED SAFE CASTING OPERATIONS */
/* OTHER SAFE CASTING OPERATIONS */
/*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/

function toInt256(uint256 x) internal pure returns (int256) {
if (x >= 1 << 255) _revertOverflow();
return int256(x);
}

function toUint256(int256 x) internal pure returns (uint256) {
if (x < 0) _revertOverflow();
return uint256(x);
}

/*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
/* PRIVATE HELPERS */
/*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/
Expand Down
9 changes: 9 additions & 0 deletions test/SafeCastLib.t.sol
Original file line number Diff line number Diff line change
Expand Up @@ -256,6 +256,15 @@ contract SafeCastLibTest is SoladyTest {
}
}

function testSafeCastToUint256(int256 x) public {
if (x < 0) {
vm.expectRevert(SafeCastLib.Overflow.selector);
SafeCastLib.toUint256(x);
} else {
assertEq(SafeCastLib.toUint256(x), uint256(x));
}
}

function testSafeCastToIntBench() public {
unchecked {
int256 sum;
Expand Down

0 comments on commit 30558f5

Please sign in to comment.