4 ms·
unsafe isn't like a taint, where things that use unsafe code must propagate their unsafety outward. It's more like saying "there are invariants that this functi
by habitue 6y ago
unsafe isn't like a taint, where things that use unsafe code must propagate their unsafety outward. It's more like saying "there are invariants that this function expects, but does not enforce, and the caller may violate those invariants". Obviously, we want to minimize code like that. The best way to do that is to build abstractions around the unsafe code that only interact with the unsafe code in a way that respects those invariants. Often, (though not always) that means giving up some amount of flexibility to the user of your safe abstraction. If you design it right, the caller may never miss that flexibility.
A recent example of using private constructors and zero-sized compile time invariant enforcement is an embedded blog here: https://www.ecorax.net/macro-bunker-1/ https://www.ecorax.net/macro-bunker-1/
The embedded rust community uses this typestate pattern to build safe abstractions around pin interactions. Very similar things can be done to build safe abstractions around the volatile memory accesses etc that the kernel does.
- bestouff 6y agoI see "unsafe" more like "this is code that the compiler can't prove it holds its invariants, but in fact it does and I hope the programmer added a comment to explain why".