Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Unsigned conversion #2111 #2123

Merged
merged 14 commits into from
Mar 27, 2020
Merged
5 changes: 5 additions & 0 deletions contracts/mocks/SafeCastMock.sol
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,11 @@ import "../utils/SafeCast.sol";

contract SafeCastMock {
using SafeCast for uint;
using SafeCast for int;

function toUint256(int a) public pure returns (uint256) {
return a.toUint256();
}

function toUint128(uint a) public pure returns (uint128) {
return a.toUint128();
Expand Down
12 changes: 12 additions & 0 deletions contracts/utils/SafeCast.sol
Original file line number Diff line number Diff line change
Expand Up @@ -94,4 +94,16 @@ library SafeCast {
require(value < 2**8, "SafeCast: value doesn\'t fit in 8 bits");
return uint8(value);
}

/**
* @dev Converts an unsigned uint256 into a signed int256.
*
* Requirements:
*
* - input must be greater than or equal to 0.
*/
function toUint256(int256 value) internal pure returns (uint256) {
require(value >= 0, "SafeCast: value must be positive");
return uint256(value);
}
}
39 changes: 39 additions & 0 deletions test/utils/SafeCast.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -42,5 +42,44 @@ describe('SafeCast', async () => {
});
}

describe('toUint256', () => {
const maxInt256 = new BN('1').shln(255).notn(256);
const minInt256 = new BN('1').shln(255);
const maxUint256 = new BN('0').notn(256);

it('downcasts 0', async function () {
pepelu marked this conversation as resolved.
Show resolved Hide resolved
expect(await this.safeCast.toUint256(0)).to.be.bignumber.equal('0');
});

it('downcasts 1', async function () {
expect(await this.safeCast.toUint256(1)).to.be.bignumber.equal('1');
});

it(`downcasts INT256_MAX ${maxInt256}`, async function () {
expect(await this.safeCast.toUint256(maxInt256)).to.be.bignumber.equal(maxInt256);
nventuro marked this conversation as resolved.
Show resolved Hide resolved
});

it('reverts when downcasting -1', async function () {
await expectRevert(
this.safeCast.toUint256(-1),
'SafeCast: value must be positive'
);
});

it(`reverts when downcasting INT256_MIN ${minInt256}`, async function () {
await expectRevert(
this.safeCast.toUint256(minInt256),
'SafeCast: value must be positive'
);
});

it(`reverts when downcasting UINT256_MAX ${maxUint256}`, async function () {
await expectRevert(
this.safeCast.toUint256(maxUint256),
'SafeCast: value must be positive'
);
});
});

[8, 16, 32, 64, 128].forEach(bits => testToUint(bits));
pepelu marked this conversation as resolved.
Show resolved Hide resolved
});