Skip to content

Commit a23a77f

Browse files
committed
avoid materializing unintialized Boxes in RawVec
1 parent ed2a511 commit a23a77f

File tree

2 files changed

+12
-7
lines changed

2 files changed

+12
-7
lines changed

src/liballoc/boxed.rs

+6-3
Original file line numberDiff line numberDiff line change
@@ -546,9 +546,12 @@ impl<T: Copy> From<&[T]> for Box<[T]> {
546546
/// println!("{:?}", boxed_slice);
547547
/// ```
548548
fn from(slice: &[T]) -> Box<[T]> {
549-
let mut boxed = unsafe { RawVec::with_capacity(slice.len()).into_box() };
550-
boxed.copy_from_slice(slice);
551-
boxed
549+
let len = slice.len();
550+
let buf = RawVec::with_capacity(len);
551+
unsafe {
552+
ptr::copy_nonoverlapping(slice.as_ptr(), buf.ptr(), len);
553+
buf.into_box()
554+
}
552555
}
553556
}
554557

src/liballoc/raw_vec.rs

+6-4
Original file line numberDiff line numberDiff line change
@@ -685,12 +685,14 @@ impl<T, A: Alloc> RawVec<T, A> {
685685
impl<T> RawVec<T, Global> {
686686
/// Converts the entire buffer into `Box<[T]>`.
687687
///
688-
/// While it is not *strictly* Undefined Behavior to call
689-
/// this procedure while some of the RawVec is uninitialized,
690-
/// it certainly makes it trivial to trigger it.
691-
///
692688
/// Note that this will correctly reconstitute any `cap` changes
693689
/// that may have been performed. (see description of type for details)
690+
///
691+
/// # Undefined Behavior
692+
///
693+
/// All elements of `RawVec<T, Global>` must be initialized. Notice that
694+
/// the rules around uninitialized boxed values are not finalized yet,
695+
/// but until they are, it is advisable to avoid them.
694696
pub unsafe fn into_box(self) -> Box<[T]> {
695697
// NOTE: not calling `cap()` here, actually using the real `cap` field!
696698
let slice = slice::from_raw_parts_mut(self.ptr(), self.cap);

0 commit comments

Comments
 (0)