4 ms·
Is the amount of code in unsafe blocks really a good metric for safety?
by k__ 7y ago
Is the amount of code in unsafe blocks really a good metric for safety?
- gpm 7y agoLike many metrics, if your not measuring it, yes. It's easy to game, but with reasonably written code the number of lines in unsafe blocks should correlate fairly strongly with the number of times you did something scary. (Scary here includes things as basic as calling a c function or system call directly)
- kibwen 7y agoNot within the unsafe blocks itself, no. A more pertinent metric might be "number of lines of code in any modules that contain the `unsafe` keyword". It's true that certain operations can only happen within the unsafe block itself, but those operations can potentially invalidate safety-critical invariants being upheld by any code that the unsafe block can reach, which means the buck ultimately stops at the module boundary. If you have a module that contains unsafe code, factor out the bits that need `unsafe` into as small a submodule as possible with a well-considered interface so that you have as little code to audit as necessary. The fortunate thing is that, in practice, you can program in Rust for years without ever needing to write an `unsafe` keyword, depending on your chosen domain. `unsafe` is mostly useful for calling external C code, for implementing maximally-efficient custom data structures, and interfacing with hardware.