From 81a6709cf9f6e83b6dd2311f4dcd9e1ef1fba284 Mon Sep 17 00:00:00 2001 From: Josh Stone Date: Sat, 14 Dec 2019 22:28:52 -0800 Subject: [PATCH] Simplify Clone for Box<[T]> The bespoke `BoxBuilder` was basically a very simple `Vec`. Instead, let's clone to a real `Vec`, with all of its specialization for the task, then convert back to `Box<[T]>`. --- src/liballoc/boxed.rs | 43 +------------------------------------------ 1 file changed, 1 insertion(+), 42 deletions(-) diff --git a/src/liballoc/boxed.rs b/src/liballoc/boxed.rs index cc01de08cafb7..87a4924f9becc 100644 --- a/src/liballoc/boxed.rs +++ b/src/liballoc/boxed.rs @@ -1046,48 +1046,7 @@ impl FromIterator for Box<[A]> { #[stable(feature = "box_slice_clone", since = "1.3.0")] impl Clone for Box<[T]> { fn clone(&self) -> Self { - let mut new = BoxBuilder { data: RawVec::with_capacity(self.len()), len: 0 }; - - let mut target = new.data.ptr(); - - for item in self.iter() { - unsafe { - ptr::write(target, item.clone()); - target = target.offset(1); - }; - - new.len += 1; - } - - return unsafe { new.into_box() }; - - // Helper type for responding to panics correctly. - struct BoxBuilder { - data: RawVec, - len: usize, - } - - impl BoxBuilder { - unsafe fn into_box(self) -> Box<[T]> { - let raw = ptr::read(&self.data); - mem::forget(self); - raw.into_box() - } - } - - impl Drop for BoxBuilder { - fn drop(&mut self) { - let mut data = self.data.ptr(); - let max = unsafe { data.add(self.len) }; - - while data != max { - unsafe { - ptr::read(data); - data = data.offset(1); - } - } - } - } + self.to_vec().into_boxed_slice() } }