@@ -697,9 +697,15 @@ impl BytesMut {
697697
698698 let offset = self . ptr . as_ptr ( ) . offset_from ( ptr) as usize ;
699699
700+ let new_cap_plus_offset = match new_cap. checked_add ( offset) {
701+ Some ( new_cap_plus_offset) => new_cap_plus_offset,
702+ None if !allocate => return false ,
703+ None => panic ! ( "overflow" ) ,
704+ } ;
705+
700706 // Compare the condition in the `kind == KIND_VEC` case above
701707 // for more details.
702- if v_capacity >= new_cap + offset {
708+ if v_capacity >= new_cap_plus_offset {
703709 self . cap = new_cap;
704710 // no copy is necessary
705711 } else if v_capacity >= new_cap && offset >= len {
@@ -715,14 +721,12 @@ impl BytesMut {
715721 if !allocate {
716722 return false ;
717723 }
718- // calculate offset
719- let off = ( self . ptr . as_ptr ( ) as usize ) - ( v. as_ptr ( ) as usize ) ;
720724
721725 // new_cap is calculated in terms of `BytesMut`, not the underlying
722726 // `Vec`, so it does not take the offset into account.
723727 //
724728 // Thus we have to manually add it here.
725- new_cap = new_cap . checked_add ( off ) . expect ( "overflow" ) ;
729+ new_cap = new_cap_plus_offset ;
726730
727731 // The vector capacity is not sufficient. The reserve request is
728732 // asking for more than the initial buffer capacity. Allocate more
@@ -744,13 +748,13 @@ impl BytesMut {
744748 // the unused capacity of the vector is copied over to the new
745749 // allocation, so we need to ensure that we don't have any data we
746750 // care about in the unused capacity before calling `reserve`.
747- debug_assert ! ( off + len <= v. capacity( ) ) ;
748- v. set_len ( off + len) ;
751+ debug_assert ! ( offset + len <= v. capacity( ) ) ;
752+ v. set_len ( offset + len) ;
749753 v. reserve ( new_cap - v. len ( ) ) ;
750754
751755 // Update the info
752- self . ptr = vptr ( v. as_mut_ptr ( ) . add ( off ) ) ;
753- self . cap = v. capacity ( ) - off ;
756+ self . ptr = vptr ( v. as_mut_ptr ( ) . add ( offset ) ) ;
757+ self . cap = v. capacity ( ) - offset ;
754758 }
755759
756760 return true ;
0 commit comments