Description
Proposal
Add as_(mut_)ptr
methods to raw array pointers (*(const/mut) [T; N]
) as in the slice_ptr_get
feature to allow for type-safe casting of *[T; N]
to *T
, and as_(mut_)slice
as a safe way to convert a *[T; N]
into a *[T]
.
Problem statement
The ergonomics for raw array pointers are lacking behind from those for raw slices.
I also think that get_unchecked(_mut)
should at some point be available for array pointers, but IMHO there are const-generic-related implications to trying to stabilize that, while I believe these methods might have fewer blockers.
Motivating examples or use cases
Array-based ring buffer crate I wrote for fun:
https://github.com/yotamofek/ring-buffer/blob/11efcc6ba80a9bb7ad65ef491d8746cf132f4eb4/src/iter.rs#L36C17-L38C40
Doing ptr arithmetic on raw arrays/slices is scary because if you end up doing ptr.add(..)
on a *[T;N]
instead of a *T
that could have really bad implications. The methods I'm proposing here could help me write the cast more explicitly, and the as_(mut_)slice
method could also allow me to use the raw slice methods on my ptr (sorta like how autoderef allows using slice methods on non-raw-arrays).
Solution sketch
impl<T, const N: usize> *mut [T; N] {
pub fn as_mut_ptr(self) -> *mut T {}
pub fn as_mut_slice(self) -> *mut [T] {}
}
impl<T, const N: usize> *const [T; N] {
pub const fn as_ptr(self) -> *const T {}
pub const fn as_slice(self) -> *const [T] {}
}
Alternatives
Could be implemented in a 3rd party crate with extension trait, I guess.
Links and related work
rust-lang/rust#74265
rust-lang/rust#73986
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):
- We think this problem seems worth solving, and the standard library might be the right place to solve it.
- We think that this probably doesn't belong in the standard library.
Second, if there's a concrete solution:
- We think this specific solution looks roughly right, approved, you or someone else should implement this. (Further review will still happen on the subsequent implementation PR.)
- We're not sure this is the right solution, and the alternatives or other materials don't give us enough information to be sure about that. Here are some questions we have that aren't answered, or rough ideas about alternatives we'd want to see discussed.