3 ms·
> Genuine question : do we know that those bugs would have been avoided using rust? Maybe some of those part would have had to be done unsafe mode for some reas
by scottlamb 10y ago
> Genuine question : do we know that those bugs would have been avoided using rust? Maybe some of those part would have had to be done unsafe mode for some reasons.
AFAIK no one's done a comprehensive survey, and it'd be hard to know for certain what someone would choose to use unsafe for until/unless they actually rewrite the code in question into Rust.
But if you look at code that is written in Rust today, I think you'll find less than 1% of the code is unsafe. [1] I think it's used for
* FFI / interfacing with C (common now, but less so the more you rewrite into Rust),
* low-level code (such as synchronization primitives and data structures), and
* a few bits of performance-sensitive code.
My gut feeling is that many of these bugs are in safe code, the "boring" 99%. The bugs would either be prevented by the compiler or turned into a panic at runtime instead of undefined behavior.
When people use unsafe, I'd like to think having to explicitly flag it as such would make authors and reviewers more careful. But certainly there's no 100% guarantee; I've seen broken unsafe Rust code in the wild already. As a small example, sqlite3::core::ResultRow::column_slice [2] is unsound; a following call to another column_* method would invalidate the returned pointer, [3] but as they all take a &self nothing prevents you from using the pointer after it's no longer valid. column_slice should take a &mut self instead. I haven't reported the bug because this buggy crate has been marked obsolete in favor of rusqlite.
[1] For a project of mine, it's found on 0.3% of non-comment-non-blank lines (23 unsafes / 7,390 lines). 13 of those were for FFI; the remaining 10 were due to my unfortunate obsession with optimizing for CPU. If anyone's done an accounting of more/larger projects, I'd be curious to hear it.
[2] http://www.madmode.com/rust-sqlite3/sqlite3/core/struct.ResultRow.html http://www.madmode.com/rust-sqlite3/sqlite3/core/struct.Resu...
[3] https://www.sqlite.org/capi3ref.html#sqlite3_column_blob https://www.sqlite.org/capi3ref.html#sqlite3_column_blob