]> git.lizzy.rs Git - rust.git/blobdiff - src/libstd/vec.rs
auto merge of #8604 : kballard/rust/iter-size-hint, r=graydon
[rust.git] / src / libstd / vec.rs
index e69cb1341bf9d4e50fcfa3defe679733c9784423..01e7e053cf5d62da337c9f4ce39902e6fc688f93 100644 (file)
@@ -1214,6 +1214,7 @@ pub trait OwnedVector<T> {
     fn reserve(&mut self, n: uint);
     fn reserve_at_least(&mut self, n: uint);
     fn capacity(&self) -> uint;
+    fn shrink_to_fit(&mut self);
 
     fn push(&mut self, t: T);
     unsafe fn push_fast(&mut self, t: T);
@@ -1307,6 +1308,7 @@ fn reserve(&mut self, n: uint) {
      *
      * * n - The number of elements to reserve space for
      */
+    #[inline]
     fn reserve_at_least(&mut self, n: uint) {
         self.reserve(uint::next_power_of_two(n));
     }
@@ -1325,6 +1327,17 @@ fn capacity(&self) -> uint {
         }
     }
 
+    /// Shrink the capacity of the vector to match the length
+    fn shrink_to_fit(&mut self) {
+        unsafe {
+            let ptr: *mut *mut Vec<()> = cast::transmute(self);
+            let alloc = (**ptr).fill;
+            let size = alloc + sys::size_of::<Vec<()>>();
+            *ptr = realloc_raw(*ptr as *mut c_void, size) as *mut Vec<()>;
+            (**ptr).alloc = alloc;
+        }
+    }
+
     /// Append an element to a vector
     #[inline]
     fn push(&mut self, t: T) {
@@ -2395,6 +2408,7 @@ mod tests {
     use sys;
     use vec::*;
     use cmp::*;
+    use prelude::*;
 
     fn square(n: uint) -> uint { n * n }
 
@@ -3668,6 +3682,18 @@ fn test_iter_zero_sized() {
         }
         assert!(cnt == 3);
     }
+
+    #[test]
+    fn test_shrink_to_fit() {
+        let mut xs = ~[0, 1, 2, 3];
+        for i in range(4, 100) {
+            xs.push(i)
+        }
+        assert_eq!(xs.capacity(), 128);
+        xs.shrink_to_fit();
+        assert_eq!(xs.capacity(), 100);
+        assert_eq!(xs, range(0, 100).to_owned_vec());
+    }
 }
 
 #[cfg(test)]