Re: The Case for Rust (in any system)

From: David Chisnall <theraven_at_freebsd.org>
Date: Fri, 06 Sep 2024 07:13:34 UTC
On 5 Sep 2024, at 20:50, Alan Somers <asomers@freebsd.org> wrote:
> 
> I think you are misinformed about the runtime costs involved.  In
> fact, Rust's overhead is quite low.

It’s very hard to get good apples to apples comparisons here but the main thing to remember is that C and Rust compile down to the same instruction sets. For spatial safety, you have basically two cases:

 - Things where the size is statically known and so all accesses are in bounds if their offsets are known.
 - Things where the size needs to be carried around with the object.

There is nothing magic in C here. You either have fixed-sized things and a compiler will be able to statically bounds check (though will typically only warn for invalid ones) or you carry the length around and check it. The difference is that Rust or C++ can express both of these in the type system and so will always insert bounds checks for any access where they cannot be proven to be redundant.

The cases where you will see a difference are the ones where the safety depends on some extrinsic property that the programmer knows but which cannot be expressed in the type system. In C, you will do an unchecked access. In Rust, you *can* do unsafe things with raw pointers, but usually you won’t, and so you’ll get bounds checks that are redundant. Assuming, of course, that the assumption that the programmer made is correct and remains correct as the code is refactored. Which it often isn’t, and then you get security vulnerabilities.

David