about summary refs log tree commit diff
path: root/src/libcollections
diff options
context:
space:
mode:
authorAlex Crichton <alex@alexcrichton.com>2014-12-21 00:04:14 -0800
committerAlex Crichton <alex@alexcrichton.com>2014-12-21 09:27:34 -0800
commitfb6ff04994a61e5c8c6e0a270b5099ec6983ff10 (patch)
treefa2f97de059c5f1b8be9f660c31e04a854667ad0 /src/libcollections
parenteb47e1e4469fc23cf4fdce7aebdfd59d9b012064 (diff)
parentd61db0c6964b436b3fe1a65295e0101cce45debf (diff)
rollup merge of #20044: csouth3/vec-resize
This PR adds `resize()` to `Vec` in accordance with RFC 509.
Diffstat (limited to 'src/libcollections')
-rw-r--r--src/libcollections/vec.rs27
1 files changed, 27 insertions, 0 deletions
diff --git a/src/libcollections/vec.rs b/src/libcollections/vec.rs
index 0222a3689bd..64213021735 100644
--- a/src/libcollections/vec.rs
+++ b/src/libcollections/vec.rs
@@ -411,6 +411,33 @@ impl<T: Clone> Vec<T> {
         }
     }
 
+    /// Resizes the `Vec` in-place so that `len()` is equal to `new_len`.
+    ///
+    /// Calls either `extend()` or `truncate()` depending on whether `new_len`
+    /// is larger than the current value of `len()` or not.
+    ///
+    /// # Examples
+    ///
+    /// ```
+    /// let mut vec = vec!["hello"];
+    /// vec.resize(3, "world");
+    /// assert_eq!(vec, vec!["hello", "world", "world"]);
+    ///
+    /// let mut vec = vec![1i, 2, 3, 4];
+    /// vec.resize(2, 0);
+    /// assert_eq!(vec, vec![1, 2]);
+    /// ```
+    #[unstable = "matches collection reform specification; waiting for dust to settle"]
+    pub fn resize(&mut self, new_len: uint, value: T) {
+        let len = self.len();
+
+        if new_len > len {
+            self.extend(repeat(value).take(new_len - len));
+        } else {
+            self.truncate(new_len);
+        }
+    }
+
     /// Partitions a vector based on a predicate.
     ///
     /// Clones the elements of the vector, partitioning them into two `Vec<T>`s