Skip to content

Commit 0f03fdd

Browse files
authored
Rollup merge of rust-lang#72417 - nnethercote:rm-RawVec-reserve_in_place, r=Amanieu
Remove `RawVec::reserve_in_place`. And some related clean-ups. r? @oli-obk
2 parents feb3536 + c9cbe7e commit 0f03fdd

File tree

3 files changed

+79
-137
lines changed

3 files changed

+79
-137
lines changed

src/liballoc/raw_vec.rs

+36-86
Original file line numberDiff line numberDiff line change
@@ -9,7 +9,7 @@ use core::ptr::{NonNull, Unique};
99
use core::slice;
1010

1111
use crate::alloc::{
12-
handle_alloc_error, AllocErr,
12+
handle_alloc_error,
1313
AllocInit::{self, *},
1414
AllocRef, Global, Layout,
1515
ReallocPlacement::{self, *},
@@ -235,13 +235,13 @@ impl<T, A: AllocRef> RawVec<T, A> {
235235
}
236236
}
237237

238-
/// Ensures that the buffer contains at least enough space to hold
239-
/// `used_capacity + needed_extra_capacity` elements. If it doesn't already have
240-
/// enough capacity, will reallocate enough space plus comfortable slack
241-
/// space to get amortized `O(1)` behavior. Will limit this behavior
242-
/// if it would needlessly cause itself to panic.
238+
/// Ensures that the buffer contains at least enough space to hold `len +
239+
/// additional` elements. If it doesn't already have enough capacity, will
240+
/// reallocate enough space plus comfortable slack space to get amortized
241+
/// `O(1)` behavior. Will limit this behavior if it would needlessly cause
242+
/// itself to panic.
243243
///
244-
/// If `used_capacity` exceeds `self.capacity()`, this may fail to actually allocate
244+
/// If `len` exceeds `self.capacity()`, this may fail to actually allocate
245245
/// the requested space. This is not really unsafe, but the unsafe
246246
/// code *you* write that relies on the behavior of this function may break.
247247
///
@@ -287,64 +287,32 @@ impl<T, A: AllocRef> RawVec<T, A> {
287287
/// # vector.push_all(&[1, 3, 5, 7, 9]);
288288
/// # }
289289
/// ```
290-
pub fn reserve(&mut self, used_capacity: usize, needed_extra_capacity: usize) {
291-
match self.try_reserve(used_capacity, needed_extra_capacity) {
290+
pub fn reserve(&mut self, len: usize, additional: usize) {
291+
match self.try_reserve(len, additional) {
292292
Err(CapacityOverflow) => capacity_overflow(),
293293
Err(AllocError { layout, .. }) => handle_alloc_error(layout),
294294
Ok(()) => { /* yay */ }
295295
}
296296
}
297297

298298
/// The same as `reserve`, but returns on errors instead of panicking or aborting.
299-
pub fn try_reserve(
300-
&mut self,
301-
used_capacity: usize,
302-
needed_extra_capacity: usize,
303-
) -> Result<(), TryReserveError> {
304-
if self.needs_to_grow(used_capacity, needed_extra_capacity) {
305-
self.grow_amortized(used_capacity, needed_extra_capacity, MayMove)
299+
pub fn try_reserve(&mut self, len: usize, additional: usize) -> Result<(), TryReserveError> {
300+
if self.needs_to_grow(len, additional) {
301+
self.grow_amortized(len, additional)
306302
} else {
307303
Ok(())
308304
}
309305
}
310306

311-
/// Attempts to ensure that the buffer contains at least enough space to hold
312-
/// `used_capacity + needed_extra_capacity` elements. If it doesn't already have
313-
/// enough capacity, will reallocate in place enough space plus comfortable slack
314-
/// space to get amortized `O(1)` behavior. Will limit this behaviour
315-
/// if it would needlessly cause itself to panic.
307+
/// Ensures that the buffer contains at least enough space to hold `len +
308+
/// additional` elements. If it doesn't already, will reallocate the
309+
/// minimum possible amount of memory necessary. Generally this will be
310+
/// exactly the amount of memory necessary, but in principle the allocator
311+
/// is free to give back more than we asked for.
316312
///
317-
/// If `used_capacity` exceeds `self.capacity()`, this may fail to actually allocate
318-
/// the requested space. This is not really unsafe, but the unsafe
319-
/// code *you* write that relies on the behavior of this function may break.
320-
///
321-
/// Returns `true` if the reallocation attempt has succeeded.
322-
///
323-
/// # Panics
324-
///
325-
/// * Panics if the requested capacity exceeds `usize::MAX` bytes.
326-
/// * Panics on 32-bit platforms if the requested capacity exceeds
327-
/// `isize::MAX` bytes.
328-
pub fn reserve_in_place(&mut self, used_capacity: usize, needed_extra_capacity: usize) -> bool {
329-
// This is more readable than putting this in one line:
330-
// `!self.needs_to_grow(...) || self.grow(...).is_ok()`
331-
if self.needs_to_grow(used_capacity, needed_extra_capacity) {
332-
self.grow_amortized(used_capacity, needed_extra_capacity, InPlace).is_ok()
333-
} else {
334-
true
335-
}
336-
}
337-
338-
/// Ensures that the buffer contains at least enough space to hold
339-
/// `used_capacity + needed_extra_capacity` elements. If it doesn't already,
340-
/// will reallocate the minimum possible amount of memory necessary.
341-
/// Generally this will be exactly the amount of memory necessary,
342-
/// but in principle the allocator is free to give back more than what
343-
/// we asked for.
344-
///
345-
/// If `used_capacity` exceeds `self.capacity()`, this may fail to actually allocate
346-
/// the requested space. This is not really unsafe, but the unsafe
347-
/// code *you* write that relies on the behavior of this function may break.
313+
/// If `len` exceeds `self.capacity()`, this may fail to actually allocate
314+
/// the requested space. This is not really unsafe, but the unsafe code
315+
/// *you* write that relies on the behavior of this function may break.
348316
///
349317
/// # Panics
350318
///
@@ -355,8 +323,8 @@ impl<T, A: AllocRef> RawVec<T, A> {
355323
/// # Aborts
356324
///
357325
/// Aborts on OOM.
358-
pub fn reserve_exact(&mut self, used_capacity: usize, needed_extra_capacity: usize) {
359-
match self.try_reserve_exact(used_capacity, needed_extra_capacity) {
326+
pub fn reserve_exact(&mut self, len: usize, additional: usize) {
327+
match self.try_reserve_exact(len, additional) {
360328
Err(CapacityOverflow) => capacity_overflow(),
361329
Err(AllocError { layout, .. }) => handle_alloc_error(layout),
362330
Ok(()) => { /* yay */ }
@@ -366,14 +334,10 @@ impl<T, A: AllocRef> RawVec<T, A> {
366334
/// The same as `reserve_exact`, but returns on errors instead of panicking or aborting.
367335
pub fn try_reserve_exact(
368336
&mut self,
369-
used_capacity: usize,
370-
needed_extra_capacity: usize,
337+
len: usize,
338+
additional: usize,
371339
) -> Result<(), TryReserveError> {
372-
if self.needs_to_grow(used_capacity, needed_extra_capacity) {
373-
self.grow_exact(used_capacity, needed_extra_capacity)
374-
} else {
375-
Ok(())
376-
}
340+
if self.needs_to_grow(len, additional) { self.grow_exact(len, additional) } else { Ok(()) }
377341
}
378342

379343
/// Shrinks the allocation down to the specified amount. If the given amount
@@ -398,8 +362,8 @@ impl<T, A: AllocRef> RawVec<T, A> {
398362
impl<T, A: AllocRef> RawVec<T, A> {
399363
/// Returns if the buffer needs to grow to fulfill the needed extra capacity.
400364
/// Mainly used to make inlining reserve-calls possible without inlining `grow`.
401-
fn needs_to_grow(&self, used_capacity: usize, needed_extra_capacity: usize) -> bool {
402-
needed_extra_capacity > self.capacity().wrapping_sub(used_capacity)
365+
fn needs_to_grow(&self, len: usize, additional: usize) -> bool {
366+
additional > self.capacity().wrapping_sub(len)
403367
}
404368

405369
fn capacity_from_bytes(excess: usize) -> usize {
@@ -419,14 +383,9 @@ impl<T, A: AllocRef> RawVec<T, A> {
419383
// so that all of the code that depends on `T` is within it, while as much
420384
// of the code that doesn't depend on `T` as possible is in functions that
421385
// are non-generic over `T`.
422-
fn grow_amortized(
423-
&mut self,
424-
used_capacity: usize,
425-
needed_extra_capacity: usize,
426-
placement: ReallocPlacement,
427-
) -> Result<(), TryReserveError> {
386+
fn grow_amortized(&mut self, len: usize, additional: usize) -> Result<(), TryReserveError> {
428387
// This is ensured by the calling contexts.
429-
debug_assert!(needed_extra_capacity > 0);
388+
debug_assert!(additional > 0);
430389

431390
if mem::size_of::<T>() == 0 {
432391
// Since we return a capacity of `usize::MAX` when `elem_size` is
@@ -435,8 +394,7 @@ impl<T, A: AllocRef> RawVec<T, A> {
435394
}
436395

437396
// Nothing we can really do about these checks, sadly.
438-
let required_cap =
439-
used_capacity.checked_add(needed_extra_capacity).ok_or(CapacityOverflow)?;
397+
let required_cap = len.checked_add(additional).ok_or(CapacityOverflow)?;
440398

441399
// This guarantees exponential growth. The doubling cannot overflow
442400
// because `cap <= isize::MAX` and the type of `cap` is `usize`.
@@ -461,30 +419,26 @@ impl<T, A: AllocRef> RawVec<T, A> {
461419
let new_layout = Layout::array::<T>(cap);
462420

463421
// `finish_grow` is non-generic over `T`.
464-
let memory = finish_grow(new_layout, placement, self.current_memory(), &mut self.alloc)?;
422+
let memory = finish_grow(new_layout, self.current_memory(), &mut self.alloc)?;
465423
self.set_memory(memory);
466424
Ok(())
467425
}
468426

469427
// The constraints on this method are much the same as those on
470428
// `grow_amortized`, but this method is usually instantiated less often so
471429
// it's less critical.
472-
fn grow_exact(
473-
&mut self,
474-
used_capacity: usize,
475-
needed_extra_capacity: usize,
476-
) -> Result<(), TryReserveError> {
430+
fn grow_exact(&mut self, len: usize, additional: usize) -> Result<(), TryReserveError> {
477431
if mem::size_of::<T>() == 0 {
478432
// Since we return a capacity of `usize::MAX` when the type size is
479433
// 0, getting to here necessarily means the `RawVec` is overfull.
480434
return Err(CapacityOverflow);
481435
}
482436

483-
let cap = used_capacity.checked_add(needed_extra_capacity).ok_or(CapacityOverflow)?;
437+
let cap = len.checked_add(additional).ok_or(CapacityOverflow)?;
484438
let new_layout = Layout::array::<T>(cap);
485439

486440
// `finish_grow` is non-generic over `T`.
487-
let memory = finish_grow(new_layout, MayMove, self.current_memory(), &mut self.alloc)?;
441+
let memory = finish_grow(new_layout, self.current_memory(), &mut self.alloc)?;
488442
self.set_memory(memory);
489443
Ok(())
490444
}
@@ -518,7 +472,6 @@ impl<T, A: AllocRef> RawVec<T, A> {
518472
// much smaller than the number of `T` types.)
519473
fn finish_grow<A>(
520474
new_layout: Result<Layout, LayoutErr>,
521-
placement: ReallocPlacement,
522475
current_memory: Option<(NonNull<u8>, Layout)>,
523476
alloc: &mut A,
524477
) -> Result<MemoryBlock, TryReserveError>
@@ -532,12 +485,9 @@ where
532485

533486
let memory = if let Some((ptr, old_layout)) = current_memory {
534487
debug_assert_eq!(old_layout.align(), new_layout.align());
535-
unsafe { alloc.grow(ptr, old_layout, new_layout.size(), placement, Uninitialized) }
488+
unsafe { alloc.grow(ptr, old_layout, new_layout.size(), MayMove, Uninitialized) }
536489
} else {
537-
match placement {
538-
MayMove => alloc.alloc(new_layout, Uninitialized),
539-
InPlace => Err(AllocErr),
540-
}
490+
alloc.alloc(new_layout, Uninitialized)
541491
}
542492
.map_err(|_| AllocError { layout: new_layout, non_exhaustive: () })?;
543493

src/liballoc/vec.rs

+4-4
Original file line numberDiff line numberDiff line change
@@ -2977,12 +2977,12 @@ impl<T> Drain<'_, T> {
29772977
}
29782978

29792979
/// Makes room for inserting more elements before the tail.
2980-
unsafe fn move_tail(&mut self, extra_capacity: usize) {
2980+
unsafe fn move_tail(&mut self, additional: usize) {
29812981
let vec = self.vec.as_mut();
2982-
let used_capacity = self.tail_start + self.tail_len;
2983-
vec.buf.reserve(used_capacity, extra_capacity);
2982+
let len = self.tail_start + self.tail_len;
2983+
vec.buf.reserve(len, additional);
29842984

2985-
let new_tail_start = self.tail_start + extra_capacity;
2985+
let new_tail_start = self.tail_start + additional;
29862986
let src = vec.as_ptr().add(self.tail_start);
29872987
let dst = vec.as_mut_ptr().add(new_tail_start);
29882988
ptr::copy(src, dst, self.tail_len);

src/librustc_arena/lib.rs

+39-47
Original file line numberDiff line numberDiff line change
@@ -146,18 +146,18 @@ impl<T> TypedArena<T> {
146146
}
147147

148148
#[inline]
149-
fn can_allocate(&self, len: usize) -> bool {
150-
let available_capacity_bytes = self.end.get() as usize - self.ptr.get() as usize;
151-
let at_least_bytes = len.checked_mul(mem::size_of::<T>()).unwrap();
152-
available_capacity_bytes >= at_least_bytes
149+
fn can_allocate(&self, additional: usize) -> bool {
150+
let available_bytes = self.end.get() as usize - self.ptr.get() as usize;
151+
let additional_bytes = additional.checked_mul(mem::size_of::<T>()).unwrap();
152+
available_bytes >= additional_bytes
153153
}
154154

155155
/// Ensures there's enough space in the current chunk to fit `len` objects.
156156
#[inline]
157-
fn ensure_capacity(&self, len: usize) {
158-
if !self.can_allocate(len) {
159-
self.grow(len);
160-
debug_assert!(self.can_allocate(len));
157+
fn ensure_capacity(&self, additional: usize) {
158+
if !self.can_allocate(additional) {
159+
self.grow(additional);
160+
debug_assert!(self.can_allocate(additional));
161161
}
162162
}
163163

@@ -214,36 +214,31 @@ impl<T> TypedArena<T> {
214214
/// Grows the arena.
215215
#[inline(never)]
216216
#[cold]
217-
fn grow(&self, n: usize) {
217+
fn grow(&self, additional: usize) {
218218
unsafe {
219-
// We need the element size in to convert chunk sizes (ranging from
219+
// We need the element size to convert chunk sizes (ranging from
220220
// PAGE to HUGE_PAGE bytes) to element counts.
221221
let elem_size = cmp::max(1, mem::size_of::<T>());
222222
let mut chunks = self.chunks.borrow_mut();
223-
let (chunk, mut new_capacity);
223+
let mut new_cap;
224224
if let Some(last_chunk) = chunks.last_mut() {
225225
let used_bytes = self.ptr.get() as usize - last_chunk.start() as usize;
226-
let currently_used_cap = used_bytes / mem::size_of::<T>();
227-
last_chunk.entries = currently_used_cap;
228-
if last_chunk.storage.reserve_in_place(currently_used_cap, n) {
229-
self.end.set(last_chunk.end());
230-
return;
231-
} else {
232-
// If the previous chunk's capacity is less than HUGE_PAGE
233-
// bytes, then this chunk will be least double the previous
234-
// chunk's size.
235-
new_capacity = last_chunk.storage.capacity();
236-
if new_capacity < HUGE_PAGE / elem_size {
237-
new_capacity = new_capacity.checked_mul(2).unwrap();
238-
}
226+
last_chunk.entries = used_bytes / mem::size_of::<T>();
227+
228+
// If the previous chunk's capacity is less than HUGE_PAGE
229+
// bytes, then this chunk will be least double the previous
230+
// chunk's size.
231+
new_cap = last_chunk.storage.capacity();
232+
if new_cap < HUGE_PAGE / elem_size {
233+
new_cap = new_cap.checked_mul(2).unwrap();
239234
}
240235
} else {
241-
new_capacity = PAGE / elem_size;
236+
new_cap = PAGE / elem_size;
242237
}
243-
// Also ensure that this chunk can fit `n`.
244-
new_capacity = cmp::max(n, new_capacity);
238+
// Also ensure that this chunk can fit `additional`.
239+
new_cap = cmp::max(additional, new_cap);
245240

246-
chunk = TypedArenaChunk::<T>::new(new_capacity);
241+
let chunk = TypedArenaChunk::<T>::new(new_cap);
247242
self.ptr.set(chunk.start());
248243
self.end.set(chunk.end());
249244
chunks.push(chunk);
@@ -347,31 +342,28 @@ impl DroplessArena {
347342

348343
#[inline(never)]
349344
#[cold]
350-
fn grow(&self, needed_bytes: usize) {
345+
fn grow(&self, additional: usize) {
351346
unsafe {
352347
let mut chunks = self.chunks.borrow_mut();
353-
let (chunk, mut new_capacity);
348+
let mut new_cap;
354349
if let Some(last_chunk) = chunks.last_mut() {
355-
let used_bytes = self.ptr.get() as usize - last_chunk.start() as usize;
356-
if last_chunk.storage.reserve_in_place(used_bytes, needed_bytes) {
357-
self.end.set(last_chunk.end());
358-
return;
359-
} else {
360-
// If the previous chunk's capacity is less than HUGE_PAGE
361-
// bytes, then this chunk will be least double the previous
362-
// chunk's size.
363-
new_capacity = last_chunk.storage.capacity();
364-
if new_capacity < HUGE_PAGE {
365-
new_capacity = new_capacity.checked_mul(2).unwrap();
366-
}
350+
// There is no need to update `last_chunk.entries` because that
351+
// field isn't used by `DroplessArena`.
352+
353+
// If the previous chunk's capacity is less than HUGE_PAGE
354+
// bytes, then this chunk will be least double the previous
355+
// chunk's size.
356+
new_cap = last_chunk.storage.capacity();
357+
if new_cap < HUGE_PAGE {
358+
new_cap = new_cap.checked_mul(2).unwrap();
367359
}
368360
} else {
369-
new_capacity = PAGE;
361+
new_cap = PAGE;
370362
}
371-
// Also ensure that this chunk can fit `needed_bytes`.
372-
new_capacity = cmp::max(needed_bytes, new_capacity);
363+
// Also ensure that this chunk can fit `additional`.
364+
new_cap = cmp::max(additional, new_cap);
373365

374-
chunk = TypedArenaChunk::<u8>::new(new_capacity);
366+
let chunk = TypedArenaChunk::<u8>::new(new_cap);
375367
self.ptr.set(chunk.start());
376368
self.end.set(chunk.end());
377369
chunks.push(chunk);
@@ -386,7 +378,7 @@ impl DroplessArena {
386378
self.align(align);
387379

388380
let future_end = intrinsics::arith_offset(self.ptr.get(), bytes as isize);
389-
if (future_end as *mut u8) >= self.end.get() {
381+
if (future_end as *mut u8) > self.end.get() {
390382
self.grow(bytes);
391383
}
392384

0 commit comments

Comments
 (0)