Open RalfJung opened 4 months ago
It is worth noting that this is entirely independent of https://github.com/rust-lang/unsafe-code-guidelines/issues/326. It's about avoiding intermediate references on the way from Box
to the raw pointer; references unambiguously have noalias
so their presence can make a difference.
I think we should do this regardless of it can can be done with casts, like how we have https://doc.rust-lang.org/std/ptr/fn.from_ref.html.
Proposal
Problem statement
When working with raw pointers, it can be necessary to obtain raw pointers to the contents of a container in a way that multiple such pointers can alias with each other arbitrarily. For
Vec
, we haveVec::as_mut_ptr
for that purpose, and that aliasing model interaction is even documented nowadays. However, forBox
, we have no such method. One has to instead writeaddr_of_mut!(*bx)
, which works because Box is a primitive and this does not go throughDerefMut
. (DerefMut
would be creating a reference and thus defeat the aliasing point of this.)Motivating examples or use cases
Here's an example of code that's wrong:
This came about in rustc itself due to a refactor that replaced
Vec
byBox
.Solution sketch
I'm not sure how to avoid the refactoring issue, since
Box
can't really haveself
methods, soas_mut_ptr
on aBox<[T]>
will always call the slice method and thus create an intermediate reference. But we could at least provide methods that do the right thing and are more discoverable than theaddr_of_mut!
trick:This would also complement the existing
into_raw
.Alternatives
We could do nothing and instead just document the
addr_of_mut!
pattern somewhere in theBox
type docs.Links and related work
Vec
hasas_ptr
/as_mut_ptr
with aliasing model guarantees.What happens now?
This issue contains an API change proposal (or ACP) and is part of the libs-api team feature lifecycle. Once this issue is filed, the libs-api team will review open proposals as capability becomes available. Current response times do not have a clear estimate, but may be up to several months.
Possible responses
The libs team may respond in various different ways. First, the team will consider the problem (this doesn't require any concrete solution or alternatives to have been proposed):
Second, if there's a concrete solution: