3 ms·
> Even if one in ten lines are marked as "unsafe", that's already many times less "unsafe" than what they are used to in their C or C++ code. As a Rust program
by nyanpasu64 6y ago
> Even if one in ten lines are marked as "unsafe", that's already many times less "unsafe" than what they are used to in their C or C++ code.
As a Rust programmer who's written safe code and some unsafe abstractions, one in ten lines being unsafe means that the remaining 90% of your lines need to be written with the same care as your unsafe code, to avoid feeding invalid arguments into unsafe operations which cause UB. The general approach is to not scatter unsafe code around your entire program, but segregate it into safe abstractions that prevent callers from triggering UB. (Though some APIs make it difficult to achieve, so the alternative is to create unsafe abstractions that expect callers to take care to avoid triggering UB, which requires auditing the callers for security as well.)
- rectang 6y agoI'm baffled by why this answer is downvoted. It matches my experience precisely, and articulates the proper approach for isolating `unsafe` code so that the safe code around isn't so tricky to write.
- nyanpasu64 6y agoMy guess is that fewer people are proficient in writing Rust than know about it being memory-safe, and only a fraction of Rust programmers have studied how to write unsafe code, its (footgun-filled) potential for undefined behavior, and the task of writing safe interfaces that don't allow for UB... yet the rest of them vote on HN anyway, thinking that "safe code can't cause UB" (which is an incomplete mental model). On a related note, looking at the comments of a semi-"fluff" blog post commenting on an unsafe-Rust data race (https://news.ycombinator.com/item?id=26713037 https://news.ycombinator.com/item?id=26713037), I'm the first person across all of the Mozilla bug-tracker, Mozilla blog, and HN comments to point out that Firefox had "data races in safe code" because an unsafe block in a (module-private) "safe" function was unsound, allowing other safe code in the module to cause data races. (Maybe not the first, https://news.ycombinator.com/item?id=26714209 https://news.ycombinator.com/item?id=26714209 pointed out the 'bad pattern of "sprinkle atomics it until it works"' (though not researching it as deeply as I did) and got downvoted even though they were right in this instance.)
- conradludgate 6y agoI'd argue that if your unsafe usage is making your 'safe' code unsafe, then you're using unsafe wrong. The idea is that once you leave the unsafe boundary, you have guaranteed to yourself that the assumptions required by the unsafe code have been met. Maybe there needs to be a syntax to say "yes I'm really sure that out here the assumptions have been checked so this is actually safe now" just to remind developers that this is what the unsafe block is for