]> git.lizzy.rs Git - rust.git/commitdiff
collections: minimize code that's in unsafe blocks
authorErick Tryzelaar <erick.tryzelaar@gmail.com>
Mon, 7 Jul 2014 16:11:03 +0000 (09:11 -0700)
committerErick Tryzelaar <erick.tryzelaar@gmail.com>
Mon, 7 Jul 2014 16:16:36 +0000 (09:16 -0700)
This changes Vec::from_slice to call unsafe_push_all_clone
directly to avoid doing an unnecessary reserve_additional call

src/libcollections/vec.rs

index ea7442b1f34557f8a518ad6606eb8bfb41e5ff1e..3c38e6d1c2e8c8e611097567c9863724ad29ccb0 100644 (file)
@@ -198,7 +198,13 @@ pub fn append(mut self, second: &[T]) -> Vec<T> {
     #[inline]
     pub fn from_slice(values: &[T]) -> Vec<T> {
         let mut vector = Vec::with_capacity(values.len());
-        vector.push_all(values);
+
+        // Directly call `unsafe_push_all_clone` so we can skip a call to
+        // `reserve_addtional`.
+        unsafe {
+            unsafe_push_all_clone(&mut vector, values);
+        }
+
         vector
     }
 
@@ -240,8 +246,9 @@ pub fn from_elem(length: uint, value: T) -> Vec<T> {
     /// ```
     #[inline]
     pub fn push_all(&mut self, other: &[T]) {
+        self.reserve_additional(other.len());
+
         unsafe {
-            self.reserve_additional(other.len());
             unsafe_push_all_clone(self, other)
         }
     }
@@ -323,31 +330,24 @@ pub fn partitioned(&self, f: |&T| -> bool) -> (Vec<T>, Vec<T>) {
 #[unstable]
 impl<T:Clone> Clone for Vec<T> {
     fn clone(&self) -> Vec<T> {
-        unsafe {
-            let mut vector = Vec::with_capacity(self.len);
-            unsafe_push_all_clone(&mut vector, self.as_slice());
-            vector
-        }
+        Vec::from_slice(self.as_slice())
     }
 
     fn clone_from(&mut self, other: &Vec<T>) {
-        unsafe {
-            // drop anything in self that will not be overwritten
-            if self.len() > other.len() {
-                self.truncate(other.len())
-            }
-
-            // reuse the contained values' allocations/resources.
-            for (place, thing) in self.mut_iter().zip(other.iter()) {
-                place.clone_from(thing)
-            }
+        // drop anything in self that will not be overwritten
+        if self.len() > other.len() {
+            self.truncate(other.len())
+        }
 
-            // self.len <= other.len due to the truncate above, so the
-            // slice here is always in-bounds.
-            let slice = other.slice_from(self.len());
-            self.reserve_additional(slice.len());
-            unsafe_push_all_clone(self, slice)
+        // reuse the contained values' allocations/resources.
+        for (place, thing) in self.mut_iter().zip(other.iter()) {
+            place.clone_from(thing)
         }
+
+        // self.len <= other.len due to the truncate above, so the
+        // slice here is always in-bounds.
+        let slice = other.slice_from(self.len());
+        self.push_all(slice);
     }
 }