Skip to content

Tracking Issue for slice_to_boxed #82725

Closed
@calebsander

Description

@calebsander

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

Unresolved Questions

  • None yet.

Metadata

Metadata

Assignees

No one assigned

    Labels

    C-tracking-issueCategory: An issue tracking the progress of sth. like the implementation of an RFCT-libs-apiRelevant to the library API team, which will review and decide on the PR/issue.

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions