Skip to main content

alloc/raw_vec/
mod.rs

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