←back to thread

Pitfalls of Safe Rust

(corrode.dev)
168 points pjmlp | 2 comments | | HN request time: 0.492s | 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 #
int_19h ◴[] No.43605473[source]
The vast majority of code that does arithmetic will not produce a correct result with two's complement. It is simply assuming that the values involved are small enough that it won't matter. Sometimes it is a correct assumption, but whenever it involves anything derived from inputs, it can go very wrong.
replies(2): >>43605520 #>>43607770 #
1. Spivak ◴[] No.43607770[source]
This is something that's always bugged me because, yes, this is a real problem that produces real bugs. But at the same time if you really care about this issue then every arithmetic operation is unsafe and there is never a time you should use them without overflow checks. Sometimes you can know something won't overflow but outside of some niche type systems you can't really prove it to the compiler to elide the check in a way that is safe against code modifications— i.e. if someone edits code that breaks the assumption we needed to know it won't overflow it will err.

But at the same time in real code in the real world you just do the maths, throw caution to the wind, and if it overflows and produces a bug you just fix it there. It's not worth the performance hit and your fellow developers will call you mad if you try to have a whole codebase with only checked maths.

replies(1): >>43613793 #
2. int_19h ◴[] No.43613793[source]
I think this is very much a cultural issue rather than a technical one. Just look at array bounds checking: widespread in the mainframe era even in systems languages, relegated to high-level languages for a very long time on the basis of unacceptable perf hit in low-level code, but more recently seeing more acceptance in new systems languages (e.g. Rust).

Similarly in this case, it's not like we don't have languages that do checked arithmetic throughout by default. VB.NET, for example, does exactly that. Higher-level languages have other strategies to deal with the problem; e.g. unbounded integer types as in Python, which simply never overflow. And, like you say, this sort of thing is considered unacceptable for low-level code on perf grounds, but, given the history with nulls and OOB checking, I think there is a lesson here.