Skip to content

Commit

Permalink
Fix shrink and capacity_from_bytes
Browse files Browse the repository at this point in the history
  • Loading branch information
a1phyr committed Aug 7, 2021
1 parent 731cd26 commit e7f1c8e
Showing 1 changed file with 5 additions and 3 deletions.
8 changes: 5 additions & 3 deletions library/alloc/src/raw_vec.rs
Original file line number Diff line number Diff line change
Expand Up @@ -402,7 +402,8 @@ impl<T, A: Allocator> RawVec<T, A> {

fn capacity_from_bytes(excess: usize) -> usize {
debug_assert_ne!(mem::size_of::<T>(), 0);
excess / mem::size_of::<T>()
let size_of_item = Layout::new::<T>().pad_to_align().size();
excess / size_of_item
}

fn set_ptr(&mut self, ptr: NonNull<[u8]>) {
Expand Down Expand Up @@ -466,10 +467,11 @@ impl<T, A: Allocator> RawVec<T, A> {
assert!(amount <= self.capacity(), "Tried to shrink to a larger capacity");

let (ptr, layout) = if let Some(mem) = self.current_memory() { mem } else { return Ok(()) };
let new_size = amount * mem::size_of::<T>();

let ptr = unsafe {
let new_layout = Layout::from_size_align_unchecked(new_size, layout.align());
// `Layout::array` cannot overflow here because it would have
// owerflown earlier when capacity was larger.
let new_layout = Layout::array::<T>(amount).unwrap_unchecked();
self.alloc
.shrink(ptr, layout, new_layout)
.map_err(|_| AllocError { layout: new_layout, non_exhaustive: () })?
Expand Down

0 comments on commit e7f1c8e

Please sign in to comment.