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

[RFC] Wrapped negation of unsigned integers #9914

Closed
HertzDevil opened this issue Nov 13, 2020 · 0 comments · Fixed by #9947
Closed

[RFC] Wrapped negation of unsigned integers #9914

HertzDevil opened this issue Nov 13, 2020 · 0 comments · Fixed by #9947

Comments

@HertzDevil
Copy link
Contributor

Regular negation of unsigned integers always leads to an underflow for anything other than 0, but wrapped negation is still useful when dealing with binary data or low-level code. Crystal however doesn't support them:

x = 1
-x # => -1

x = 1_u32
-x # Error: wrong number of arguments for 'UInt32#-' (given 0, expected 1)
&-x # Error: wrong number of arguments for 'UInt32#&-' (given 0, expected 1)

This means one is left with these less clear alternatives:

~x &+ 1 # => 4294967295
x.class.zero &- x # => 4294967295

Thus I propose that the unsigned integer types (UInt8, UInt16, UInt32, UInt64, UInt128) define the argument-less #&- method, which performs wrapped negation. There are some possible extensions:

  • Signed integer types could define #&- too, but the only affected value is the minimum representable integer of each respective type (in contrast to a hypothetical #- working on exactly one value from each unsigned type), so that's not as useful.
  • The argument-less #&+ is exactly the same as #+ for integers, so that's probably useless as well.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

Successfully merging a pull request may close this issue.

2 participants