From 0917beb92a92d06f6267ee595a65cb0858f3ed59 Mon Sep 17 00:00:00 2001 From: Alex Helfet <alex.helfet@gmail.com> Date: Tue, 19 Dec 2017 20:08:40 +0000 Subject: [PATCH] Add method Vec::resize_default(). --- src/vec.rs | 25 +++++++++++++++++++++++++ 1 file changed, 25 insertions(+) diff --git a/src/vec.rs b/src/vec.rs index c8ea121..c153896 100644 --- a/src/vec.rs +++ b/src/vec.rs @@ -92,6 +92,8 @@ where /// If new_len is greater than len, the Vec is extended by the /// difference, with each additional slot filled with value. If /// new_len is less than len, the Vec is simply truncated. + /// + /// See also [`resize_default`]. pub fn resize(&mut self, new_len: usize, value: T) -> Result<(), BufferFullError> where T: Clone { @@ -109,6 +111,19 @@ where Ok(()) } + + /// Resizes the `Vec` in-place so that `len` is equal to `new_len`. + /// + /// If `new_len` is greater than `len`, the `Vec` is extended by the + /// difference, with each additional slot filled with `Default::default()`. + /// If `new_len` is less than `len`, the `Vec` is simply truncated. + /// + /// See also [`resize`]. + pub fn resize_default(&mut self, new_len: usize) + -> Result<(), BufferFullError> + where T: Clone + Default { + self.resize(new_len, T::default()) + } } impl<T, A> Drop for Vec<T, A> @@ -335,4 +350,14 @@ mod tests { v.resize(1, 0).unwrap(); assert_eq!(v[0], 17); } + + #[test] + fn resize_default() { + let mut v: Vec<u8, [u8; 4]> = Vec::new(); + + // resize_default is implemented using resize, so just check the + // correct value is being written. + v.resize_default(1).unwrap(); + assert_eq!(v[0], 0); + } } -- GitLab