Description
Proposal
This is an ACP for rust-lang/rust#95198, which I believe predates ACPs. Either that or I just didn't know about them at the time.
Problem statement
In some cases, it's valuable to convert between slices and arrays, and there's not really a good way to do this safely.
Motivation, use-cases
The current best API we have for this is the unstable as_chunks
, which leads to the below being used fairly often:
slice.as_chunks::<N>().0[0]
Which just isn't as readable.
Solution sketches
The proposed solution:
impl [T] {
pub const fn first_chunk<const N: usize>(&self) -> Option<&[T; N]>;
pub const fn first_chunk_mut<const N: usize>(&mut self) -> Option<&mut [T; N]>;
pub const fn last_chunk<const N: usize>(&self) -> Option<&[T; N]>;
pub const fn last_chunk_mut<const N: usize>(&mut self) -> Option<&mut [T; N]>;
pub const fn split_first_chunk<const N: usize>(&self) -> Option<(&[T; N], &[T])>;
pub const fn split_first_chunk_mut<const N: usize>(&mut self) -> Option<(&mut [T; N], &mut [T])>;
pub const fn split_last_chunk<const N: usize>(&self) -> Option<(&[T; N], &[T])>;
pub const fn split_last_chunk_mut<const N: usize>(&mut self) -> Option<(&mut [T; N], &mut [T])>;
}
This borrows directly from the first
/last
APIs:
impl [T] {
pub const fn first(&self) -> Option<&T>;
pub const fn first_mut(&mut self) -> Option<&mut T>;
pub const fn last(&self) -> Option<&T>;
pub const fn last_mut(&mut self) -> Option<&mut T>;
pub const fn split_first(&self) -> Option<(&T, &[T])>;
pub const fn split_first_mut(&mut self) -> Option<(&mut T, &mut [T])>;
pub const fn split_last(&self) -> Option<(&T, &[T])>;
pub const fn split_last_mut(&mut self) -> Option<(&mut T, &mut [T])>;
}
Links and related work
The PR with the proposed solution: rust-lang/rust#95198
Discussion in the array_chunks
tracking issue: rust-lang/rust#74985
What happens now?
This issue is part of the libs-api team API change proposal process. Once this issue is filed the libs-api team will review open proposals in its weekly meeting. You should receive feedback within a week or two.