Skip to content

Commit e7f1c8e

Browse files
committed
Fix shrink and capacity_from_bytes
1 parent 731cd26 commit e7f1c8e

File tree

1 file changed

+5
-3
lines changed

1 file changed

+5
-3
lines changed

library/alloc/src/raw_vec.rs

+5-3
Original file line numberDiff line numberDiff line change
@@ -402,7 +402,8 @@ impl<T, A: Allocator> RawVec<T, A> {
402402

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

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

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

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

0 commit comments

Comments
 (0)