←back to thread

611 points LorenDB | 5 comments | | HN request time: 0s | source
Show context
codedokode ◴[] No.43908897[source]
What about catching integer overflow? Free open-source languages still cannot do it unlike they commercial competitors like Swift?
replies(5): >>43908922 #>>43909326 #>>43909444 #>>43910683 #>>43912986 #
lytedev ◴[] No.43908922[source]
I'm not sure if this is what you mean, exactly, but Rust indeed catches this at compile time.

https://play.rust-lang.org/?version=stable&mode=debug&editio... https://play.rust-lang.org/?version=stable&mode=debug&editio...

replies(1): >>43909313 #
codedokode ◴[] No.43909313[source]
I meant panic if during any addition (including in runtime) an overflow occurs.
replies(3): >>43909686 #>>43909733 #>>43913823 #
1. trealira ◴[] No.43909686{3}[source]
You can set a flag for that: https://doc.rust-lang.org/rustc/codegen-options/index.html#o...

By default, they're on during debug mode and off in release mode.

replies(1): >>43913716 #
2. codedokode ◴[] No.43913716[source]
The choice doesn't make sense because you want the program to always behave correctly and not only during development.
replies(1): >>43916558 #
3. lytedev ◴[] No.43916558[source]
Eh, maybe. There's a performance tradeoff here and maintainers opted for performance. I'm sure many folks would agree with you that it was the wrong choice, and I'm sure many folks would disagree with you that it was the wrong choice.

There are also specific methods for doing *erflow-checked arithmetic if you like.

replies(1): >>43918689 #
4. codedokode ◴[] No.43918689{3}[source]
Why should there be a performance tradeoff? Because Intel CPU doesn't have add-with-overflow-check instruction, we make our languages less safe?
replies(1): >>43920644 #
5. genrilz ◴[] No.43920644{4}[source]
Actually, the x86 'ADD' instruction automagically sets the 'OF' and 'CF' flags for you for signed and unsigned overflow respectively [0]. So all you need to do to panic would be to follow that with an 'JO' or 'JB' instruction to the panic handling code. This is about as efficient as you could ask for, but a large sequence of arithmetic operations is still going to gum up the branch predictor, resulting in more pipeline stalls.

[0]: https://www.felixcloutier.com/x86/add