Pre-RFC: Unsafe Types

I didn’t know this has come up before, thanks for the pointer!

I think I agree unsafe fields would be more natural; I arrived at the same conclusion over night. If you look at a type like RcBox:

struct RcBox<T: ?Sized> {
    strong: Cell<usize>,
    weak: Cell<usize>,
    value: T,
}

then even though all fields are private, only strong and weak have extra invariants on them. However, this example also shows a limitation of the suggested approach: Modifying the contents of the cells will not require an unsafe block, even though it could violate invariants. It’s not clear to me how to best fix that.

So I guess the question of whether we want something like this boils down to:

Do we want to (artificially?) extend the amount of operations considered unsafe such that more code that could cause memory unsafety, has to be in unsafe blocks?

The caveat is that we will never be able to make sure that all such code is in unsafe blocks.

Also, on another note, I forgot to stress that I think this does not violate the rule that unsafe should only cover operations that can actually lead to violations of Rust’s safety promises (the rule that was coined when forget was deemed safe). If the programmer annotation on the field is correct, i.e. if there really are additional invariants on the given fields that unsafe code relies on, then writing bad values to such fields really can cause safety violations.

4 Likes