←back to thread

Pitfalls of Safe Rust

(corrode.dev)
168 points pjmlp | 1 comments | | HN request time: 0.226s | source
Show context
forrestthewoods ◴[] No.43604132[source]
> Overflow errors can happen pretty easily

No they can’t. Overflows aren’t a real problem. Do not add checked_mul to all your maths.

Thankfully Rust changed overflow behavior from “undefined” to “well defined twos-complement”.

replies(4): >>43604262 #>>43605035 #>>43605473 #>>43605491 #
wongarsu ◴[] No.43605491[source]
I'm a big fan of liberal use of saturating_mul/add/sub whenever there is a conceivable risk of coming withing a couple orders of magnitude of overflow. Or checked_*() or whatever the best behavior in the given case is. For my code it happens to mostly be saturating.

Overflow bugs are a real pain, and so easy to prevent in Rust with just a function call. It's pretty high on my list of favorite improvements over C/C++

replies(1): >>43606416 #
forrestthewoods ◴[] No.43606416[source]
If you saturate you almost never ever want to use the result. You need to check and if it saturates do something else.
replies(2): >>43609149 #>>43613178 #
1. sfink ◴[] No.43613178[source]
If you're going to check then you shouldn't be saturating, you should just be checking.