Skip to content

Commit 24041c3

Browse files
committed
Add RawVec::finish_grow().
This factors out common code at the end of `RawVec::finish_grow_exact` and `RawVec::finish_grow_amortized`.
1 parent 3ee8933 commit 24041c3

File tree

1 file changed

+13
-19
lines changed

1 file changed

+13
-19
lines changed

library/alloc/src/raw_vec.rs

+13-19
Original file line numberDiff line numberDiff line change
@@ -455,25 +455,7 @@ where
455455
let cap = cmp::max(current_cap * 2, required_cap);
456456
let cap = cmp::max(min_non_zero_cap, cap);
457457

458-
let array_size = elem_layout.size().checked_mul(cap).ok_or(CapacityOverflow)?;
459-
alloc_guard(array_size)?;
460-
461-
let new_layout = unsafe { Layout::from_size_align_unchecked(array_size, elem_layout.align()) };
462-
463-
let new_ptr = if let Some((old_ptr, old_layout)) = current_memory {
464-
debug_assert_eq!(old_layout.align(), new_layout.align());
465-
unsafe {
466-
// The allocator checks for alignment equality
467-
intrinsics::assume(old_layout.align() == new_layout.align());
468-
alloc.grow(old_ptr, old_layout, new_layout)
469-
}
470-
} else {
471-
alloc.allocate(new_layout)
472-
}
473-
.map_err(|_| TryReserveError::from(AllocError { layout: new_layout, non_exhaustive: () }))?;
474-
475-
let new_cap = new_ptr.len() / elem_layout.size();
476-
Ok((new_ptr, new_cap))
458+
finish_grow(elem_layout, cap, current_memory, alloc)
477459
}
478460

479461
// This function is outside `RawVec` to minimize compile times. See the comment
@@ -499,6 +481,18 @@ where
499481
// succeeded, this early return will occur.)
500482
let cap = len.checked_add(additional).ok_or(CapacityOverflow)?;
501483

484+
finish_grow(elem_layout, cap, current_memory, alloc)
485+
}
486+
487+
fn finish_grow<A>(
488+
elem_layout: Layout,
489+
cap: usize,
490+
current_memory: Option<(NonNull<u8>, Layout)>,
491+
alloc: &mut A,
492+
) -> Result<(NonNull<[u8]>, usize), TryReserveError>
493+
where
494+
A: Allocator,
495+
{
502496
let array_size = elem_layout.size().checked_mul(cap).ok_or(CapacityOverflow)?;
503497
alloc_guard(array_size)?;
504498

0 commit comments

Comments
 (0)