Vec::as_non_null()
method
#440
Labels
ACP-accepted
API Change Proposal is accepted (seconded with no objections)
api-change-proposal
A proposal to add or alter unstable APIs in the standard libraries
T-libs-api
Proposal
This is a follow-up to a previous ACP, which proposes convenience conversions from/to
NonNull
. This proposal proposes an API addition that was not accepted in that previous ACP.Solution sketch
I would like to propose the following API addition:
Alternatives
&mut self
vs&self
Consider the existing
Vec::as_ptr()
method, which converts a&Vec<T>
into a*const T
. It currently is implemented with code identical toVec::as_mut_ptr()
. However,as_ptr
has documentation that prohibits using the returned pointer to mutate the buffer. Such a mutation wouldn't be language UB with the current implementation ofas_ptr
, but would be ruled as being library UB. That is, a&Vec<T>
should not be used to mutate the underlying buffer.In order to preserve this library UB, the proposed
as_non_null
method should take a&mut self
argument, not&self
.Other APIs (which are not proposed in this ACP)
The following two methods were also proposed in the previous ACP but were not accepted:
It turns out that methods that turn slices into raw pointers should probably not take a reference as the argument. The existing
[T]::as_mut_ptr()
method, which converts a reference into a raw pointer in this way, is a footgun, since it imposes extra aliasing constraints. In particular, callingas_mut_ptr()
a second time will invalidate the pointer returned from the first call. Therefore, a slice method that returns a raw pointer of some kind, should take a raw pointer of some kind as an argument.Given that
NonNull<[T]>::as_non_null_ptr()
(which converts fromNonNull<[T]>
toNonNull<T>
) already exists, there is no need to add anotheras_non_null
method on slices.As for
as_non_null_range
, it could potentially exist as a method that converts fromNonNull<[T]>
to aRange<NonNull<T>>
. However, this would require doing pointer arithmetic to get the pointer pointing to the end of the range, and it is unclear whether the unsafeptr::add
semantics or theptr::wrapping_add
semantics are desirable. Therefore, I am not proposing thisas_non_null_range
method on slices.Links and related work
T-opsem Zulip discussion
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:
The text was updated successfully, but these errors were encountered: