←back to thread

Pitfalls of Safe Rust

(corrode.dev)
168 points pjmlp | 1 comments | | HN request time: 0.203s | 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. wongarsu ◴[] No.43609149[source]
You 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.