rust-lang / libs-team

The home of the library team
Apache License 2.0
110 stars 18 forks source link

as_(mut_)ptr and as_(mut_)slice methods on raw array pointers #321

Closed yotamofek closed 6 months ago

yotamofek commented 6 months ago

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

https://github.com/rust-lang/rust/pull/119411

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

https://github.com/rust-lang/rust/issues/74265 https://github.com/rust-lang/rust/pull/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):

Second, if there's a concrete solution:

the8472 commented 6 months ago

We discussed this during today's libs-API meeting. We're ok accepting these methods as unstable additions. But stabilization will likely be blocked on the arbitrary_self_types feature (https://github.com/rust-lang/rfcs/pull/3519) and may end up moving the methods to impl [T; N] { fn as_mut_ptr(*const Self) } or make them available via some pointer-deref to equivalent slice pointer methods. This should be noted in the tracking issue.