Skip to content

Commit

Permalink
Don't panic when trying to reclaim a huge number
Browse files Browse the repository at this point in the history
Implementing the suggestion by @conradludgate
  • Loading branch information
shahn committed Jun 27, 2024
1 parent 26c14f0 commit c5db373
Show file tree
Hide file tree
Showing 2 changed files with 14 additions and 4 deletions.
6 changes: 5 additions & 1 deletion src/bytes_mut.rs
Original file line number Diff line number Diff line change
Expand Up @@ -666,7 +666,11 @@ impl BytesMut {
// allocating a new vector with the requested capacity.
//
// Compute the new capacity
let mut new_cap = len.checked_add(additional).expect("overflow");
let mut new_cap = match len.checked_add(additional) {
Some(new_cap) => new_cap,
None if !allocate => return false,
None => panic!("overflow"),
};

unsafe {
// First, try to reclaim the buffer. This is possible if the current
Expand Down
12 changes: 9 additions & 3 deletions tests/test_bytes.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1285,7 +1285,7 @@ fn test_bytes_make_mut_promotable_even_arc_offset() {
}

#[test]
fn try_reserve_empty() {
fn try_reclaim_empty() {
let mut buf = BytesMut::new();
assert_eq!(false, buf.try_reclaim(6));
buf.reserve(6);
Expand All @@ -1306,9 +1306,12 @@ fn try_reserve_empty() {
}

#[test]
fn try_reserve_vec() {
fn try_reclaim_vec() {
let mut buf = BytesMut::with_capacity(6);
buf.put_slice(b"abc");
// Reclaiming a ludicrous amount of space should calmly return false
assert_eq!(false, buf.try_reclaim(usize::MAX));

assert_eq!(false, buf.try_reclaim(6));
buf.advance(2);
assert_eq!(4, buf.capacity());
Expand All @@ -1322,11 +1325,14 @@ fn try_reserve_vec() {
}

#[test]
fn try_reserve_arc() {
fn try_reclaim_arc() {
let mut buf = BytesMut::with_capacity(6);
buf.put_slice(b"abc");
let x = buf.split().freeze();
buf.put_slice(b"def");
// Reclaiming a ludicrous amount of space should calmly return false
assert_eq!(false, buf.try_reclaim(usize::MAX));

let y = buf.split().freeze();
let z = y.clone();
assert_eq!(false, buf.try_reclaim(6));
Expand Down

0 comments on commit c5db373

Please sign in to comment.