Skip to content

Commit 7ff4515

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 ad4bc33 + 2391497 commit 7ff4515

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, *},
@@ -211,13 +211,13 @@ impl<T, A: AllocRef> RawVec<T, A> {
211211
}
212212
}
213213

214-
/// Ensures that the buffer contains at least enough space to hold
215-
/// `used_capacity + needed_extra_capacity` elements. If it doesn't already have
216-
/// enough capacity, will reallocate enough space plus comfortable slack
217-
/// space to get amortized `O(1)` behavior. Will limit this behavior
218-
/// if it would needlessly cause itself to panic.
214+
/// Ensures that the buffer contains at least enough space to hold `len +
215+
/// additional` elements. If it doesn't already have enough capacity, will
216+
/// reallocate enough space plus comfortable slack space to get amortized
217+
/// `O(1)` behavior. Will limit this behavior if it would needlessly cause
218+
/// itself to panic.
219219
///
220-
/// If `used_capacity` exceeds `self.capacity()`, this may fail to actually allocate
220+
/// If `len` exceeds `self.capacity()`, this may fail to actually allocate
221221
/// the requested space. This is not really unsafe, but the unsafe
222222
/// code *you* write that relies on the behavior of this function may break.
223223
///
@@ -263,64 +263,32 @@ impl<T, A: AllocRef> RawVec<T, A> {
263263
/// # vector.push_all(&[1, 3, 5, 7, 9]);
264264
/// # }
265265
/// ```
266-
pub fn reserve(&mut self, used_capacity: usize, needed_extra_capacity: usize) {
267-
match self.try_reserve(used_capacity, needed_extra_capacity) {
266+
pub fn reserve(&mut self, len: usize, additional: usize) {
267+
match self.try_reserve(len, additional) {
268268
Err(CapacityOverflow) => capacity_overflow(),
269269
Err(AllocError { layout, .. }) => handle_alloc_error(layout),
270270
Ok(()) => { /* yay */ }
271271
}
272272
}
273273

274274
/// The same as `reserve`, but returns on errors instead of panicking or aborting.
275-
pub fn try_reserve(
276-
&mut self,
277-
used_capacity: usize,
278-
needed_extra_capacity: usize,
279-
) -> Result<(), TryReserveError> {
280-
if self.needs_to_grow(used_capacity, needed_extra_capacity) {
281-
self.grow_amortized(used_capacity, needed_extra_capacity, MayMove)
275+
pub fn try_reserve(&mut self, len: usize, additional: usize) -> Result<(), TryReserveError> {
276+
if self.needs_to_grow(len, additional) {
277+
self.grow_amortized(len, additional)
282278
} else {
283279
Ok(())
284280
}
285281
}
286282

287-
/// Attempts to ensure that the buffer contains at least enough space to hold
288-
/// `used_capacity + needed_extra_capacity` elements. If it doesn't already have
289-
/// enough capacity, will reallocate in place enough space plus comfortable slack
290-
/// space to get amortized `O(1)` behavior. Will limit this behaviour
291-
/// if it would needlessly cause itself to panic.
283+
/// Ensures that the buffer contains at least enough space to hold `len +
284+
/// additional` elements. If it doesn't already, will reallocate the
285+
/// minimum possible amount of memory necessary. Generally this will be
286+
/// exactly the amount of memory necessary, but in principle the allocator
287+
/// is free to give back more than we asked for.
292288
///
293-
/// If `used_capacity` exceeds `self.capacity()`, this may fail to actually allocate
294-
/// the requested space. This is not really unsafe, but the unsafe
295-
/// code *you* write that relies on the behavior of this function may break.
296-
///
297-
/// Returns `true` if the reallocation attempt has succeeded.
298-
///
299-
/// # Panics
300-
///
301-
/// * Panics if the requested capacity exceeds `usize::MAX` bytes.
302-
/// * Panics on 32-bit platforms if the requested capacity exceeds
303-
/// `isize::MAX` bytes.
304-
pub fn reserve_in_place(&mut self, used_capacity: usize, needed_extra_capacity: usize) -> bool {
305-
// This is more readable than putting this in one line:
306-
// `!self.needs_to_grow(...) || self.grow(...).is_ok()`
307-
if self.needs_to_grow(used_capacity, needed_extra_capacity) {
308-
self.grow_amortized(used_capacity, needed_extra_capacity, InPlace).is_ok()
309-
} else {
310-
true
311-
}
312-
}
313-
314-
/// Ensures that the buffer contains at least enough space to hold
315-
/// `used_capacity + needed_extra_capacity` elements. If it doesn't already,
316-
/// will reallocate the minimum possible amount of memory necessary.
317-
/// Generally this will be exactly the amount of memory necessary,
318-
/// but in principle the allocator is free to give back more than what
319-
/// we asked for.
320-
///
321-
/// If `used_capacity` exceeds `self.capacity()`, this may fail to actually allocate
322-
/// the requested space. This is not really unsafe, but the unsafe
323-
/// code *you* write that relies on the behavior of this function may break.
289+
/// If `len` exceeds `self.capacity()`, this may fail to actually allocate
290+
/// the requested space. This is not really unsafe, but the unsafe code
291+
/// *you* write that relies on the behavior of this function may break.
324292
///
325293
/// # Panics
326294
///
@@ -331,8 +299,8 @@ impl<T, A: AllocRef> RawVec<T, A> {
331299
/// # Aborts
332300
///
333301
/// Aborts on OOM.
334-
pub fn reserve_exact(&mut self, used_capacity: usize, needed_extra_capacity: usize) {
335-
match self.try_reserve_exact(used_capacity, needed_extra_capacity) {
302+
pub fn reserve_exact(&mut self, len: usize, additional: usize) {
303+
match self.try_reserve_exact(len, additional) {
336304
Err(CapacityOverflow) => capacity_overflow(),
337305
Err(AllocError { layout, .. }) => handle_alloc_error(layout),
338306
Ok(()) => { /* yay */ }
@@ -342,14 +310,10 @@ impl<T, A: AllocRef> RawVec<T, A> {
342310
/// The same as `reserve_exact`, but returns on errors instead of panicking or aborting.
343311
pub fn try_reserve_exact(
344312
&mut self,
345-
used_capacity: usize,
346-
needed_extra_capacity: usize,
313+
len: usize,
314+
additional: usize,
347315
) -> Result<(), TryReserveError> {
348-
if self.needs_to_grow(used_capacity, needed_extra_capacity) {
349-
self.grow_exact(used_capacity, needed_extra_capacity)
350-
} else {
351-
Ok(())
352-
}
316+
if self.needs_to_grow(len, additional) { self.grow_exact(len, additional) } else { Ok(()) }
353317
}
354318

355319
/// Shrinks the allocation down to the specified amount. If the given amount
@@ -374,8 +338,8 @@ impl<T, A: AllocRef> RawVec<T, A> {
374338
impl<T, A: AllocRef> RawVec<T, A> {
375339
/// Returns if the buffer needs to grow to fulfill the needed extra capacity.
376340
/// Mainly used to make inlining reserve-calls possible without inlining `grow`.
377-
fn needs_to_grow(&self, used_capacity: usize, needed_extra_capacity: usize) -> bool {
378-
needed_extra_capacity > self.capacity().wrapping_sub(used_capacity)
341+
fn needs_to_grow(&self, len: usize, additional: usize) -> bool {
342+
additional > self.capacity().wrapping_sub(len)
379343
}
380344

381345
fn capacity_from_bytes(excess: usize) -> usize {
@@ -395,14 +359,9 @@ impl<T, A: AllocRef> RawVec<T, A> {
395359
// so that all of the code that depends on `T` is within it, while as much
396360
// of the code that doesn't depend on `T` as possible is in functions that
397361
// are non-generic over `T`.
398-
fn grow_amortized(
399-
&mut self,
400-
used_capacity: usize,
401-
needed_extra_capacity: usize,
402-
placement: ReallocPlacement,
403-
) -> Result<(), TryReserveError> {
362+
fn grow_amortized(&mut self, len: usize, additional: usize) -> Result<(), TryReserveError> {
404363
// This is ensured by the calling contexts.
405-
debug_assert!(needed_extra_capacity > 0);
364+
debug_assert!(additional > 0);
406365

407366
if mem::size_of::<T>() == 0 {
408367
// Since we return a capacity of `usize::MAX` when `elem_size` is
@@ -411,8 +370,7 @@ impl<T, A: AllocRef> RawVec<T, A> {
411370
}
412371

413372
// Nothing we can really do about these checks, sadly.
414-
let required_cap =
415-
used_capacity.checked_add(needed_extra_capacity).ok_or(CapacityOverflow)?;
373+
let required_cap = len.checked_add(additional).ok_or(CapacityOverflow)?;
416374

417375
// This guarantees exponential growth. The doubling cannot overflow
418376
// because `cap <= isize::MAX` and the type of `cap` is `usize`.
@@ -437,30 +395,26 @@ impl<T, A: AllocRef> RawVec<T, A> {
437395
let new_layout = Layout::array::<T>(cap);
438396

439397
// `finish_grow` is non-generic over `T`.
440-
let memory = finish_grow(new_layout, placement, self.current_memory(), &mut self.alloc)?;
398+
let memory = finish_grow(new_layout, self.current_memory(), &mut self.alloc)?;
441399
self.set_memory(memory);
442400
Ok(())
443401
}
444402

445403
// The constraints on this method are much the same as those on
446404
// `grow_amortized`, but this method is usually instantiated less often so
447405
// it's less critical.
448-
fn grow_exact(
449-
&mut self,
450-
used_capacity: usize,
451-
needed_extra_capacity: usize,
452-
) -> Result<(), TryReserveError> {
406+
fn grow_exact(&mut self, len: usize, additional: usize) -> Result<(), TryReserveError> {
453407
if mem::size_of::<T>() == 0 {
454408
// Since we return a capacity of `usize::MAX` when the type size is
455409
// 0, getting to here necessarily means the `RawVec` is overfull.
456410
return Err(CapacityOverflow);
457411
}
458412

459-
let cap = used_capacity.checked_add(needed_extra_capacity).ok_or(CapacityOverflow)?;
413+
let cap = len.checked_add(additional).ok_or(CapacityOverflow)?;
460414
let new_layout = Layout::array::<T>(cap);
461415

462416
// `finish_grow` is non-generic over `T`.
463-
let memory = finish_grow(new_layout, MayMove, self.current_memory(), &mut self.alloc)?;
417+
let memory = finish_grow(new_layout, self.current_memory(), &mut self.alloc)?;
464418
self.set_memory(memory);
465419
Ok(())
466420
}
@@ -494,7 +448,6 @@ impl<T, A: AllocRef> RawVec<T, A> {
494448
// much smaller than the number of `T` types.)
495449
fn finish_grow<A>(
496450
new_layout: Result<Layout, LayoutErr>,
497-
placement: ReallocPlacement,
498451
current_memory: Option<(NonNull<u8>, Layout)>,
499452
alloc: &mut A,
500453
) -> Result<MemoryBlock, TryReserveError>
@@ -508,12 +461,9 @@ where
508461

509462
let memory = if let Some((ptr, old_layout)) = current_memory {
510463
debug_assert_eq!(old_layout.align(), new_layout.align());
511-
unsafe { alloc.grow(ptr, old_layout, new_layout.size(), placement, Uninitialized) }
464+
unsafe { alloc.grow(ptr, old_layout, new_layout.size(), MayMove, Uninitialized) }
512465
} else {
513-
match placement {
514-
MayMove => alloc.alloc(new_layout, Uninitialized),
515-
InPlace => Err(AllocErr),
516-
}
466+
alloc.alloc(new_layout, Uninitialized)
517467
}
518468
.map_err(|_| AllocError { layout: new_layout, non_exhaustive: () })?;
519469

src/liballoc/vec.rs

+4-4
Original file line numberDiff line numberDiff line change
@@ -2965,12 +2965,12 @@ impl<T> Drain<'_, T> {
29652965
}
29662966

29672967
/// Makes room for inserting more elements before the tail.
2968-
unsafe fn move_tail(&mut self, extra_capacity: usize) {
2968+
unsafe fn move_tail(&mut self, additional: usize) {
29692969
let vec = self.vec.as_mut();
2970-
let used_capacity = self.tail_start + self.tail_len;
2971-
vec.buf.reserve(used_capacity, extra_capacity);
2970+
let len = self.tail_start + self.tail_len;
2971+
vec.buf.reserve(len, additional);
29722972

2973-
let new_tail_start = self.tail_start + extra_capacity;
2973+
let new_tail_start = self.tail_start + additional;
29742974
let src = vec.as_ptr().add(self.tail_start);
29752975
let dst = vec.as_mut_ptr().add(new_tail_start);
29762976
ptr::copy(src, dst, self.tail_len);

src/libarena/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)