-
-
Notifications
You must be signed in to change notification settings - Fork 1.6k
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
Refactor: String#to_i to avoid future overflow #7172
Conversation
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Can a spec be added for this?
78301e0
to
06f344b
Compare
@asterite done |
@@ -497,7 +497,7 @@ class String | |||
if info.negative | |||
{% if max_negative %} | |||
return yield if info.value > {{max_negative}} | |||
-info.value.to_{{method}} | |||
(~info.value &+ 1).unsafe_as(Int64).to_{{method}} |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
What does ~
mean? 🤔
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
@vladfaust it's inverting bits to perform https://en.wikipedia.org/wiki/Two%27s_complement
Sample:
00000011 ( 3. info.value)
11111100 (-4. ~info.value)
11111101 (-3. ~info.value &+ 1)
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
This method could use some API docs.
This is a small refactor on
String#to_i
methods.Before this PR when parsing the minimum negative value (eg:
-128
forInt8
) the code will first convert theUInt64
absolute value to aInt8
and then return it with opposite sign.The positive
128
is not a validInt8
so we should change the conversion to use 2's complement.First compute the binary
Int64
representation of negative number to return, cast it asInt64
and then narrow its type to the expected one.