Skip to content

Vec: add uninitialized(uint) and resize(&mut self, uint, T). #19104

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
wants to merge 2 commits into from
Closed
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
43 changes: 34 additions & 9 deletions src/libcollections/vec.rs
Original file line number Diff line number Diff line change
Expand Up @@ -352,6 +352,31 @@ impl<T: Clone> Vec<T> {
}
}

/// Resizes the `Vec` in-place so that `len()` equals to `new_len`.
///
/// Calls either `grow()` or `truncate()` depending on whether `new_len` is
/// larger than the current value of `len()` or not.
///
/// # Example
///
/// ```
/// let mut vec = vec!["hello", "world"];
/// vec.resize(1, "world");
/// assert_eq!(vec!["hello"], vec);
/// vec.resize(3, "world");
/// assert_eq!(vec!["hello", "world", "world"], vec);
/// ```
#[inline]
#[experimental]
pub fn resize(&mut self, new_len: uint, value: T) {
let l = self.len();
if l < new_len {
self.grow(new_len - l, value)
} else {
self.truncate(new_len)
}
}

/// Partitions a vector based on a predicate.
///
/// Clones the elements of the vector, partitioning them into two `Vec`s
Expand Down Expand Up @@ -692,20 +717,20 @@ impl<T> Vec<T> {
/// # Example
///
/// ```
/// let mut vec = vec![1i, 2, 3, 4];
/// let mut vec = vec![1i, 2, 3];
/// vec.truncate(2);
/// assert_eq!(vec, vec![1, 2]);
/// vec.truncate(1000);
/// assert_eq!(vec, vec![1, 2]);
/// ```
#[unstable = "matches collection reform specification; waiting on panic semantics"]
pub fn truncate(&mut self, len: uint) {
unsafe {
// drop any extra elements
while len < self.len {
// decrement len before the read(), so a panic on Drop doesn't
// re-drop the just-failed value.
self.len -= 1;
ptr::read(self.as_slice().unsafe_get(self.len));
}
// drop any extra elements
while len < self.len {
// decrement len before the read(), so a panic on Drop doesn't
// re-drop the just-failed value.
self.len -= 1;
unsafe { ptr::read(self.as_slice().unsafe_get(self.len)); }
}
}

Expand Down