Description
Feature gate: #![feature(slice_to_boxed)]
This is a tracking issue for copying/cloning slices into boxed slices.
The current recommended approach for turning a &[T] where T: Clone
into a Box<[T]>
seems to be to use .to_vec().into_boxed_slice()
. This misses some opportunities for optimization, since the Vec
is allocated with a known length. A Godbolt comparison shows that Vec::into_boxed_slice()
emits unnecessary calls to realloc()
and free()
and uses some extra registers for local variables: https://godbolt.org/z/eq7Pc7.
There is currently an impl<T: Copy> From<&[T]> for Box<[T]>
, but not for T: Clone
like there is for Vec<T>
.
We propose adding a function on slices to clone/copy them into boxed slices and relaxing the From<&[T]>
bound to T: Clone
for Box<[T]>
. Both of these should be specialized to a memcpy()
for the common case of T: Copy
. This impl
bound change would be insta-stable, so it should be delayed until we are ready to stabilize the rest of this feature.
Public API
impl<T: Clone> [T] {
pub fn to_boxed_slice(&self) -> Box<Self>;
pub fn to_boxed_slice_in<A: Allocator>(&self, alloc: A) -> Box<Self, A>;
}
// Bounds relaxed from T: Copy
impl<T: Clone> From<&[T]> for Box<[T]> { /* ... */ }
// Bounds relaxed from T: Copy
impl<T: Clone> From<Cow<'_, [T]>> for Box<[T]> { /* ... */ }
Steps / History
- Implementation of new functions to clone/copy slices into boxed slices: Add
to_boxed_slice()
to clone slice into boxed slice #80460 - Replacing
T: Copy
bounds withT: Copy
onBox<[T]>
'sFrom<&[T]>
andFrom<Cow<'_, [T]>>
implementations - Final commenting period (FCP)
- Stabilization PR
Unresolved Questions
- None yet.