1#![unstable(feature = "raw_vec_internals", reason = "unstable const warnings", issue = "none")]
2
3use core::alloc::LayoutError;
4use core::cmp;
5use core::hint;
6use core::mem::{self, ManuallyDrop, MaybeUninit, SizedTypeProperties};
7use core::ptr::{self, NonNull, Unique};
8use core::slice;
9
10#[cfg(not(no_global_oom_handling))]
11use crate::alloc::handle_alloc_error;
12use crate::alloc::{Allocator, Global, Layout};
13use crate::boxed::Box;
14use crate::collections::TryReserveError;
15use crate::collections::TryReserveErrorKind::*;
16
17#[cfg(test)]
18mod tests;
19
20#[cfg(not(no_global_oom_handling))]
21enum AllocInit {
22 /// The contents of the new memory are uninitialized.
23 Uninitialized,
24 /// The new memory is guaranteed to be zeroed.
25 Zeroed,
26}
27
28#[repr(transparent)]
29#[cfg_attr(target_pointer_width = "16", rustc_layout_scalar_valid_range_end(0x7fff))]
30#[cfg_attr(target_pointer_width = "32", rustc_layout_scalar_valid_range_end(0x7fff_ffff))]
31#[cfg_attr(target_pointer_width = "64", rustc_layout_scalar_valid_range_end(0x7fff_ffff_ffff_ffff))]
32struct Cap(usize);
33
34impl Cap {
35 const ZERO: Cap = unsafe { Cap(0) };
36}
37
38/// A low-level utility for more ergonomically allocating, reallocating, and deallocating
39/// a buffer of memory on the heap without having to worry about all the corner cases
40/// involved. This type is excellent for building your own data structures like Vec and VecDeque.
41/// In particular:
42///
43/// * Produces `Unique::dangling()` on zero-sized types.
44/// * Produces `Unique::dangling()` on zero-length allocations.
45/// * Avoids freeing `Unique::dangling()`.
46/// * Catches all overflows in capacity computations (promotes them to "capacity overflow" panics).
47/// * Guards against 32-bit systems allocating more than isize::MAX bytes.
48/// * Guards against overflowing your length.
49/// * Calls `handle_alloc_error` for fallible allocations.
50/// * Contains a `ptr::Unique` and thus endows the user with all related benefits.
51/// * Uses the excess returned from the allocator to use the largest available capacity.
52///
53/// This type does not in anyway inspect the memory that it manages. When dropped it *will*
54/// free its memory, but it *won't* try to drop its contents. It is up to the user of `RawVec`
55/// to handle the actual things *stored* inside of a `RawVec`.
56///
57/// Note that the excess of a zero-sized types is always infinite, so `capacity()` always returns
58/// `usize::MAX`. This means that you need to be careful when round-tripping this type with a
59/// `Box<[T]>`, since `capacity()` won't yield the length.
60#[allow(missing_debug_implementations)]
61pub(crate) struct RawVec<T, A: Allocator = Global> {
62 ptr: Unique<T>,
63 /// Never used for ZSTs; it's `capacity()`'s responsibility to return usize::MAX in that case.
64 ///
65 /// # Safety
66 ///
67 /// `cap` must be in the `0..=isize::MAX` range.
68 cap: Cap,
69 alloc: A,
70}
71
72impl<T> RawVec<T, Global> {
73 /// HACK(Centril): This exists because stable `const fn` can only call stable `const fn`, so
74 /// they cannot call `Self::new()`.
75 ///
76 /// If you change `RawVec<T>::new` or dependencies, please take care to not introduce anything
77 /// that would truly const-call something unstable.
78 pub const NEW: Self = Self::new();
79
80 /// Creates the biggest possible `RawVec` (on the system heap)
81 /// without allocating. If `T` has positive size, then this makes a
82 /// `RawVec` with capacity `0`. If `T` is zero-sized, then it makes a
83 /// `RawVec` with capacity `usize::MAX`. Useful for implementing
84 /// delayed allocation.
85 #[must_use]
86 pub const fn new() -> Self {
87 Self::new_in(Global)
88 }
89
90 /// Creates a `RawVec` (on the system heap) with exactly the
91 /// capacity and alignment requirements for a `[T; capacity]`. This is
92 /// equivalent to calling `RawVec::new` when `capacity` is `0` or `T` is
93 /// zero-sized. Note that if `T` is zero-sized this means you will
94 /// *not* get a `RawVec` with the requested capacity.
95 ///
96 /// # Panics
97 ///
98 /// Panics if the requested capacity exceeds `isize::MAX` bytes.
99 ///
100 /// # Aborts
101 ///
102 /// Aborts on OOM.
103 #[cfg(not(any(no_global_oom_handling, test)))]
104 #[must_use]
105 #[inline]
106 pub fn with_capacity(capacity: usize) -> Self {
107 Self::with_capacity_in(capacity, Global)
108 }
109
110 /// Like `with_capacity`, but guarantees the buffer is zeroed.
111 #[cfg(not(any(no_global_oom_handling, test)))]
112 #[must_use]
113 #[inline]
114 pub fn with_capacity_zeroed(capacity: usize) -> Self {
115 Self::with_capacity_zeroed_in(capacity, Global)
116 }
117}
118
119impl<T, A: Allocator> RawVec<T, A> {
120 // Tiny Vecs are dumb. Skip to:
121 // - 8 if the element size is 1, because any heap allocators is likely
122 // to round up a request of less than 8 bytes to at least 8 bytes.
123 // - 4 if elements are moderate-sized (<= 1 KiB).
124 // - 1 otherwise, to avoid wasting too much space for very short Vecs.
125 pub(crate) const MIN_NON_ZERO_CAP: usize = if mem::size_of::<T>() == 1 {
126 8
127 } else if mem::size_of::<T>() <= 1024 {
128 4
129 } else {
130 1
131 };
132
133 /// Like `new`, but parameterized over the choice of allocator for
134 /// the returned `RawVec`.
135 pub const fn new_in(alloc: A) -> Self {
136 // `cap: 0` means "unallocated". zero-sized types are ignored.
137 Self { ptr: Unique::dangling(), cap: Cap::ZERO, alloc }
138 }
139
140 /// Like `with_capacity`, but parameterized over the choice of
141 /// allocator for the returned `RawVec`.
142 #[cfg(not(no_global_oom_handling))]
143 #[inline]
144 pub fn with_capacity_in(capacity: usize, alloc: A) -> Self {
145 Self::allocate_in(capacity, AllocInit::Uninitialized, alloc)
146 }
147
148 /// Like `with_capacity_zeroed`, but parameterized over the choice
149 /// of allocator for the returned `RawVec`.
150 #[cfg(not(no_global_oom_handling))]
151 #[inline]
152 pub fn with_capacity_zeroed_in(capacity: usize, alloc: A) -> Self {
153 Self::allocate_in(capacity, AllocInit::Zeroed, alloc)
154 }
155
156 /// Converts the entire buffer into `Box<[MaybeUninit<T>]>` with the specified `len`.
157 ///
158 /// Note that this will correctly reconstitute any `cap` changes
159 /// that may have been performed. (See description of type for details.)
160 ///
161 /// # Safety
162 ///
163 /// * `len` must be greater than or equal to the most recently requested capacity, and
164 /// * `len` must be less than or equal to `self.capacity()`.
165 ///
166 /// Note, that the requested capacity and `self.capacity()` could differ, as
167 /// an allocator could overallocate and return a greater memory block than requested.
168 pub unsafe fn into_box(self, len: usize) -> Box<[MaybeUninit<T>], A> {
169 // Sanity-check one half of the safety requirement (we cannot check the other half).
170 debug_assert!(
171 len <= self.capacity(),
172 "`len` must be smaller than or equal to `self.capacity()`"
173 );
174
175 let me = ManuallyDrop::new(self);
176 unsafe {
177 let slice = slice::from_raw_parts_mut(me.ptr() as *mut MaybeUninit<T>, len);
178 Box::from_raw_in(slice, ptr::read(&me.alloc))
179 }
180 }
181
182 #[cfg(not(no_global_oom_handling))]
183 fn allocate_in(capacity: usize, init: AllocInit, alloc: A) -> Self {
184 // Don't allocate here because `Drop` will not deallocate when `capacity` is 0.
185 if T::IS_ZST || capacity == 0 {
186 Self::new_in(alloc)
187 } else {
188 // We avoid `unwrap_or_else` here because it bloats the amount of
189 // LLVM IR generated.
190 let layout = match Layout::array::<T>(capacity) {
191 Ok(layout) => layout,
192 Err(_) => capacity_overflow(),
193 };
194 match alloc_guard(layout.size()) {
195 Ok(_) => {}
196 Err(_) => capacity_overflow(),
197 }
198 let result = match init {
199 AllocInit::Uninitialized => alloc.allocate(layout),
200 AllocInit::Zeroed => alloc.allocate_zeroed(layout),
201 };
202 let ptr = match result {
203 Ok(ptr) => ptr,
204 Err(_) => handle_alloc_error(layout),
205 };
206
207 // Allocators currently return a `NonNull<[u8]>` whose length
208 // matches the size requested. If that ever changes, the capacity
209 // here should change to `ptr.len() / mem::size_of::<T>()`.
210 Self {
211 ptr: unsafe { Unique::new_unchecked(ptr.cast().as_ptr()) },
212 cap: unsafe { Cap(capacity) },
213 alloc,
214 }
215 }
216 }
217
218 /// Reconstitutes a `RawVec` from a pointer, capacity, and allocator.
219 ///
220 /// # Safety
221 ///
222 /// The `ptr` must be allocated (via the given allocator `alloc`), and with the given
223 /// `capacity`.
224 /// The `capacity` cannot exceed `isize::MAX` for sized types. (only a concern on 32-bit
225 /// systems). For ZSTs capacity is ignored.
226 /// If the `ptr` and `capacity` come from a `RawVec` created via `alloc`, then this is
227 /// guaranteed.
228 #[inline]
229 pub unsafe fn from_raw_parts_in(ptr: *mut T, capacity: usize, alloc: A) -> Self {
230 let cap = if T::IS_ZST { Cap::ZERO } else { unsafe { Cap(capacity) } };
231 Self { ptr: unsafe { Unique::new_unchecked(ptr) }, cap, alloc }
232 }
233
234 /// Gets a raw pointer to the start of the allocation. Note that this is
235 /// `Unique::dangling()` if `capacity == 0` or `T` is zero-sized. In the former case, you must
236 /// be careful.
237 #[inline]
238 pub fn ptr(&self) -> *mut T {
239 self.ptr.as_ptr()
240 }
241
242 /// Gets the capacity of the allocation.
243 ///
244 /// This will always be `usize::MAX` if `T` is zero-sized.
245 #[inline(always)]
246 pub fn capacity(&self) -> usize {
247 if T::IS_ZST { usize::MAX } else { self.cap.0 }
248 }
249
250 /// Returns a shared reference to the allocator backing this `RawVec`.
251 pub fn allocator(&self) -> &A {
252 &self.alloc
253 }
254
255 fn current_memory(&self) -> Option<(NonNull<u8>, Layout)> {
256 if T::IS_ZST || self.cap.0 == 0 {
257 None
258 } else {
259 // We could use Layout::array here which ensures the absence of isize and usize overflows
260 // and could hypothetically handle differences between stride and size, but this memory
261 // has already been allocated so we know it can't overflow and currently rust does not
262 // support such types. So we can do better by skipping some checks and avoid an unwrap.
263 let _: () = const { assert!(mem::size_of::<T>() % mem::align_of::<T>() == 0) };
264 unsafe {
265 let align = mem::align_of::<T>();
266 let size = mem::size_of::<T>().unchecked_mul(self.cap.0);
267 let layout = Layout::from_size_align_unchecked(size, align);
268 Some((self.ptr.cast().into(), layout))
269 }
270 }
271 }
272
273 /// Ensures that the buffer contains at least enough space to hold `len +
274 /// additional` elements. If it doesn't already have enough capacity, will
275 /// reallocate enough space plus comfortable slack space to get amortized
276 /// *O*(1) behavior. Will limit this behavior if it would needlessly cause
277 /// itself to panic.
278 ///
279 /// If `len` exceeds `self.capacity()`, this may fail to actually allocate
280 /// the requested space. This is not really unsafe, but the unsafe
281 /// code *you* write that relies on the behavior of this function may break.
282 ///
283 /// This is ideal for implementing a bulk-push operation like `extend`.
284 ///
285 /// # Panics
286 ///
287 /// Panics if the new capacity exceeds `isize::MAX` _bytes_.
288 ///
289 /// # Aborts
290 ///
291 /// Aborts on OOM.
292 #[cfg(not(no_global_oom_handling))]
293 #[inline]
294 pub fn reserve(&mut self, len: usize, additional: usize) {
295 // Callers expect this function to be very cheap when there is already sufficient capacity.
296 // Therefore, we move all the resizing and error-handling logic from grow_amortized and
297 // handle_reserve behind a call, while making sure that this function is likely to be
298 // inlined as just a comparison and a call if the comparison fails.
299 #[cold]
300 fn do_reserve_and_handle<T, A: Allocator>(
301 slf: &mut RawVec<T, A>,
302 len: usize,
303 additional: usize,
304 ) {
305 handle_reserve(slf.grow_amortized(len, additional));
306 }
307
308 if self.needs_to_grow(len, additional) {
309 do_reserve_and_handle(self, len, additional);
310 }
311 }
312
313 /// A specialized version of `reserve()` used only by the hot and
314 /// oft-instantiated `Vec::push()`, which does its own capacity check.
315 #[cfg(not(no_global_oom_handling))]
316 #[inline(never)]
317 pub fn reserve_for_push(&mut self, len: usize) {
318 handle_reserve(self.grow_amortized(len, 1));
319 }
320
321 /// The same as `reserve`, but returns on errors instead of panicking or aborting.
322 pub fn try_reserve(&mut self, len: usize, additional: usize) -> Result<(), TryReserveError> {
323 if self.needs_to_grow(len, additional) {
324 self.grow_amortized(len, additional)?;
325 }
326 unsafe {
327 // Inform the optimizer that the reservation has succeeded or wasn't needed
328 hint::assert_unchecked(!self.needs_to_grow(len, additional));
329 }
330 Ok(())
331 }
332
333 /// Ensures that the buffer contains at least enough space to hold `len +
334 /// additional` elements. If it doesn't already, will reallocate the
335 /// minimum possible amount of memory necessary. Generally this will be
336 /// exactly the amount of memory necessary, but in principle the allocator
337 /// is free to give back more than we asked for.
338 ///
339 /// If `len` exceeds `self.capacity()`, this may fail to actually allocate
340 /// the requested space. This is not really unsafe, but the unsafe code
341 /// *you* write that relies on the behavior of this function may break.
342 ///
343 /// # Panics
344 ///
345 /// Panics if the new capacity exceeds `isize::MAX` _bytes_.
346 ///
347 /// # Aborts
348 ///
349 /// Aborts on OOM.
350 #[cfg(not(no_global_oom_handling))]
351 pub fn reserve_exact(&mut self, len: usize, additional: usize) {
352 handle_reserve(self.try_reserve_exact(len, additional));
353 }
354
355 /// The same as `reserve_exact`, but returns on errors instead of panicking or aborting.
356 pub fn try_reserve_exact(
357 &mut self,
358 len: usize,
359 additional: usize,
360 ) -> Result<(), TryReserveError> {
361 if self.needs_to_grow(len, additional) {
362 self.grow_exact(len, additional)?;
363 }
364 unsafe {
365 // Inform the optimizer that the reservation has succeeded or wasn't needed
366 hint::assert_unchecked(!self.needs_to_grow(len, additional));
367 }
368 Ok(())
369 }
370
371 /// Shrinks the buffer down to the specified capacity. If the given amount
372 /// is 0, actually completely deallocates.
373 ///
374 /// # Panics
375 ///
376 /// Panics if the given amount is *larger* than the current capacity.
377 ///
378 /// # Aborts
379 ///
380 /// Aborts on OOM.
381 #[cfg(not(no_global_oom_handling))]
382 pub fn shrink_to_fit(&mut self, cap: usize) {
383 handle_reserve(self.shrink(cap));
384 }
385}
386
387impl<T, A: Allocator> RawVec<T, A> {
388 /// Returns if the buffer needs to grow to fulfill the needed extra capacity.
389 /// Mainly used to make inlining reserve-calls possible without inlining `grow`.
390 fn needs_to_grow(&self, len: usize, additional: usize) -> bool {
391 additional > self.capacity().wrapping_sub(len)
392 }
393
394 /// # Safety:
395 ///
396 /// `cap` must not exceed `isize::MAX`.
397 unsafe fn set_ptr_and_cap(&mut self, ptr: NonNull<[u8]>, cap: usize) {
398 // Allocators currently return a `NonNull<[u8]>` whose length matches
399 // the size requested. If that ever changes, the capacity here should
400 // change to `ptr.len() / mem::size_of::<T>()`.
401 self.ptr = unsafe { Unique::new_unchecked(ptr.cast().as_ptr()) };
402 self.cap = unsafe { Cap(cap) };
403 }
404
405 // This method is usually instantiated many times. So we want it to be as
406 // small as possible, to improve compile times. But we also want as much of
407 // its contents to be statically computable as possible, to make the
408 // generated code run faster. Therefore, this method is carefully written
409 // so that all of the code that depends on `T` is within it, while as much
410 // of the code that doesn't depend on `T` as possible is in functions that
411 // are non-generic over `T`.
412 fn grow_amortized(&mut self, len: usize, additional: usize) -> Result<(), TryReserveError> {
413 // This is ensured by the calling contexts.
414 debug_assert!(additional > 0);
415
416 if T::IS_ZST {
417 // Since we return a capacity of `usize::MAX` when `elem_size` is
418 // 0, getting to here necessarily means the `RawVec` is overfull.
419 return Err(CapacityOverflow.into());
420 }
421
422 // Nothing we can really do about these checks, sadly.
423 let required_cap = len.checked_add(additional).ok_or(CapacityOverflow)?;
424
425 // This guarantees exponential growth. The doubling cannot overflow
426 // because `cap <= isize::MAX` and the type of `cap` is `usize`.
427 let cap = cmp::max(self.cap.0 * 2, required_cap);
428 let cap = cmp::max(Self::MIN_NON_ZERO_CAP, cap);
429
430 let new_layout = Layout::array::<T>(cap);
431
432 // `finish_grow` is non-generic over `T`.
433 let ptr = finish_grow(new_layout, self.current_memory(), &mut self.alloc)?;
434 // SAFETY: finish_grow would have resulted in a capacity overflow if we tried to allocate more than isize::MAX items
435 unsafe { self.set_ptr_and_cap(ptr, cap) };
436 Ok(())
437 }
438
439 // The constraints on this method are much the same as those on
440 // `grow_amortized`, but this method is usually instantiated less often so
441 // it's less critical.
442 fn grow_exact(&mut self, len: usize, additional: usize) -> Result<(), TryReserveError> {
443 if T::IS_ZST {
444 // Since we return a capacity of `usize::MAX` when the type size is
445 // 0, getting to here necessarily means the `RawVec` is overfull.
446 return Err(CapacityOverflow.into());
447 }
448
449 let cap = len.checked_add(additional).ok_or(CapacityOverflow)?;
450 let new_layout = Layout::array::<T>(cap);
451
452 // `finish_grow` is non-generic over `T`.
453 let ptr = finish_grow(new_layout, self.current_memory(), &mut self.alloc)?;
454 // SAFETY: finish_grow would have resulted in a capacity overflow if we tried to allocate more than isize::MAX items
455 unsafe {
456 self.set_ptr_and_cap(ptr, cap);
457 }
458 Ok(())
459 }
460
461 #[cfg(not(no_global_oom_handling))]
462 fn shrink(&mut self, cap: usize) -> Result<(), TryReserveError> {
463 assert!(cap <= self.capacity(), "Tried to shrink to a larger capacity");
464
465 let (ptr, layout) = if let Some(mem) = self.current_memory() { mem } else { return Ok(()) };
466 // See current_memory() why this assert is here
467 let _: () = const { assert!(mem::size_of::<T>() % mem::align_of::<T>() == 0) };
468
469 // If shrinking to 0, deallocate the buffer. We don't reach this point
470 // for the T::IS_ZST case since current_memory() will have returned
471 // None.
472 if cap == 0 {
473 unsafe { self.alloc.deallocate(ptr, layout) };
474 self.ptr = Unique::dangling();
475 self.cap = Cap::ZERO;
476 } else {
477 let ptr = unsafe {
478 // `Layout::array` cannot overflow here because it would have
479 // overflowed earlier when capacity was larger.
480 let new_size = mem::size_of::<T>().unchecked_mul(cap);
481 let new_layout = Layout::from_size_align_unchecked(new_size, layout.align());
482 self.alloc
483 .shrink(ptr, layout, new_layout)
484 .map_err(|_| AllocError { layout: new_layout, non_exhaustive: () })?
485 };
486 // SAFETY: if the allocation is valid, then the capacity is too
487 unsafe {
488 self.set_ptr_and_cap(ptr, cap);
489 }
490 }
491 Ok(())
492 }
493}
494
495// This function is outside `RawVec` to minimize compile times. See the comment
496// above `RawVec::grow_amortized` for details. (The `A` parameter isn't
497// significant, because the number of different `A` types seen in practice is
498// much smaller than the number of `T` types.)
499#[inline(never)]
500fn finish_grow<A>(
501 new_layout: Result<Layout, LayoutError>,
502 current_memory: Option<(NonNull<u8>, Layout)>,
503 alloc: &mut A,
504) -> Result<NonNull<[u8]>, TryReserveError>
505where
506 A: Allocator,
507{
508 // Check for the error here to minimize the size of `RawVec::grow_*`.
509 let new_layout: Layout = new_layout.map_err(|_| CapacityOverflow)?;
510
511 alloc_guard(alloc_size:new_layout.size())?;
512
513 let memory: Result, AllocError> = if let Some((ptr: NonNull, old_layout: Layout)) = current_memory {
514 debug_assert_eq!(old_layout.align(), new_layout.align());
515 unsafe {
516 // The allocator checks for alignment equality
517 hint::assert_unchecked(cond:old_layout.align() == new_layout.align());
518 alloc.grow(ptr, old_layout, new_layout)
519 }
520 } else {
521 alloc.allocate(new_layout)
522 };
523
524 memory.map_err(|_| AllocError { layout: new_layout, non_exhaustive: () }.into())
525}
526
527unsafe impl<#[may_dangle] T, A: Allocator> Drop for RawVec<T, A> {
528 /// Frees the memory owned by the `RawVec` *without* trying to drop its contents.
529 fn drop(&mut self) {
530 if let Some((ptr: NonNull, layout: Layout)) = self.current_memory() {
531 unsafe { self.alloc.deallocate(ptr, layout) }
532 }
533 }
534}
535
536// Central function for reserve error handling.
537#[cfg(not(no_global_oom_handling))]
538#[inline]
539fn handle_reserve(result: Result<(), TryReserveError>) {
540 match result.map_err(|e: TryReserveError| e.kind()) {
541 Err(CapacityOverflow) => capacity_overflow(),
542 Err(AllocError { layout: Layout, .. }) => handle_alloc_error(layout),
543 Ok(()) => { /* yay */ }
544 }
545}
546
547// We need to guarantee the following:
548// * We don't ever allocate `> isize::MAX` byte-size objects.
549// * We don't overflow `usize::MAX` and actually allocate too little.
550//
551// On 64-bit we just need to check for overflow since trying to allocate
552// `> isize::MAX` bytes will surely fail. On 32-bit and 16-bit we need to add
553// an extra guard for this in case we're running on a platform which can use
554// all 4GB in user-space, e.g., PAE or x32.
555#[inline]
556fn alloc_guard(alloc_size: usize) -> Result<(), TryReserveError> {
557 if usize::BITS < 64 && alloc_size > isize::MAX as usize {
558 Err(CapacityOverflow.into())
559 } else {
560 Ok(())
561 }
562}
563
564// One central function responsible for reporting capacity overflows. This'll
565// ensure that the code generation related to these panics is minimal as there's
566// only one location which panics rather than a bunch throughout the module.
567#[cfg(not(no_global_oom_handling))]
568#[cfg_attr(not(feature = "panic_immediate_abort"), inline(never))]
569fn capacity_overflow() -> ! {
570 panic!("capacity overflow");
571}
572