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

Add SafeCast variants for signed integers #2240

Closed
nventuro opened this issue May 20, 2020 · 4 comments · Fixed by #2243
Closed

Add SafeCast variants for signed integers #2240

nventuro opened this issue May 20, 2020 · 4 comments · Fixed by #2243
Labels
good first issue Low hanging fruit for new contributors to get involved!

Comments

@nventuro
Copy link
Contributor

SafeCast currently has support for downcasting uints and casting them to int256, but there's no safe way to downcast signed integers.

This is slightly trickier because the two's complement integer representation has different ranges for positive and negative numbers, but should be easy to do anyway.

@nventuro nventuro added the good first issue Low hanging fruit for new contributors to get involved! label May 20, 2020
@frangio
Copy link
Contributor

frangio commented May 20, 2020

You're talking about a function functions like toInt128(int256 x) right?

@nventuro
Copy link
Contributor Author

Precisely, yes. toInt8(int256 x) for example needs to check that -128 <= x <= 127.

@julianmrodri
Copy link
Contributor

@nventuro @frangio I can tackle this if you are OK. Just let me know.

@julianmrodri
Copy link
Contributor

julianmrodri commented May 23, 2020

@nventuro @frangio I gave it a shot. Submitted PR #2243 Here is how one of the functions look for the example you mentioned above. Any chances or adjustments that need to be made please let me know. Thanks!

/**
 * @dev Returns the downcasted int8 from int256, reverting on
 * overflow (when the input is less than smallest int8 or greater 
 * than largest int8).
 *
 * Counterpart to Solidity's `int8` operator.
 *
 * Requirements:
 *
 * - input must fit into 8 bits.
 */ 
function toInt8(int256 value) internal pure returns (int8) {
    require(value >= -2**7 && value < 2**7, "SafeCast: value doesn\'t fit in 8 bits");
    return int8(value);         
 }

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
good first issue Low hanging fruit for new contributors to get involved!
Projects
None yet
Development

Successfully merging a pull request may close this issue.

3 participants