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 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 { 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 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 let slice = me.ptr().cast::<MaybeUninit<T>>().cast_slice(len);
249 // SAFETY: `slice` is a valid pointer for `len` `T`s, and the
250 // above `ManuallyDrop` ensures that the destructor of `me` which
251 // would free the allocation is never run. The caller upholds that
252 // `len` meets or exceeds the last requested capacity, ensuring that
253 // the layout generated when dropping the resulting `Box` fits the
254 // allocation the `RawVec` created.
255 //
256 // Moving the allocator out of `me.inner` is also sound since it is
257 // never accessed after this point.
258 unsafe { Box::from_raw_in(slice, ptr::read(&me.inner.alloc)) }
259 }
260
261 /// Reconstitutes a `RawVec` from a pointer, capacity, and allocator.
262 ///
263 /// # Safety
264 ///
265 /// The `ptr` must be allocated (via the given allocator `alloc`), and with the given
266 /// `capacity`.
267 /// The `capacity` cannot exceed `isize::MAX` for sized types. (only a concern on 32-bit
268 /// systems). For ZSTs capacity is ignored.
269 /// If the `ptr` and `capacity` come from a `RawVec` created via `alloc`, then this is
270 /// guaranteed.
271 #[inline]
272 pub(crate) const unsafe fn from_raw_parts_in(ptr: *mut T, capacity: usize, alloc: A) -> Self {
273 // SAFETY: Precondition passed to the caller
274 unsafe {
275 let ptr = ptr.cast();
276 let capacity = new_cap::<T>(capacity);
277 Self {
278 inner: RawVecInner::from_raw_parts_in(ptr, capacity, alloc),
279 _marker: PhantomData,
280 }
281 }
282 }
283
284 /// A convenience method for hoisting the non-null precondition out of [`RawVec::from_raw_parts_in`].
285 ///
286 /// # Safety
287 ///
288 /// See [`RawVec::from_raw_parts_in`].
289 #[inline]
290 #[rustc_const_unstable(feature = "const_heap", issue = "79597")]
291 pub(crate) const unsafe fn from_nonnull_in(ptr: NonNull<T>, capacity: usize, alloc: A) -> Self {
292 // SAFETY: Precondition passed to the caller
293 unsafe {
294 let ptr = ptr.cast();
295 let capacity = new_cap::<T>(capacity);
296 Self { inner: RawVecInner::from_nonnull_in(ptr, capacity, alloc), _marker: PhantomData }
297 }
298 }
299
300 /// Gets a raw pointer to the start of the allocation. Note that this is
301 /// `Unique::dangling()` if `capacity == 0` or `T` is zero-sized. In the former case, you must
302 /// be careful.
303 #[inline]
304 pub(crate) const fn ptr(&self) -> *mut T {
305 self.inner.ptr()
306 }
307
308 #[inline]
309 pub(crate) const fn non_null(&self) -> NonNull<T> {
310 self.inner.non_null()
311 }
312
313 /// Gets the capacity of the allocation.
314 ///
315 /// This will always be `usize::MAX` if `T` is zero-sized.
316 #[inline]
317 pub(crate) const fn capacity(&self) -> usize {
318 self.inner.capacity(size_of::<T>())
319 }
320
321 /// Returns a shared reference to the allocator backing this `RawVec`.
322 #[inline]
323 pub(crate) const fn allocator(&self) -> &A {
324 self.inner.allocator()
325 }
326
327 /// Ensures that the buffer contains at least enough space to hold `len +
328 /// additional` elements. If it doesn't already have enough capacity, will
329 /// reallocate enough space plus comfortable slack space to get amortized
330 /// *O*(1) behavior. Will limit this behavior if it would needlessly cause
331 /// itself to panic.
332 ///
333 /// If `len` exceeds `self.capacity()`, this may fail to actually allocate
334 /// the requested space. This is not really unsafe, but the unsafe
335 /// code *you* write that relies on the behavior of this function may break.
336 ///
337 /// This is ideal for implementing a bulk-push operation like `extend`.
338 ///
339 /// # Panics
340 ///
341 /// Panics if the new capacity exceeds `isize::MAX` _bytes_.
342 ///
343 /// # Aborts
344 ///
345 /// Aborts on OOM.
346 #[cfg(not(no_global_oom_handling))]
347 #[inline]
348 pub(crate) fn reserve(&mut self, len: usize, additional: usize) {
349 // SAFETY: All calls on self.inner pass T::LAYOUT as the elem_layout
350 unsafe { self.inner.reserve(len, additional, T::LAYOUT) }
351 }
352
353 /// The same as `reserve`, but returns on errors instead of panicking or aborting.
354 pub(crate) fn try_reserve(
355 &mut self,
356 len: usize,
357 additional: usize,
358 ) -> Result<(), TryReserveError> {
359 // SAFETY: All calls on self.inner pass T::LAYOUT as the elem_layout
360 unsafe { self.inner.try_reserve(len, additional, T::LAYOUT) }
361 }
362
363 /// Ensures that the buffer contains at least enough space to hold `len +
364 /// additional` elements. If it doesn't already, will reallocate the
365 /// minimum possible amount of memory necessary. Generally this will be
366 /// exactly the amount of memory necessary, but in principle the allocator
367 /// is free to give back more than we asked for.
368 ///
369 /// If `len` exceeds `self.capacity()`, this may fail to actually allocate
370 /// the requested space. This is not really unsafe, but the unsafe code
371 /// *you* write that relies on the behavior of this function may break.
372 ///
373 /// # Panics
374 ///
375 /// Panics if the new capacity exceeds `isize::MAX` _bytes_.
376 ///
377 /// # Aborts
378 ///
379 /// Aborts on OOM.
380 #[cfg(not(no_global_oom_handling))]
381 pub(crate) fn reserve_exact(&mut self, len: usize, additional: usize) {
382 // SAFETY: All calls on self.inner pass T::LAYOUT as the elem_layout
383 unsafe { self.inner.reserve_exact(len, additional, T::LAYOUT) }
384 }
385
386 /// The same as `reserve_exact`, but returns on errors instead of panicking or aborting.
387 pub(crate) fn try_reserve_exact(
388 &mut self,
389 len: usize,
390 additional: usize,
391 ) -> Result<(), TryReserveError> {
392 // SAFETY: All calls on self.inner pass T::LAYOUT as the elem_layout
393 unsafe { self.inner.try_reserve_exact(len, additional, T::LAYOUT) }
394 }
395
396 /// Shrinks the buffer down to the specified capacity. If the given amount
397 /// is 0, actually completely deallocates.
398 ///
399 /// # Panics
400 ///
401 /// Panics if the given amount is *larger* than the current capacity.
402 ///
403 /// # Aborts
404 ///
405 /// Aborts on OOM.
406 #[cfg(not(no_global_oom_handling))]
407 #[inline]
408 pub(crate) fn shrink_to_fit(&mut self, cap: usize) {
409 // SAFETY: All calls on self.inner pass T::LAYOUT as the elem_layout
410 unsafe { self.inner.shrink_to_fit(cap, T::LAYOUT) }
411 }
412
413 /// Shrinks the buffer down to the specified capacity. If the given amount
414 /// is 0, actually completely deallocates.
415 ///
416 /// # Errors
417 ///
418 /// This function returns an error if the allocator cannot shrink the allocation.
419 ///
420 /// # Panics
421 ///
422 /// Panics if the given amount is *larger* than the current capacity.
423 #[inline]
424 pub(crate) fn try_shrink_to_fit(&mut self, cap: usize) -> Result<(), TryReserveError> {
425 // SAFETY: Layout is valid for T.
426 unsafe { self.inner.try_shrink_to_fit(cap, T::LAYOUT) }
427 }
428}
429
430#[rustc_const_unstable(feature = "const_heap", issue = "79597")]
431const unsafe impl<#[may_dangle] T, A: [const] Allocator + [const] Destruct> Drop for RawVec<T, A> {
432 /// Frees the memory owned by the `RawVec` *without* trying to drop its contents.
433 fn drop(&mut self) {
434 // SAFETY: We are in a Drop impl, self.inner will not be used again.
435 unsafe { self.inner.deallocate(T::LAYOUT) }
436 }
437}
438
439#[rustc_const_unstable(feature = "const_heap", issue = "79597")]
440#[rustfmt::skip] // FIXME(fee1-dead): temporary measure before rustfmt is bumped
441const impl<A: [const] Allocator + [const] Destruct> RawVecInner<A> {
442 #[cfg(not(no_global_oom_handling))]
443 #[inline]
444 fn with_capacity_in(capacity: usize, alloc: A, elem_layout: Layout) -> Self {
445 match Self::try_allocate_in(capacity, AllocInit::Uninitialized, alloc, elem_layout) {
446 Ok(this) => {
447 // SAFETY: We already allocated at least `capacity`.
448 unsafe {
449 // Make it more obvious that a subsequent Vec::reserve(capacity) will not allocate.
450 hint::assert_unchecked(!this.needs_to_grow(0, capacity, elem_layout));
451 }
452 this
453 }
454 Err(err) => handle_error(err),
455 }
456 }
457
458 fn try_allocate_in(
459 capacity: usize,
460 init: AllocInit,
461 alloc: A,
462 elem_layout: Layout,
463 ) -> Result<Self, TryReserveError> {
464 // We avoid `unwrap_or_else` here because it bloats the amount of
465 // LLVM IR generated.
466 let layout = match layout_array(capacity, elem_layout) {
467 Ok(layout) => layout,
468 Err(_) => return Err(CapacityOverflow.into()),
469 };
470
471 // Don't allocate here because `Drop` will not deallocate when `capacity` is 0.
472 if layout.size() == 0 {
473 return Ok(Self::new_in(alloc, elem_layout.alignment()));
474 }
475
476 let result = match init {
477 AllocInit::Uninitialized => alloc.allocate(layout),
478 #[cfg(not(no_global_oom_handling))]
479 AllocInit::Zeroed => alloc.allocate_zeroed(layout),
480 };
481 let ptr = match result {
482 Ok(ptr) => ptr,
483 Err(_) => return Err(AllocError { layout, non_exhaustive: () }.into()),
484 };
485
486 // Allocators currently return a `NonNull<[u8]>` whose length
487 // matches the size requested. If that ever changes, the capacity
488 // here should change to `ptr.len() / size_of::<T>()`.
489 Ok(Self {
490 ptr: Unique::from(ptr.cast()),
491 // SAFETY: We return early if `T` is a ZST, and if `capacity` would
492 // overflow an isize layout creation would have returned early as well.
493 cap: unsafe { Cap::new_unchecked(capacity) },
494 alloc,
495 })
496 }
497
498 /// # Safety
499 /// - `elem_layout` must be valid for `self`, i.e. it must be the same `elem_layout` used to
500 /// initially construct `self`
501 /// - `elem_layout`'s size must be a multiple of its alignment
502 #[cfg(not(no_global_oom_handling))]
503 #[inline]
504 unsafe fn grow_one(&mut self, elem_layout: Layout) {
505 // SAFETY: Precondition passed to caller
506 if let Err(err) = unsafe { self.grow_amortized(self.cap.as_inner(), 1, elem_layout) } {
507 handle_error(err);
508 }
509 }
510
511 /// # Safety
512 /// - `elem_layout` must be valid for `self`, i.e. it must be the same `elem_layout` used to
513 /// initially construct `self`
514 /// - `elem_layout`'s size must be a multiple of its alignment
515 /// - The sum of `len` and `additional` must be greater than the current capacity
516 unsafe fn grow_amortized(
517 &mut self,
518 len: usize,
519 additional: usize,
520 elem_layout: Layout,
521 ) -> Result<(), TryReserveError> {
522 // This is ensured by the calling contexts.
523 debug_assert!(additional > 0);
524
525 if elem_layout.size() == 0 {
526 // Since we return a capacity of `usize::MAX` when `elem_size` is
527 // 0, getting to here necessarily means the `RawVec` is overfull.
528 return Err(CapacityOverflow.into());
529 }
530
531 // Nothing we can really do about these checks, sadly.
532 let required_cap = len.checked_add(additional).ok_or(CapacityOverflow)?;
533
534 // This guarantees exponential growth. The doubling cannot overflow
535 // because `cap <= isize::MAX` and the type of `cap` is `usize`.
536 let cap = cmp::max(self.cap.as_inner() * 2, required_cap);
537 let cap = cmp::max(min_non_zero_cap(elem_layout.size()), cap);
538
539 // SAFETY:
540 // - cap >= len + additional
541 // - other preconditions passed to caller
542 let ptr = unsafe { self.finish_grow(cap, elem_layout)? };
543
544 // SAFETY: `finish_grow` would have failed if `cap > isize::MAX`
545 unsafe { self.set_ptr_and_cap(ptr, cap) };
546 Ok(())
547 }
548
549 /// # Safety
550 /// - `elem_layout` must be valid for `self`, i.e. it must be the same `elem_layout` used to
551 /// initially construct `self`
552 /// - `elem_layout`'s size must be a multiple of its alignment
553 /// - `cap` must be greater than the current capacity
554 // not marked inline(never) since we want optimizers to be able to observe the specifics of this
555 // function, see tests/codegen-llvm/vec-reserve-extend.rs.
556 #[cold]
557 unsafe fn finish_grow(
558 &self,
559 cap: usize,
560 elem_layout: Layout,
561 ) -> Result<NonNull<[u8]>, TryReserveError> {
562 let new_layout = layout_array(cap, elem_layout)?;
563
564 // SAFETY: Upheld by caller.
565 let memory = if let Some((ptr, old_layout)) = unsafe { self.current_memory(elem_layout) } {
566 // FIXME(const-hack): switch to `debug_assert_eq`
567 debug_assert!(old_layout.align() == new_layout.align());
568 // SAFETY: Upheld by caller.
569 unsafe {
570 // The allocator checks for alignment equality
571 hint::assert_unchecked(old_layout.align() == new_layout.align());
572 self.alloc.grow(ptr, old_layout, new_layout)
573 }
574 } else {
575 self.alloc.allocate(new_layout)
576 };
577
578 memory.map_err(const |_| AllocError { layout: new_layout, non_exhaustive: () }.into())
579 }
580}
581
582impl<A: Allocator> RawVecInner<A> {
583 #[inline]
584 const fn new_in(alloc: A, align: Alignment) -> Self {
585 let ptr = Unique::from_non_null(NonNull::without_provenance(align.as_nonzero_usize()));
586 // `cap: 0` means "unallocated". zero-sized types are ignored.
587 Self { ptr, cap: ZERO_CAP, alloc }
588 }
589
590 #[inline]
591 fn try_with_capacity_in(
592 capacity: usize,
593 alloc: A,
594 elem_layout: Layout,
595 ) -> Result<Self, TryReserveError> {
596 Self::try_allocate_in(capacity, AllocInit::Uninitialized, alloc, elem_layout)
597 }
598
599 #[cfg(not(no_global_oom_handling))]
600 #[inline]
601 fn with_capacity_zeroed_in(capacity: usize, alloc: A, elem_layout: Layout) -> Self {
602 match Self::try_allocate_in(capacity, AllocInit::Zeroed, alloc, elem_layout) {
603 Ok(res) => res,
604 Err(err) => handle_error(err),
605 }
606 }
607
608 #[inline]
609 const unsafe fn from_raw_parts_in(ptr: *mut u8, cap: Cap, alloc: A) -> Self {
610 // SAFETY: Upheld by caller.
611 Self { ptr: unsafe { Unique::new_unchecked(ptr) }, cap, alloc }
612 }
613
614 #[inline]
615 #[rustc_const_unstable(feature = "const_heap", issue = "79597")]
616 const unsafe fn from_nonnull_in(ptr: NonNull<u8>, cap: Cap, alloc: A) -> Self {
617 Self { ptr: Unique::from(ptr), cap, alloc }
618 }
619
620 #[inline]
621 const fn ptr<T>(&self) -> *mut T {
622 self.non_null::<T>().as_ptr()
623 }
624
625 #[inline]
626 const fn non_null<T>(&self) -> NonNull<T> {
627 self.ptr.cast().as_non_null_ptr()
628 }
629
630 #[inline]
631 const fn capacity(&self, elem_size: usize) -> usize {
632 if elem_size == 0 { usize::MAX } else { self.cap.as_inner() }
633 }
634
635 #[inline]
636 const fn allocator(&self) -> &A {
637 &self.alloc
638 }
639
640 /// # Safety
641 /// - `elem_layout` must be valid for `self`, i.e. it must be the same `elem_layout` used to
642 /// initially construct `self`
643 /// - `elem_layout`'s size must be a multiple of its alignment
644 #[inline]
645 #[rustc_const_unstable(feature = "const_heap", issue = "79597")]
646 const unsafe fn current_memory(&self, elem_layout: Layout) -> Option<(NonNull<u8>, Layout)> {
647 if elem_layout.size() == 0 || self.cap.as_inner() == 0 {
648 None
649 } else {
650 // We could use Layout::array here which ensures the absence of isize and usize overflows
651 // and could hypothetically handle differences between stride and size, but this memory
652 // has already been allocated so we know it can't overflow and currently Rust does not
653 // support such types. So we can do better by skipping some checks and avoid an unwrap.
654 // SAFETY: Upheld by caller, unless the element size is 0 which is checked against.
655 unsafe {
656 let alloc_size = elem_layout.size().unchecked_mul(self.cap.as_inner());
657 let layout = Layout::from_size_align_unchecked(alloc_size, elem_layout.align());
658 Some((self.ptr.into(), layout))
659 }
660 }
661 }
662
663 /// # Safety
664 /// - `elem_layout` must be valid for `self`, i.e. it must be the same `elem_layout` used to
665 /// initially construct `self`
666 /// - `elem_layout`'s size must be a multiple of its alignment
667 #[cfg(not(no_global_oom_handling))]
668 #[inline]
669 unsafe fn reserve(&mut self, len: usize, additional: usize, elem_layout: Layout) {
670 // Callers expect this function to be very cheap when there is already sufficient capacity.
671 // Therefore, we move all the resizing and error-handling logic from grow_amortized and
672 // handle_reserve behind a call, while making sure that this function is likely to be
673 // inlined as just a comparison and a call if the comparison fails.
674 #[cold]
675 unsafe fn do_reserve_and_handle<A: Allocator>(
676 slf: &mut RawVecInner<A>,
677 len: usize,
678 additional: usize,
679 elem_layout: Layout,
680 ) {
681 // SAFETY: Precondition passed to caller
682 if let Err(err) = unsafe { slf.grow_amortized(len, additional, elem_layout) } {
683 handle_error(err);
684 }
685 }
686
687 if self.needs_to_grow(len, additional, elem_layout) {
688 // SAFETY: `needs_to_grow` ensures that `len + additional` is greater than
689 // the current capacity, with the other preconditions upheld by our caller.
690 unsafe {
691 do_reserve_and_handle(self, len, additional, elem_layout);
692 }
693 }
694 }
695
696 /// # Safety
697 /// - `elem_layout` must be valid for `self`, i.e. it must be the same `elem_layout` used to
698 /// initially construct `self`
699 /// - `elem_layout`'s size must be a multiple of its alignment
700 unsafe fn try_reserve(
701 &mut self,
702 len: usize,
703 additional: usize,
704 elem_layout: Layout,
705 ) -> Result<(), TryReserveError> {
706 if self.needs_to_grow(len, additional, elem_layout) {
707 // SAFETY: Precondition passed to caller
708 unsafe {
709 self.grow_amortized(len, additional, elem_layout)?;
710 }
711 }
712 // SAFETY: If we've already grown, we will not need to again immediately after.
713 unsafe {
714 // Inform the optimizer that the reservation has succeeded or wasn't needed
715 hint::assert_unchecked(!self.needs_to_grow(len, additional, elem_layout));
716 }
717 Ok(())
718 }
719
720 /// # Safety
721 /// - `elem_layout` must be valid for `self`, i.e. it must be the same `elem_layout` used to
722 /// initially construct `self`
723 /// - `elem_layout`'s size must be a multiple of its alignment
724 #[cfg(not(no_global_oom_handling))]
725 unsafe fn reserve_exact(&mut self, len: usize, additional: usize, elem_layout: Layout) {
726 // SAFETY: Precondition passed to caller
727 if let Err(err) = unsafe { self.try_reserve_exact(len, additional, elem_layout) } {
728 handle_error(err);
729 }
730 }
731
732 /// # Safety
733 /// - `elem_layout` must be valid for `self`, i.e. it must be the same `elem_layout` used to
734 /// initially construct `self`
735 /// - `elem_layout`'s size must be a multiple of its alignment
736 unsafe fn try_reserve_exact(
737 &mut self,
738 len: usize,
739 additional: usize,
740 elem_layout: Layout,
741 ) -> Result<(), TryReserveError> {
742 if self.needs_to_grow(len, additional, elem_layout) {
743 // SAFETY: Precondition passed to caller
744 unsafe {
745 self.grow_exact(len, additional, elem_layout)?;
746 }
747 }
748 // SAFETY: If we've already grown, we will not need to again immediately after.
749 unsafe {
750 // Inform the optimizer that the reservation has succeeded or wasn't needed
751 hint::assert_unchecked(!self.needs_to_grow(len, additional, elem_layout));
752 }
753 Ok(())
754 }
755
756 /// # Safety
757 /// - `elem_layout` must be valid for `self`, i.e. it must be the same `elem_layout` used to
758 /// initially construct `self`
759 /// - `elem_layout`'s size must be a multiple of its alignment
760 /// - `cap` must be less than or equal to `self.capacity(elem_layout.size())`
761 #[cfg(not(no_global_oom_handling))]
762 #[inline]
763 unsafe fn shrink_to_fit(&mut self, cap: usize, elem_layout: Layout) {
764 // SAFETY: Upheld by caller.
765 if let Err(err) = unsafe { self.shrink(cap, elem_layout) } {
766 handle_error(err);
767 }
768 }
769
770 /// # Safety
771 ///
772 /// - `elem_layout` must be valid for `self`, i.e. it must be the same `elem_layout` used to
773 /// initially construct `self`
774 /// - `elem_layout`'s size must be a multiple of its alignment
775 /// - `cap` must be less than or equal to `self.capacity(elem_layout.size())`
776 unsafe fn try_shrink_to_fit(
777 &mut self,
778 cap: usize,
779 elem_layout: Layout,
780 ) -> Result<(), TryReserveError> {
781 // SAFETY: Upheld by caller.
782 unsafe { self.shrink(cap, elem_layout) }
783 }
784
785 #[inline]
786 const fn needs_to_grow(&self, len: usize, additional: usize, elem_layout: Layout) -> bool {
787 additional > self.capacity(elem_layout.size()).wrapping_sub(len)
788 }
789
790 #[inline]
791 #[rustc_const_unstable(feature = "const_heap", issue = "79597")]
792 const unsafe fn set_ptr_and_cap(&mut self, ptr: NonNull<[u8]>, cap: usize) {
793 // Allocators currently return a `NonNull<[u8]>` whose length matches
794 // the size requested. If that ever changes, the capacity here should
795 // change to `ptr.len() / size_of::<T>()`.
796 self.ptr = Unique::from(ptr.cast());
797 // SAFETY: Upheld by caller.
798 self.cap = unsafe { Cap::new_unchecked(cap) };
799 }
800
801 /// # Safety
802 /// - `elem_layout` must be valid for `self`, i.e. it must be the same `elem_layout` used to
803 /// initially construct `self`
804 /// - `elem_layout`'s size must be a multiple of its alignment
805 /// - The sum of `len` and `additional` must be greater than the current capacity
806 unsafe fn grow_exact(
807 &mut self,
808 len: usize,
809 additional: usize,
810 elem_layout: Layout,
811 ) -> Result<(), TryReserveError> {
812 if elem_layout.size() == 0 {
813 // Since we return a capacity of `usize::MAX` when the type size is
814 // 0, getting to here necessarily means the `RawVec` is overfull.
815 return Err(CapacityOverflow.into());
816 }
817
818 let cap = len.checked_add(additional).ok_or(CapacityOverflow)?;
819
820 // SAFETY: preconditions passed to caller
821 let ptr = unsafe { self.finish_grow(cap, elem_layout)? };
822
823 // SAFETY: `finish_grow` would have failed if `cap > isize::MAX`
824 unsafe { self.set_ptr_and_cap(ptr, cap) };
825 Ok(())
826 }
827
828 /// # Safety
829 /// - `elem_layout` must be valid for `self`, i.e. it must be the same `elem_layout` used to
830 /// initially construct `self`
831 /// - `elem_layout`'s size must be a multiple of its alignment
832 /// - `cap` must be less than or equal to `self.capacity(elem_layout.size())`
833 #[inline]
834 unsafe fn shrink(&mut self, cap: usize, elem_layout: Layout) -> Result<(), TryReserveError> {
835 assert!(cap <= self.capacity(elem_layout.size()), "Tried to shrink to a larger capacity");
836 // SAFETY: Just checked this isn't trying to grow
837 unsafe { self.shrink_unchecked(cap, elem_layout) }
838 }
839
840 /// `shrink`, but without the capacity check.
841 ///
842 /// This is split out so that `shrink` can inline the check, since it
843 /// optimizes out in things like `shrink_to_fit`, without needing to
844 /// also inline all this code, as doing that ends up failing the
845 /// `vec-shrink-panic` codegen test when `shrink_to_fit` ends up being too
846 /// big for LLVM to be willing to inline.
847 ///
848 /// # Safety
849 /// - `cap <= self.capacity()`
850 /// - `elem_layout` must be valid for `self`.
851 unsafe fn shrink_unchecked(
852 &mut self,
853 cap: usize,
854 elem_layout: Layout,
855 ) -> Result<(), TryReserveError> {
856 // SAFETY: Precondition passed to caller
857 let Some((ptr, layout)) = (unsafe { self.current_memory(elem_layout) }) else {
858 return Ok(());
859 };
860
861 // If shrinking to 0, deallocate the buffer. We don't reach this point
862 // for the T::IS_ZST case since current_memory() will have returned
863 // None.
864 if cap == 0 {
865 // SAFETY: T isn't a ZST if we're here and `ptr` is our pointer that `current_memory`
866 // ensures was allocated with `layout`.
867 unsafe { self.alloc.deallocate(ptr, layout) };
868 self.ptr =
869 // SAFETY: Alignment is guaranteed to be nonzero.
870 unsafe { Unique::new_unchecked(ptr::without_provenance_mut(elem_layout.align())) };
871 self.cap = ZERO_CAP;
872 } else {
873 // SAFETY: `cap` is less than the previous capacity, which must have fit in an
874 // isize already for the non-ZST case. `shrink` is also sound to call since
875 // `current_memory` ensures `ptr` and `layout` are correct for the old allocation,
876 // while `new_layout` is computed with a smaller size than the old one per the
877 // requirement we instate on our callers.
878 let ptr = unsafe {
879 let new_size = elem_layout.size().unchecked_mul(cap);
880 let new_layout = Layout::from_size_align_unchecked(new_size, layout.align());
881 self.alloc
882 .shrink(ptr, layout, new_layout)
883 .map_err(|_| AllocError { layout: new_layout, non_exhaustive: () })?
884 };
885 // SAFETY: if the allocation is valid, then the capacity is too
886 unsafe {
887 self.set_ptr_and_cap(ptr, cap);
888 }
889 }
890 Ok(())
891 }
892}
893
894#[rustc_const_unstable(feature = "const_heap", issue = "79597")]
895const impl<A: [const] Allocator> RawVecInner<A> {
896 /// # Safety
897 ///
898 /// This function deallocates the owned allocation, but does not update `ptr` or `cap` to
899 /// prevent double-free or use-after-free. Essentially, do not do anything with the caller
900 /// after this function returns.
901 /// Ideally this function would take `self` by move, but it cannot because it exists to be
902 /// called from a `Drop` impl.
903 unsafe fn deallocate(&mut self, elem_layout: Layout) {
904 // SAFETY: Caller ensures `elem_layout` is correct for `self`.
905 if let Some((ptr, layout)) = unsafe { self.current_memory(elem_layout) } {
906 // SAFETY: `current_memory` gives us a pointer with provenance for our allocation
907 // and a matching layout. Caller ensures we're not accessed again after deallocating.
908 unsafe {
909 self.alloc.deallocate(ptr, layout);
910 }
911 }
912 }
913}
914
915// Central function for reserve error handling.
916#[cfg(not(no_global_oom_handling))]
917#[cold]
918#[optimize(size)]
919#[rustc_const_unstable(feature = "const_heap", issue = "79597")]
920const fn handle_error(e: TryReserveError) -> ! {
921 match e.kind() {
922 CapacityOverflow => capacity_overflow(),
923 AllocError { layout, .. } => handle_alloc_error(layout),
924 }
925}
926
927#[inline]
928#[rustc_const_unstable(feature = "const_heap", issue = "79597")]
929const fn layout_array(cap: usize, elem_layout: Layout) -> Result<Layout, TryReserveError> {
930 // This is only used with `elem_layout`s which are those of real rust types,
931 // which lets us use the much-simpler `repeat_packed`.
932 debug_assert!(elem_layout.size() == elem_layout.pad_to_align().size());
933
934 elem_layout.repeat_packed(cap).map_err(const |_| CapacityOverflow.into())
935}