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