Description
On unstable Rust, we can finally have a sound unrestricted offset_of!
macro (as already implemented in the memoffset crate). But one interesting open question remains: what about a macro like what @Amanieu called container_of!
in Gilnaa/memoffset#21? That macro compute a pointer to the "outer object" given a pointer to some field.
The problem with that macro is that it is very hard to use with aliasing rules as strict as Stacked Borrows, but I also see no good way to adjust Stacked Borrows to support this without losing many optimizations. Basically, the restriction is that only raw pointers may be used when computing the field pointer from the "outer object pointer". Any intermediate reference asserts that this and all derived pointers may only be used for the memory range covered by this reference, making container_of!
incorrect.
I don't see a fundamental reason why a Rust aliasing model has to constrain pointers like that. However, I do think it is crucial that we may not just use a reference to one field for a sibling field if a reference to the sibling field exists. That would be illegal aliasing with that sibling reference. So we might be able to relax Stacked Borrows a bit, but not a lot.
I am not sure if a container_of!
macro is still useful with all these restrictions, it certainly is non-trivial to use.