3 ms·
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 check
by wongarsu 2y ago
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++
- forrestthewoods 2y agoIf you saturate you almost never ever want to use the result. You need to check and if it saturates do something else.
- wongarsu 2y agoYou obviously have to decide it on a case-by-case basis. But anything that is only used in a comparison is usually fine with saturating. And many things that measures values or work with measurements are fine with saturating if it's documented. Saturating is how most analog equipment works too, and in non-interactive use cases "just pick the closest value we can represent" is often better than erroring out or recording nothing at all. Of course don't use saturating_add to calculate account balance, there you should use checked_add.
- sfink 2y agoIf you're going to check then you shouldn't be saturating, you should just be checking.