Skip to content

Commit 075ee26

Browse files
Loosen From<&[T]> for Box<[T]> bound to T: Clone
1 parent 1c42cb4 commit 075ee26

File tree

1 file changed

+30
-8
lines changed

1 file changed

+30
-8
lines changed

library/alloc/src/boxed.rs

+30-8
Original file line numberDiff line numberDiff line change
@@ -1455,9 +1455,35 @@ where
14551455
}
14561456
}
14571457

1458+
/// Specialization trait used for `From<&[T]>`.
1459+
trait BoxFromSlice<T> {
1460+
fn from_slice(slice: &[T]) -> Self;
1461+
}
1462+
1463+
#[cfg(not(no_global_oom_handling))]
1464+
impl<T: Clone> BoxFromSlice<T> for Box<[T]> {
1465+
#[inline]
1466+
default fn from_slice(slice: &[T]) -> Self {
1467+
slice.to_vec().into_boxed_slice()
1468+
}
1469+
}
1470+
1471+
#[cfg(not(no_global_oom_handling))]
1472+
impl<T: Copy> BoxFromSlice<T> for Box<[T]> {
1473+
#[inline]
1474+
fn from_slice(slice: &[T]) -> Self {
1475+
let len = slice.len();
1476+
let buf = RawVec::with_capacity(len);
1477+
unsafe {
1478+
ptr::copy_nonoverlapping(slice.as_ptr(), buf.ptr(), len);
1479+
buf.into_box(slice.len()).assume_init()
1480+
}
1481+
}
1482+
}
1483+
14581484
#[cfg(not(no_global_oom_handling))]
14591485
#[stable(feature = "box_from_slice", since = "1.17.0")]
1460-
impl<T: Copy> From<&[T]> for Box<[T]> {
1486+
impl<T: Clone> From<&[T]> for Box<[T]> {
14611487
/// Converts a `&[T]` into a `Box<[T]>`
14621488
///
14631489
/// This conversion allocates on the heap
@@ -1471,19 +1497,15 @@ impl<T: Copy> From<&[T]> for Box<[T]> {
14711497
///
14721498
/// println!("{boxed_slice:?}");
14731499
/// ```
1500+
#[inline]
14741501
fn from(slice: &[T]) -> Box<[T]> {
1475-
let len = slice.len();
1476-
let buf = RawVec::with_capacity(len);
1477-
unsafe {
1478-
ptr::copy_nonoverlapping(slice.as_ptr(), buf.ptr(), len);
1479-
buf.into_box(slice.len()).assume_init()
1480-
}
1502+
<Self as BoxFromSlice<T>>::from_slice(slice)
14811503
}
14821504
}
14831505

14841506
#[cfg(not(no_global_oom_handling))]
14851507
#[stable(feature = "box_from_cow", since = "1.45.0")]
1486-
impl<T: Copy> From<Cow<'_, [T]>> for Box<[T]> {
1508+
impl<T: Clone> From<Cow<'_, [T]>> for Box<[T]> {
14871509
/// Converts a `Cow<'_, [T]>` into a `Box<[T]>`
14881510
///
14891511
/// When `cow` is the `Cow::Borrowed` variant, this

0 commit comments

Comments
 (0)