←back to thread

611 points LorenDB | 1 comments | | HN request time: 0.001s | 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 #
ultimaweapon ◴[] No.43912986[source]
Rust is the only language I can easily control how integer overflow should behave. I can use `var1.wrapping_add(var2)` if I want the result to be wrapped or `var1.checked_add(var2)` if I don't want it to overflow.
replies(1): >>43913695 #
codedokode ◴[] No.43913695[source]
The functions are so verbose and inconvenient that even Rust developers themselves do not use them. For example, in this code [1] they used a wrapping addition instead of "checked_add" because it is faster to write.

For comparison, Swift uses "+" for checked addition and as a result, majority of developers use checked addition by default. And in Rust due to its poor design choices most developers use wrapping addition even where a checked addition should be used.

[1] https://doc.rust-lang.org/src/alloc/vec/mod.rs.html#2010

replies(2): >>43913890 #>>43917535 #
1. genrilz ◴[] No.43917535{3}[source]
The reason '+ 1' is fine in the example you gave is that length is always less than or equal to capacity. If you follow 'grow_one' which was earlier in the function to grow the capacity by one if needed, you will find that it leads to the checked addition in [0], which returns an error that [1] catches and turns into a panic. So using '+1' prevents a redundant check in release mode while still adding the check in debug mode in case future code changes break the 'len <= capacity' invariant.

Of course, if you don't trust the standard library, you can turn on overflow checks in release mode too. However, the standard library is well tested and I think most people would appreciate the speed from eliding redundant checks.

  [0]: https://doc.rust-lang.org/src/alloc/raw_vec.rs.html#651
  [1]: https://doc.rust-lang.org/src/alloc/raw_vec.rs.html#567