From e9a7098658edaa6f4303de81002fa6d9fb2d81fb Mon Sep 17 00:00:00 2001 From: Luke Horsley Date: Fri, 25 May 2018 21:54:32 +0100 Subject: [PATCH] Added a resize function for BytesMut (#203) --- src/bytes.rs | 41 +++++++++++++++++++++++++++++++++++++++++ 1 file changed, 41 insertions(+) diff --git a/src/bytes.rs b/src/bytes.rs index 1022f00..cbcf58b 100644 --- a/src/bytes.rs +++ b/src/bytes.rs @@ -1276,6 +1276,32 @@ impl BytesMut { self.truncate(0); } + /// Resizes the buffer so that `len` is equal to `new_len`. + /// + /// If `new_len` is greater than `len`, the buffer is extended by the + /// difference with each additional byte set to `value`. If `new_len` is + /// less than `len`, the buffer is simply truncated. + /// + /// # Examples + /// + /// ``` + /// use bytes::BytesMut; + /// + /// let mut buf = BytesMut::new(); + /// + /// buf.resize(3, 0x1); + /// assert_eq!(&buf[..], &[0x1, 0x1, 0x1]); + /// + /// buf.resize(2, 0x2); + /// assert_eq!(&buf[..], &[0x1, 0x1]); + /// + /// buf.resize(4, 0x3); + /// assert_eq!(&buf[..], &[0x1, 0x1, 0x3, 0x3]); + /// ``` + pub fn resize(&mut self, new_len: usize, value: u8) { + self.inner.resize(new_len, value); + } + /// Sets the length of the buffer. /// /// This will explicitly set the size of the buffer without actually @@ -1890,6 +1916,21 @@ impl Inner { } } + fn resize(&mut self, new_len: usize, value: u8) { + let len = self.len(); + if new_len > len { + let additional = new_len - len; + self.reserve(additional); + unsafe { + let dst = self.as_raw()[len..].as_mut_ptr(); + ptr::write_bytes(dst, value, additional); + self.set_len(new_len); + } + } else { + self.truncate(new_len); + } + } + unsafe fn set_start(&mut self, start: usize) { // Setting the start to 0 is a no-op, so return early if this is the // case.