Skip to content

Commit d61db0c

Browse files
committed
Implement resize for Vec
This commit adds `resize` to `Vec` in accordance with RFC 509.
1 parent 95c2ed3 commit d61db0c

File tree

1 file changed

+27
-0
lines changed

1 file changed

+27
-0
lines changed

src/libcollections/vec.rs

Lines changed: 27 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -412,6 +412,33 @@ impl<T: Clone> Vec<T> {
412412
}
413413
}
414414

415+
/// Resizes the `Vec` in-place so that `len()` is equal to `new_len`.
416+
///
417+
/// Calls either `extend()` or `truncate()` depending on whether `new_len`
418+
/// is larger than the current value of `len()` or not.
419+
///
420+
/// # Examples
421+
///
422+
/// ```
423+
/// let mut vec = vec!["hello"];
424+
/// vec.resize(3, "world");
425+
/// assert_eq!(vec, vec!["hello", "world", "world"]);
426+
///
427+
/// let mut vec = vec![1i, 2, 3, 4];
428+
/// vec.resize(2, 0);
429+
/// assert_eq!(vec, vec![1, 2]);
430+
/// ```
431+
#[unstable = "matches collection reform specification; waiting for dust to settle"]
432+
pub fn resize(&mut self, new_len: uint, value: T) {
433+
let len = self.len();
434+
435+
if new_len > len {
436+
self.extend(repeat(value).take(new_len - len));
437+
} else {
438+
self.truncate(new_len);
439+
}
440+
}
441+
415442
/// Partitions a vector based on a predicate.
416443
///
417444
/// Clones the elements of the vector, partitioning them into two `Vec<T>`s

0 commit comments

Comments
 (0)