Skip to content

Commit fb6ff04

Browse files
committed
rollup merge of #20044: csouth3/vec-resize
This PR adds `resize()` to `Vec` in accordance with RFC 509.
2 parents eb47e1e + d61db0c commit fb6ff04

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
@@ -411,6 +411,33 @@ impl<T: Clone> Vec<T> {
411411
}
412412
}
413413

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

0 commit comments

Comments
 (0)