Fix #354 -- Make advance_mut impl of BufMut for Vec<u8> panic if cnt > remaining

This commit is contained in:
Tim Hambourger
2020-03-25 12:30:15 -07:00
committed by Sean McArthur
parent 8bbe9dd87b
commit b4ebe8432e
2 changed files with 9 additions and 8 deletions
+7 -5
View File
@@ -990,11 +990,13 @@ impl BufMut for Vec<u8> {
unsafe fn advance_mut(&mut self, cnt: usize) { unsafe fn advance_mut(&mut self, cnt: usize) {
let len = self.len(); let len = self.len();
let remaining = self.capacity() - len; let remaining = self.capacity() - len;
if cnt > remaining {
// Reserve additional capacity, and ensure that the total length assert!(
// will not overflow usize. cnt <= remaining,
self.reserve(cnt); "cannot advance past `remaining_mut`: {:?} <= {:?}",
} cnt,
remaining
);
self.set_len(len + cnt); self.set_len(len + cnt);
} }
+2 -3
View File
@@ -45,13 +45,12 @@ fn test_put_u16() {
} }
#[test] #[test]
#[should_panic(expected = "cannot advance")]
fn test_vec_advance_mut() { fn test_vec_advance_mut() {
// Regression test for carllerche/bytes#108. // Verify fix for #354
let mut buf = Vec::with_capacity(8); let mut buf = Vec::with_capacity(8);
unsafe { unsafe {
buf.advance_mut(12); buf.advance_mut(12);
assert_eq!(buf.len(), 12);
assert!(buf.capacity() >= 12, "capacity: {}", buf.capacity());
} }
} }