alloc/raw_vec.rs
1#![unstable(feature = "raw_vec_internals", reason = "unstable const warnings", issue = "none")]
2
3use core::marker::PhantomData;
4use core::mem::{ManuallyDrop, MaybeUninit, SizedTypeProperties};
5use core::ptr::{self, NonNull, Unique};
6use core::{cmp, hint};
7
8#[cfg(not(no_global_oom_handling))]
9use crate::alloc::handle_alloc_error;
10use crate::alloc::{Allocator, Global, Layout};
11use crate::boxed::Box;
12use crate::collections::TryReserveError;
13use crate::collections::TryReserveErrorKind::*;
14
15#[cfg(test)]
16mod tests;
17
18// One central function responsible for reporting capacity overflows. This'll
19// ensure that the code generation related to these panics is minimal as there's
20// only one location which panics rather than a bunch throughout the module.
21#[cfg(not(no_global_oom_handling))]
22#[cfg_attr(not(feature = "panic_immediate_abort"), inline(never))]
23#[track_caller]
24fn capacity_overflow() -> ! {
25 panic!("capacity overflow");
26}
27
28enum AllocInit {
29 /// The contents of the new memory are uninitialized.
30 Uninitialized,
31 #[cfg(not(no_global_oom_handling))]
32 /// The new memory is guaranteed to be zeroed.
33 Zeroed,
34}
35
36type Cap = core::num::niche_types::UsizeNoHighBit;
37
38const ZERO_CAP: Cap = unsafe { Cap::new_unchecked(0) };
39
40/// `Cap(cap)`, except if `T` is a ZST then `Cap::ZERO`.
41///
42/// # Safety: cap must be <= `isize::MAX`.
43unsafe fn new_cap<T>(cap: usize) -> Cap {
44 if T::IS_ZST { ZERO_CAP } else { unsafe { Cap::new_unchecked(cap) } }
45}
46
47/// A low-level utility for more ergonomically allocating, reallocating, and deallocating
48/// a buffer of memory on the heap without having to worry about all the corner cases
49/// involved. This type is excellent for building your own data structures like Vec and VecDeque.
50/// In particular:
51///
52/// * Produces `Unique::dangling()` on zero-sized types.
53/// * Produces `Unique::dangling()` on zero-length allocations.
54/// * Avoids freeing `Unique::dangling()`.
55/// * Catches all overflows in capacity computations (promotes them to "capacity overflow" panics).
56/// * Guards against 32-bit systems allocating more than `isize::MAX` bytes.
57/// * Guards against overflowing your length.
58/// * Calls `handle_alloc_error` for fallible allocations.
59/// * Contains a `ptr::Unique` and thus endows the user with all related benefits.
60/// * Uses the excess returned from the allocator to use the largest available capacity.
61///
62/// This type does not in anyway inspect the memory that it manages. When dropped it *will*
63/// free its memory, but it *won't* try to drop its contents. It is up to the user of `RawVec`
64/// to handle the actual things *stored* inside of a `RawVec`.
65///
66/// Note that the excess of a zero-sized types is always infinite, so `capacity()` always returns
67/// `usize::MAX`. This means that you need to be careful when round-tripping this type with a
68/// `Box<[T]>`, since `capacity()` won't yield the length.
69#[allow(missing_debug_implementations)]
70pub(crate) struct RawVec<T, A: Allocator = Global> {
71 inner: RawVecInner<A>,
72 _marker: PhantomData<T>,
73}
74
75/// Like a `RawVec`, but only generic over the allocator, not the type.
76///
77/// As such, all the methods need the layout passed-in as a parameter.
78///
79/// Having this separation reduces the amount of code we need to monomorphize,
80/// as most operations don't need the actual type, just its layout.
81#[allow(missing_debug_implementations)]
82struct RawVecInner<A: Allocator = Global> {
83 ptr: Unique<u8>,
84 /// Never used for ZSTs; it's `capacity()`'s responsibility to return usize::MAX in that case.
85 ///
86 /// # Safety
87 ///
88 /// `cap` must be in the `0..=isize::MAX` range.
89 cap: Cap,
90 alloc: A,
91}
92
93impl<T> RawVec<T, Global> {
94 /// Creates the biggest possible `RawVec` (on the system heap)
95 /// without allocating. If `T` has positive size, then this makes a
96 /// `RawVec` with capacity `0`. If `T` is zero-sized, then it makes a
97 /// `RawVec` with capacity `usize::MAX`. Useful for implementing
98 /// delayed allocation.
99 #[must_use]
100 pub(crate) const fn new() -> Self {
101 Self::new_in(Global)
102 }
103
104 /// Creates a `RawVec` (on the system heap) with exactly the
105 /// capacity and alignment requirements for a `[T; capacity]`. This is
106 /// equivalent to calling `RawVec::new` when `capacity` is `0` or `T` is
107 /// zero-sized. Note that if `T` is zero-sized this means you will
108 /// *not* get a `RawVec` with the requested capacity.
109 ///
110 /// Non-fallible version of `try_with_capacity`
111 ///
112 /// # Panics
113 ///
114 /// Panics if the requested capacity exceeds `isize::MAX` bytes.
115 ///
116 /// # Aborts
117 ///
118 /// Aborts on OOM.
119 #[cfg(not(any(no_global_oom_handling, test)))]
120 #[must_use]
121 #[inline]
122 #[track_caller]
123 pub(crate) fn with_capacity(capacity: usize) -> Self {
124 Self { inner: RawVecInner::with_capacity(capacity, T::LAYOUT), _marker: PhantomData }
125 }
126
127 /// Like `with_capacity`, but guarantees the buffer is zeroed.
128 #[cfg(not(any(no_global_oom_handling, test)))]
129 #[must_use]
130 #[inline]
131 #[track_caller]
132 pub(crate) fn with_capacity_zeroed(capacity: usize) -> Self {
133 Self {
134 inner: RawVecInner::with_capacity_zeroed_in(capacity, Global, T::LAYOUT),
135 _marker: PhantomData,
136 }
137 }
138}
139
140impl RawVecInner<Global> {
141 #[cfg(not(any(no_global_oom_handling, test)))]
142 #[must_use]
143 #[inline]
144 #[track_caller]
145 fn with_capacity(capacity: usize, elem_layout: Layout) -> Self {
146 match Self::try_allocate_in(capacity, AllocInit::Uninitialized, Global, elem_layout) {
147 Ok(res) => res,
148 Err(err) => handle_error(err),
149 }
150 }
151}
152
153// Tiny Vecs are dumb. Skip to:
154// - 8 if the element size is 1, because any heap allocators is likely
155// to round up a request of less than 8 bytes to at least 8 bytes.
156// - 4 if elements are moderate-sized (<= 1 KiB).
157// - 1 otherwise, to avoid wasting too much space for very short Vecs.
158const fn min_non_zero_cap(size: usize) -> usize {
159 if size == 1 {
160 8
161 } else if size <= 1024 {
162 4
163 } else {
164 1
165 }
166}
167
168impl<T, A: Allocator> RawVec<T, A> {
169 #[cfg(not(no_global_oom_handling))]
170 pub(crate) const MIN_NON_ZERO_CAP: usize = min_non_zero_cap(size_of::<T>());
171
172 /// Like `new`, but parameterized over the choice of allocator for
173 /// the returned `RawVec`.
174 #[inline]
175 pub(crate) const fn new_in(alloc: A) -> Self {
176 Self { inner: RawVecInner::new_in(alloc, align_of::<T>()), _marker: PhantomData }
177 }
178
179 /// Like `with_capacity`, but parameterized over the choice of
180 /// allocator for the returned `RawVec`.
181 #[cfg(not(no_global_oom_handling))]
182 #[inline]
183 #[track_caller]
184 pub(crate) fn with_capacity_in(capacity: usize, alloc: A) -> Self {
185 Self {
186 inner: RawVecInner::with_capacity_in(capacity, alloc, T::LAYOUT),
187 _marker: PhantomData,
188 }
189 }
190
191 /// Like `try_with_capacity`, but parameterized over the choice of
192 /// allocator for the returned `RawVec`.
193 #[inline]
194 pub(crate) fn try_with_capacity_in(capacity: usize, alloc: A) -> Result<Self, TryReserveError> {
195 match RawVecInner::try_with_capacity_in(capacity, alloc, T::LAYOUT) {
196 Ok(inner) => Ok(Self { inner, _marker: PhantomData }),
197 Err(e) => Err(e),
198 }
199 }
200
201 /// Like `with_capacity_zeroed`, but parameterized over the choice
202 /// of allocator for the returned `RawVec`.
203 #[cfg(not(no_global_oom_handling))]
204 #[inline]
205 #[track_caller]
206 pub(crate) fn with_capacity_zeroed_in(capacity: usize, alloc: A) -> Self {
207 Self {
208 inner: RawVecInner::with_capacity_zeroed_in(capacity, alloc, T::LAYOUT),
209 _marker: PhantomData,
210 }
211 }
212
213 /// Converts the entire buffer into `Box<[MaybeUninit<T>]>` with the specified `len`.
214 ///
215 /// Note that this will correctly reconstitute any `cap` changes
216 /// that may have been performed. (See description of type for details.)
217 ///
218 /// # Safety
219 ///
220 /// * `len` must be greater than or equal to the most recently requested capacity, and
221 /// * `len` must be less than or equal to `self.capacity()`.
222 ///
223 /// Note, that the requested capacity and `self.capacity()` could differ, as
224 /// an allocator could overallocate and return a greater memory block than requested.
225 pub(crate) unsafe fn into_box(self, len: usize) -> Box<[MaybeUninit<T>], A> {
226 // Sanity-check one half of the safety requirement (we cannot check the other half).
227 debug_assert!(
228 len <= self.capacity(),
229 "`len` must be smaller than or equal to `self.capacity()`"
230 );
231
232 let me = ManuallyDrop::new(self);
233 unsafe {
234 let slice = ptr::slice_from_raw_parts_mut(me.ptr() as *mut MaybeUninit<T>, len);
235 Box::from_raw_in(slice, ptr::read(&me.inner.alloc))
236 }
237 }
238
239 /// Reconstitutes a `RawVec` from a pointer, capacity, and allocator.
240 ///
241 /// # Safety
242 ///
243 /// The `ptr` must be allocated (via the given allocator `alloc`), and with the given
244 /// `capacity`.
245 /// The `capacity` cannot exceed `isize::MAX` for sized types. (only a concern on 32-bit
246 /// systems). For ZSTs capacity is ignored.
247 /// If the `ptr` and `capacity` come from a `RawVec` created via `alloc`, then this is
248 /// guaranteed.
249 #[inline]
250 pub(crate) unsafe fn from_raw_parts_in(ptr: *mut T, capacity: usize, alloc: A) -> Self {
251 // SAFETY: Precondition passed to the caller
252 unsafe {
253 let ptr = ptr.cast();
254 let capacity = new_cap::<T>(capacity);
255 Self {
256 inner: RawVecInner::from_raw_parts_in(ptr, capacity, alloc),
257 _marker: PhantomData,
258 }
259 }
260 }
261
262 /// A convenience method for hoisting the non-null precondition out of [`RawVec::from_raw_parts_in`].
263 ///
264 /// # Safety
265 ///
266 /// See [`RawVec::from_raw_parts_in`].
267 #[inline]
268 pub(crate) unsafe fn from_nonnull_in(ptr: NonNull<T>, capacity: usize, alloc: A) -> Self {
269 // SAFETY: Precondition passed to the caller
270 unsafe {
271 let ptr = ptr.cast();
272 let capacity = new_cap::<T>(capacity);
273 Self { inner: RawVecInner::from_nonnull_in(ptr, capacity, alloc), _marker: PhantomData }
274 }
275 }
276
277 /// Gets a raw pointer to the start of the allocation. Note that this is
278 /// `Unique::dangling()` if `capacity == 0` or `T` is zero-sized. In the former case, you must
279 /// be careful.
280 #[inline]
281 pub(crate) const fn ptr(&self) -> *mut T {
282 self.inner.ptr()
283 }
284
285 #[inline]
286 pub(crate) fn non_null(&self) -> NonNull<T> {
287 self.inner.non_null()
288 }
289
290 /// Gets the capacity of the allocation.
291 ///
292 /// This will always be `usize::MAX` if `T` is zero-sized.
293 #[inline]
294 pub(crate) const fn capacity(&self) -> usize {
295 self.inner.capacity(size_of::<T>())
296 }
297
298 /// Returns a shared reference to the allocator backing this `RawVec`.
299 #[inline]
300 pub(crate) fn allocator(&self) -> &A {
301 self.inner.allocator()
302 }
303
304 /// Ensures that the buffer contains at least enough space to hold `len +
305 /// additional` elements. If it doesn't already have enough capacity, will
306 /// reallocate enough space plus comfortable slack space to get amortized
307 /// *O*(1) behavior. Will limit this behavior if it would needlessly cause
308 /// itself to panic.
309 ///
310 /// If `len` exceeds `self.capacity()`, this may fail to actually allocate
311 /// the requested space. This is not really unsafe, but the unsafe
312 /// code *you* write that relies on the behavior of this function may break.
313 ///
314 /// This is ideal for implementing a bulk-push operation like `extend`.
315 ///
316 /// # Panics
317 ///
318 /// Panics if the new capacity exceeds `isize::MAX` _bytes_.
319 ///
320 /// # Aborts
321 ///
322 /// Aborts on OOM.
323 #[cfg(not(no_global_oom_handling))]
324 #[inline]
325 #[track_caller]
326 pub(crate) fn reserve(&mut self, len: usize, additional: usize) {
327 self.inner.reserve(len, additional, T::LAYOUT)
328 }
329
330 /// A specialized version of `self.reserve(len, 1)` which requires the
331 /// caller to ensure `len == self.capacity()`.
332 #[cfg(not(no_global_oom_handling))]
333 #[inline(never)]
334 #[track_caller]
335 pub(crate) fn grow_one(&mut self) {
336 self.inner.grow_one(T::LAYOUT)
337 }
338
339 /// The same as `reserve`, but returns on errors instead of panicking or aborting.
340 pub(crate) fn try_reserve(
341 &mut self,
342 len: usize,
343 additional: usize,
344 ) -> Result<(), TryReserveError> {
345 self.inner.try_reserve(len, additional, T::LAYOUT)
346 }
347
348 /// Ensures that the buffer contains at least enough space to hold `len +
349 /// additional` elements. If it doesn't already, will reallocate the
350 /// minimum possible amount of memory necessary. Generally this will be
351 /// exactly the amount of memory necessary, but in principle the allocator
352 /// is free to give back more than we asked for.
353 ///
354 /// If `len` exceeds `self.capacity()`, this may fail to actually allocate
355 /// the requested space. This is not really unsafe, but the unsafe code
356 /// *you* write that relies on the behavior of this function may break.
357 ///
358 /// # Panics
359 ///
360 /// Panics if the new capacity exceeds `isize::MAX` _bytes_.
361 ///
362 /// # Aborts
363 ///
364 /// Aborts on OOM.
365 #[cfg(not(no_global_oom_handling))]
366 #[track_caller]
367 pub(crate) fn reserve_exact(&mut self, len: usize, additional: usize) {
368 self.inner.reserve_exact(len, additional, T::LAYOUT)
369 }
370
371 /// The same as `reserve_exact`, but returns on errors instead of panicking or aborting.
372 pub(crate) fn try_reserve_exact(
373 &mut self,
374 len: usize,
375 additional: usize,
376 ) -> Result<(), TryReserveError> {
377 self.inner.try_reserve_exact(len, additional, T::LAYOUT)
378 }
379
380 /// Shrinks the buffer down to the specified capacity. If the given amount
381 /// is 0, actually completely deallocates.
382 ///
383 /// # Panics
384 ///
385 /// Panics if the given amount is *larger* than the current capacity.
386 ///
387 /// # Aborts
388 ///
389 /// Aborts on OOM.
390 #[cfg(not(no_global_oom_handling))]
391 #[track_caller]
392 #[inline]
393 pub(crate) fn shrink_to_fit(&mut self, cap: usize) {
394 self.inner.shrink_to_fit(cap, T::LAYOUT)
395 }
396}
397
398unsafe impl<#[may_dangle] T, A: Allocator> Drop for RawVec<T, A> {
399 /// Frees the memory owned by the `RawVec` *without* trying to drop its contents.
400 fn drop(&mut self) {
401 // SAFETY: We are in a Drop impl, self.inner will not be used again.
402 unsafe { self.inner.deallocate(T::LAYOUT) }
403 }
404}
405
406impl<A: Allocator> RawVecInner<A> {
407 #[inline]
408 const fn new_in(alloc: A, align: usize) -> Self {
409 let ptr = unsafe { core::mem::transmute(align) };
410 // `cap: 0` means "unallocated". zero-sized types are ignored.
411 Self { ptr, cap: ZERO_CAP, alloc }
412 }
413
414 #[cfg(not(no_global_oom_handling))]
415 #[inline]
416 #[track_caller]
417 fn with_capacity_in(capacity: usize, alloc: A, elem_layout: Layout) -> Self {
418 match Self::try_allocate_in(capacity, AllocInit::Uninitialized, alloc, elem_layout) {
419 Ok(this) => {
420 unsafe {
421 // Make it more obvious that a subsequent Vec::reserve(capacity) will not allocate.
422 hint::assert_unchecked(!this.needs_to_grow(0, capacity, elem_layout));
423 }
424 this
425 }
426 Err(err) => handle_error(err),
427 }
428 }
429
430 #[inline]
431 fn try_with_capacity_in(
432 capacity: usize,
433 alloc: A,
434 elem_layout: Layout,
435 ) -> Result<Self, TryReserveError> {
436 Self::try_allocate_in(capacity, AllocInit::Uninitialized, alloc, elem_layout)
437 }
438
439 #[cfg(not(no_global_oom_handling))]
440 #[inline]
441 #[track_caller]
442 fn with_capacity_zeroed_in(capacity: usize, alloc: A, elem_layout: Layout) -> Self {
443 match Self::try_allocate_in(capacity, AllocInit::Zeroed, alloc, elem_layout) {
444 Ok(res) => res,
445 Err(err) => handle_error(err),
446 }
447 }
448
449 fn try_allocate_in(
450 capacity: usize,
451 init: AllocInit,
452 alloc: A,
453 elem_layout: Layout,
454 ) -> Result<Self, TryReserveError> {
455 // We avoid `unwrap_or_else` here because it bloats the amount of
456 // LLVM IR generated.
457 let layout = match layout_array(capacity, elem_layout) {
458 Ok(layout) => layout,
459 Err(_) => return Err(CapacityOverflow.into()),
460 };
461
462 // Don't allocate here because `Drop` will not deallocate when `capacity` is 0.
463 if layout.size() == 0 {
464 return Ok(Self::new_in(alloc, elem_layout.align()));
465 }
466
467 if let Err(err) = alloc_guard(layout.size()) {
468 return Err(err);
469 }
470
471 let result = match init {
472 AllocInit::Uninitialized => alloc.allocate(layout),
473 #[cfg(not(no_global_oom_handling))]
474 AllocInit::Zeroed => alloc.allocate_zeroed(layout),
475 };
476 let ptr = match result {
477 Ok(ptr) => ptr,
478 Err(_) => return Err(AllocError { layout, non_exhaustive: () }.into()),
479 };
480
481 // Allocators currently return a `NonNull<[u8]>` whose length
482 // matches the size requested. If that ever changes, the capacity
483 // here should change to `ptr.len() / mem::size_of::<T>()`.
484 Ok(Self {
485 ptr: Unique::from(ptr.cast()),
486 cap: unsafe { Cap::new_unchecked(capacity) },
487 alloc,
488 })
489 }
490
491 #[inline]
492 unsafe fn from_raw_parts_in(ptr: *mut u8, cap: Cap, alloc: A) -> Self {
493 Self { ptr: unsafe { Unique::new_unchecked(ptr) }, cap, alloc }
494 }
495
496 #[inline]
497 unsafe fn from_nonnull_in(ptr: NonNull<u8>, cap: Cap, alloc: A) -> Self {
498 Self { ptr: Unique::from(ptr), cap, alloc }
499 }
500
501 #[inline]
502 const fn ptr<T>(&self) -> *mut T {
503 self.non_null::<T>().as_ptr()
504 }
505
506 #[inline]
507 const fn non_null<T>(&self) -> NonNull<T> {
508 self.ptr.cast().as_non_null_ptr()
509 }
510
511 #[inline]
512 const fn capacity(&self, elem_size: usize) -> usize {
513 if elem_size == 0 { usize::MAX } else { self.cap.as_inner() }
514 }
515
516 #[inline]
517 fn allocator(&self) -> &A {
518 &self.alloc
519 }
520
521 #[inline]
522 fn current_memory(&self, elem_layout: Layout) -> Option<(NonNull<u8>, Layout)> {
523 if elem_layout.size() == 0 || self.cap.as_inner() == 0 {
524 None
525 } else {
526 // We could use Layout::array here which ensures the absence of isize and usize overflows
527 // and could hypothetically handle differences between stride and size, but this memory
528 // has already been allocated so we know it can't overflow and currently Rust does not
529 // support such types. So we can do better by skipping some checks and avoid an unwrap.
530 unsafe {
531 let alloc_size = elem_layout.size().unchecked_mul(self.cap.as_inner());
532 let layout = Layout::from_size_align_unchecked(alloc_size, elem_layout.align());
533 Some((self.ptr.into(), layout))
534 }
535 }
536 }
537
538 #[cfg(not(no_global_oom_handling))]
539 #[inline]
540 #[track_caller]
541 fn reserve(&mut self, len: usize, additional: usize, elem_layout: Layout) {
542 // Callers expect this function to be very cheap when there is already sufficient capacity.
543 // Therefore, we move all the resizing and error-handling logic from grow_amortized and
544 // handle_reserve behind a call, while making sure that this function is likely to be
545 // inlined as just a comparison and a call if the comparison fails.
546 #[cold]
547 fn do_reserve_and_handle<A: Allocator>(
548 slf: &mut RawVecInner<A>,
549 len: usize,
550 additional: usize,
551 elem_layout: Layout,
552 ) {
553 if let Err(err) = slf.grow_amortized(len, additional, elem_layout) {
554 handle_error(err);
555 }
556 }
557
558 if self.needs_to_grow(len, additional, elem_layout) {
559 do_reserve_and_handle(self, len, additional, elem_layout);
560 }
561 }
562
563 #[cfg(not(no_global_oom_handling))]
564 #[inline]
565 #[track_caller]
566 fn grow_one(&mut self, elem_layout: Layout) {
567 if let Err(err) = self.grow_amortized(self.cap.as_inner(), 1, elem_layout) {
568 handle_error(err);
569 }
570 }
571
572 fn try_reserve(
573 &mut self,
574 len: usize,
575 additional: usize,
576 elem_layout: Layout,
577 ) -> Result<(), TryReserveError> {
578 if self.needs_to_grow(len, additional, elem_layout) {
579 self.grow_amortized(len, additional, elem_layout)?;
580 }
581 unsafe {
582 // Inform the optimizer that the reservation has succeeded or wasn't needed
583 hint::assert_unchecked(!self.needs_to_grow(len, additional, elem_layout));
584 }
585 Ok(())
586 }
587
588 #[cfg(not(no_global_oom_handling))]
589 #[track_caller]
590 fn reserve_exact(&mut self, len: usize, additional: usize, elem_layout: Layout) {
591 if let Err(err) = self.try_reserve_exact(len, additional, elem_layout) {
592 handle_error(err);
593 }
594 }
595
596 fn try_reserve_exact(
597 &mut self,
598 len: usize,
599 additional: usize,
600 elem_layout: Layout,
601 ) -> Result<(), TryReserveError> {
602 if self.needs_to_grow(len, additional, elem_layout) {
603 self.grow_exact(len, additional, elem_layout)?;
604 }
605 unsafe {
606 // Inform the optimizer that the reservation has succeeded or wasn't needed
607 hint::assert_unchecked(!self.needs_to_grow(len, additional, elem_layout));
608 }
609 Ok(())
610 }
611
612 #[cfg(not(no_global_oom_handling))]
613 #[inline]
614 #[track_caller]
615 fn shrink_to_fit(&mut self, cap: usize, elem_layout: Layout) {
616 if let Err(err) = self.shrink(cap, elem_layout) {
617 handle_error(err);
618 }
619 }
620
621 #[inline]
622 fn needs_to_grow(&self, len: usize, additional: usize, elem_layout: Layout) -> bool {
623 additional > self.capacity(elem_layout.size()).wrapping_sub(len)
624 }
625
626 #[inline]
627 unsafe fn set_ptr_and_cap(&mut self, ptr: NonNull<[u8]>, cap: usize) {
628 // Allocators currently return a `NonNull<[u8]>` whose length matches
629 // the size requested. If that ever changes, the capacity here should
630 // change to `ptr.len() / mem::size_of::<T>()`.
631 self.ptr = Unique::from(ptr.cast());
632 self.cap = unsafe { Cap::new_unchecked(cap) };
633 }
634
635 fn grow_amortized(
636 &mut self,
637 len: usize,
638 additional: usize,
639 elem_layout: Layout,
640 ) -> Result<(), TryReserveError> {
641 // This is ensured by the calling contexts.
642 debug_assert!(additional > 0);
643
644 if elem_layout.size() == 0 {
645 // Since we return a capacity of `usize::MAX` when `elem_size` is
646 // 0, getting to here necessarily means the `RawVec` is overfull.
647 return Err(CapacityOverflow.into());
648 }
649
650 // Nothing we can really do about these checks, sadly.
651 let required_cap = len.checked_add(additional).ok_or(CapacityOverflow)?;
652
653 // This guarantees exponential growth. The doubling cannot overflow
654 // because `cap <= isize::MAX` and the type of `cap` is `usize`.
655 let cap = cmp::max(self.cap.as_inner() * 2, required_cap);
656 let cap = cmp::max(min_non_zero_cap(elem_layout.size()), cap);
657
658 let new_layout = layout_array(cap, elem_layout)?;
659
660 let ptr = finish_grow(new_layout, self.current_memory(elem_layout), &mut self.alloc)?;
661 // SAFETY: finish_grow would have resulted in a capacity overflow if we tried to allocate more than `isize::MAX` items
662
663 unsafe { self.set_ptr_and_cap(ptr, cap) };
664 Ok(())
665 }
666
667 fn grow_exact(
668 &mut self,
669 len: usize,
670 additional: usize,
671 elem_layout: Layout,
672 ) -> Result<(), TryReserveError> {
673 if elem_layout.size() == 0 {
674 // Since we return a capacity of `usize::MAX` when the type size is
675 // 0, getting to here necessarily means the `RawVec` is overfull.
676 return Err(CapacityOverflow.into());
677 }
678
679 let cap = len.checked_add(additional).ok_or(CapacityOverflow)?;
680 let new_layout = layout_array(cap, elem_layout)?;
681
682 let ptr = finish_grow(new_layout, self.current_memory(elem_layout), &mut self.alloc)?;
683 // SAFETY: finish_grow would have resulted in a capacity overflow if we tried to allocate more than `isize::MAX` items
684 unsafe {
685 self.set_ptr_and_cap(ptr, cap);
686 }
687 Ok(())
688 }
689
690 #[cfg(not(no_global_oom_handling))]
691 #[inline]
692 fn shrink(&mut self, cap: usize, elem_layout: Layout) -> Result<(), TryReserveError> {
693 assert!(cap <= self.capacity(elem_layout.size()), "Tried to shrink to a larger capacity");
694 // SAFETY: Just checked this isn't trying to grow
695 unsafe { self.shrink_unchecked(cap, elem_layout) }
696 }
697
698 /// `shrink`, but without the capacity check.
699 ///
700 /// This is split out so that `shrink` can inline the check, since it
701 /// optimizes out in things like `shrink_to_fit`, without needing to
702 /// also inline all this code, as doing that ends up failing the
703 /// `vec-shrink-panic` codegen test when `shrink_to_fit` ends up being too
704 /// big for LLVM to be willing to inline.
705 ///
706 /// # Safety
707 /// `cap <= self.capacity()`
708 #[cfg(not(no_global_oom_handling))]
709 unsafe fn shrink_unchecked(
710 &mut self,
711 cap: usize,
712 elem_layout: Layout,
713 ) -> Result<(), TryReserveError> {
714 let (ptr, layout) =
715 if let Some(mem) = self.current_memory(elem_layout) { mem } else { return Ok(()) };
716
717 // If shrinking to 0, deallocate the buffer. We don't reach this point
718 // for the T::IS_ZST case since current_memory() will have returned
719 // None.
720 if cap == 0 {
721 unsafe { self.alloc.deallocate(ptr, layout) };
722 self.ptr =
723 unsafe { Unique::new_unchecked(ptr::without_provenance_mut(elem_layout.align())) };
724 self.cap = ZERO_CAP;
725 } else {
726 let ptr = unsafe {
727 // Layout cannot overflow here because it would have
728 // overflowed earlier when capacity was larger.
729 let new_size = elem_layout.size().unchecked_mul(cap);
730 let new_layout = Layout::from_size_align_unchecked(new_size, layout.align());
731 self.alloc
732 .shrink(ptr, layout, new_layout)
733 .map_err(|_| AllocError { layout: new_layout, non_exhaustive: () })?
734 };
735 // SAFETY: if the allocation is valid, then the capacity is too
736 unsafe {
737 self.set_ptr_and_cap(ptr, cap);
738 }
739 }
740 Ok(())
741 }
742
743 /// # Safety
744 ///
745 /// This function deallocates the owned allocation, but does not update `ptr` or `cap` to
746 /// prevent double-free or use-after-free. Essentially, do not do anything with the caller
747 /// after this function returns.
748 /// Ideally this function would take `self` by move, but it cannot because it exists to be
749 /// called from a `Drop` impl.
750 unsafe fn deallocate(&mut self, elem_layout: Layout) {
751 if let Some((ptr, layout)) = self.current_memory(elem_layout) {
752 unsafe {
753 self.alloc.deallocate(ptr, layout);
754 }
755 }
756 }
757}
758
759// not marked inline(never) since we want optimizers to be able to observe the specifics of this
760// function, see tests/codegen/vec-reserve-extend.rs.
761#[cold]
762fn finish_grow<A>(
763 new_layout: Layout,
764 current_memory: Option<(NonNull<u8>, Layout)>,
765 alloc: &mut A,
766) -> Result<NonNull<[u8]>, TryReserveError>
767where
768 A: Allocator,
769{
770 alloc_guard(new_layout.size())?;
771
772 let memory = if let Some((ptr, old_layout)) = current_memory {
773 debug_assert_eq!(old_layout.align(), new_layout.align());
774 unsafe {
775 // The allocator checks for alignment equality
776 hint::assert_unchecked(old_layout.align() == new_layout.align());
777 alloc.grow(ptr, old_layout, new_layout)
778 }
779 } else {
780 alloc.allocate(new_layout)
781 };
782
783 memory.map_err(|_| AllocError { layout: new_layout, non_exhaustive: () }.into())
784}
785
786// Central function for reserve error handling.
787#[cfg(not(no_global_oom_handling))]
788#[cold]
789#[optimize(size)]
790#[track_caller]
791fn handle_error(e: TryReserveError) -> ! {
792 match e.kind() {
793 CapacityOverflow => capacity_overflow(),
794 AllocError { layout, .. } => handle_alloc_error(layout),
795 }
796}
797
798// We need to guarantee the following:
799// * We don't ever allocate `> isize::MAX` byte-size objects.
800// * We don't overflow `usize::MAX` and actually allocate too little.
801//
802// On 64-bit we just need to check for overflow since trying to allocate
803// `> isize::MAX` bytes will surely fail. On 32-bit and 16-bit we need to add
804// an extra guard for this in case we're running on a platform which can use
805// all 4GB in user-space, e.g., PAE or x32.
806#[inline]
807fn alloc_guard(alloc_size: usize) -> Result<(), TryReserveError> {
808 if usize::BITS < 64 && alloc_size > isize::MAX as usize {
809 Err(CapacityOverflow.into())
810 } else {
811 Ok(())
812 }
813}
814
815#[inline]
816fn layout_array(cap: usize, elem_layout: Layout) -> Result<Layout, TryReserveError> {
817 elem_layout.repeat(cap).map(|(layout, _pad)| layout).map_err(|_| CapacityOverflow.into())
818}