Unsigned conversion #2111 (#2123)

* Add signed to unsigned conversion to SafeCast

* Update SafeCast exception message

* Add test for SafeCast int to uint conversion

- Update SafeCastMock
- Add tests for SafeCast int256 to uint256

* Update SafeCast int to uint definition

Apply suggestions from code review.

Co-Authored-By: Nicolás Venturo <nicolas.venturo@gmail.com>

* Update test for SafeCast int to uint conversion

* Update SafeCast test after code review

- Change "downcasts" to "casts"
- Move test closer to its function

* Fix error in SafeCast toUint256 description

* Fix breaking error in SafeCast

* Add uint256 to int256 conversion to SafeCast

- Add function
- Add mock
- Add test

* Update SafeCast unsigned to signed conversion

- Update error in conversion to be more clear
- Update constants in test to be powers of 2 instead of shifts

* Add changelog entry

* Update SafeCast tests

- Add minus in INT256_MIN for clarity

Co-Authored-By: Nicolás Venturo <nicolas.venturo@gmail.com>

Co-authored-by: Nicolás Venturo <nicolas.venturo@gmail.com>
This commit is contained in:
pepelu
2020-03-27 14:56:30 +01:00
committed by GitHub
parent 7554ea84a3
commit 4476a2d531
4 changed files with 104 additions and 0 deletions

View File

@ -4,6 +4,15 @@ 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 toInt256(uint a) public pure returns (int256) {
return a.toInt256();
}
function toUint128(uint a) public pure returns (uint128) {
return a.toUint128();

View File

@ -92,4 +92,28 @@ library SafeCast {
require(value < 2**8, "SafeCast: value doesn\'t fit in 8 bits");
return uint8(value);
}
/**
* @dev Converts a signed int256 into an unsigned uint256.
*
* 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);
}
/**
* @dev Converts an unsigned uint256 into a signed int256.
*
* Requirements:
*
* - input must be less than or equal to maxInt256.
*/
function toInt256(uint256 value) internal pure returns (int256) {
require(value < 2**255, "SafeCast: value doesn't fit in an int256");
return int256(value);
}
}