1 #![unstable(feature = "raw_vec_internals", reason = "implementation detail", issue = "0")]
7 use core::ptr::{self, NonNull, Unique};
10 use crate::alloc::{Alloc, Layout, Global, AllocErr, handle_alloc_error};
11 use crate::collections::TryReserveError::{self, *};
12 use crate::boxed::Box;
17 /// A low-level utility for more ergonomically allocating, reallocating, and deallocating
18 /// a buffer of memory on the heap without having to worry about all the corner cases
19 /// involved. This type is excellent for building your own data structures like Vec and VecDeque.
22 /// * Produces `Unique::empty()` on zero-sized types.
23 /// * Produces `Unique::empty()` on zero-length allocations.
24 /// * Catches all overflows in capacity computations (promotes them to "capacity overflow" panics).
25 /// * Guards against 32-bit systems allocating more than isize::MAX bytes.
26 /// * Guards against overflowing your length.
27 /// * Aborts on OOM or calls `handle_alloc_error` as applicable.
28 /// * Avoids freeing `Unique::empty()`.
29 /// * Contains a `ptr::Unique` and thus endows the user with all related benefits.
31 /// This type does not in anyway inspect the memory that it manages. When dropped it *will*
32 /// free its memory, but it *won't* try to drop its contents. It is up to the user of `RawVec`
33 /// to handle the actual things *stored* inside of a `RawVec`.
35 /// Note that a `RawVec` always forces its capacity to be `usize::MAX` for zero-sized types.
36 /// This enables you to use capacity-growing logic catch the overflows in your length
37 /// that might occur with zero-sized types.
39 /// The above means that you need to be careful when round-tripping this type with a
40 /// `Box<[T]>`, since `capacity()` won't yield the length. However, `with_capacity`,
41 /// `shrink_to_fit`, and `from_box` will actually set `RawVec`'s private capacity
42 /// field. This allows zero-sized types to not be special-cased by consumers of
44 #[allow(missing_debug_implementations)]
45 pub struct RawVec<T, A: Alloc = Global> {
51 impl<T, A: Alloc> RawVec<T, A> {
52 /// Like `new`, but parameterized over the choice of allocator for
53 /// the returned `RawVec`.
54 pub const fn new_in(a: A) -> Self {
55 // `!0` is `usize::MAX`. This branch should be stripped at compile time.
56 // FIXME(mark-i-m): use this line when `if`s are allowed in `const`:
57 //let cap = if mem::size_of::<T>() == 0 { !0 } else { 0 };
59 // `Unique::empty()` doubles as "unallocated" and "zero-sized allocation".
62 // FIXME(mark-i-m): use `cap` when ifs are allowed in const
63 cap: [0, !0][(mem::size_of::<T>() == 0) as usize],
68 /// Like `with_capacity`, but parameterized over the choice of
69 /// allocator for the returned `RawVec`.
71 pub fn with_capacity_in(capacity: usize, a: A) -> Self {
72 RawVec::allocate_in(capacity, false, a)
75 /// Like `with_capacity_zeroed`, but parameterized over the choice
76 /// of allocator for the returned `RawVec`.
78 pub fn with_capacity_zeroed_in(capacity: usize, a: A) -> Self {
79 RawVec::allocate_in(capacity, true, a)
82 fn allocate_in(capacity: usize, zeroed: bool, mut a: A) -> Self {
84 let elem_size = mem::size_of::<T>();
86 let alloc_size = capacity.checked_mul(elem_size).unwrap_or_else(|| capacity_overflow());
87 alloc_guard(alloc_size).unwrap_or_else(|_| capacity_overflow());
89 // Handles ZSTs and `capacity == 0` alike.
90 let ptr = if alloc_size == 0 {
91 NonNull::<T>::dangling()
93 let align = mem::align_of::<T>();
94 let layout = Layout::from_size_align(alloc_size, align).unwrap();
95 let result = if zeroed {
96 a.alloc_zeroed(layout)
101 Ok(ptr) => ptr.cast(),
102 Err(_) => handle_alloc_error(layout),
115 impl<T> RawVec<T, Global> {
116 /// Creates the biggest possible `RawVec` (on the system heap)
117 /// without allocating. If `T` has positive size, then this makes a
118 /// `RawVec` with capacity `0`. If `T` is zero-sized, then it makes a
119 /// `RawVec` with capacity `usize::MAX`. Useful for implementing
120 /// delayed allocation.
121 pub const fn new() -> Self {
125 /// Creates a `RawVec` (on the system heap) with exactly the
126 /// capacity and alignment requirements for a `[T; capacity]`. This is
127 /// equivalent to calling `RawVec::new` when `capacity` is `0` or `T` is
128 /// zero-sized. Note that if `T` is zero-sized this means you will
129 /// *not* get a `RawVec` with the requested capacity.
133 /// * Panics if the requested capacity exceeds `usize::MAX` bytes.
134 /// * Panics on 32-bit platforms if the requested capacity exceeds
135 /// `isize::MAX` bytes.
141 pub fn with_capacity(capacity: usize) -> Self {
142 RawVec::allocate_in(capacity, false, Global)
145 /// Like `with_capacity`, but guarantees the buffer is zeroed.
147 pub fn with_capacity_zeroed(capacity: usize) -> Self {
148 RawVec::allocate_in(capacity, true, Global)
152 impl<T, A: Alloc> RawVec<T, A> {
153 /// Reconstitutes a `RawVec` from a pointer, capacity, and allocator.
155 /// # Undefined Behavior
157 /// The `ptr` must be allocated (via the given allocator `a`), and with the given `capacity`.
158 /// The `capacity` cannot exceed `isize::MAX` (only a concern on 32-bit systems).
159 /// If the `ptr` and `capacity` come from a `RawVec` created via `a`, then this is guaranteed.
160 pub unsafe fn from_raw_parts_in(ptr: *mut T, capacity: usize, a: A) -> Self {
162 ptr: Unique::new_unchecked(ptr),
169 impl<T> RawVec<T, Global> {
170 /// Reconstitutes a `RawVec` from a pointer and capacity.
172 /// # Undefined Behavior
174 /// The `ptr` must be allocated (on the system heap), and with the given `capacity`.
175 /// The `capacity` cannot exceed `isize::MAX` (only a concern on 32-bit systems).
176 /// If the `ptr` and `capacity` come from a `RawVec`, then this is guaranteed.
177 pub unsafe fn from_raw_parts(ptr: *mut T, capacity: usize) -> Self {
179 ptr: Unique::new_unchecked(ptr),
185 /// Converts a `Box<[T]>` into a `RawVec<T>`.
186 pub fn from_box(mut slice: Box<[T]>) -> Self {
188 let result = RawVec::from_raw_parts(slice.as_mut_ptr(), slice.len());
195 impl<T, A: Alloc> RawVec<T, A> {
196 /// Gets a raw pointer to the start of the allocation. Note that this is
197 /// `Unique::empty()` if `capacity == 0` or `T` is zero-sized. In the former case, you must
199 pub fn ptr(&self) -> *mut T {
203 /// Gets the capacity of the allocation.
205 /// This will always be `usize::MAX` if `T` is zero-sized.
207 pub fn capacity(&self) -> usize {
208 if mem::size_of::<T>() == 0 {
215 /// Returns a shared reference to the allocator backing this `RawVec`.
216 pub fn alloc(&self) -> &A {
220 /// Returns a mutable reference to the allocator backing this `RawVec`.
221 pub fn alloc_mut(&mut self) -> &mut A {
225 fn current_layout(&self) -> Option<Layout> {
229 // We have an allocated chunk of memory, so we can bypass runtime
230 // checks to get our current layout.
232 let align = mem::align_of::<T>();
233 let size = mem::size_of::<T>() * self.cap;
234 Some(Layout::from_size_align_unchecked(size, align))
239 /// Doubles the size of the type's backing allocation. This is common enough
240 /// to want to do that it's easiest to just have a dedicated method. Slightly
241 /// more efficient logic can be provided for this than the general case.
243 /// This function is ideal for when pushing elements one-at-a-time because
244 /// you don't need to incur the costs of the more general computations
245 /// reserve needs to do to guard against overflow. You do however need to
246 /// manually check if your `len == capacity`.
250 /// * Panics if `T` is zero-sized on the assumption that you managed to exhaust
251 /// all `usize::MAX` slots in your imaginary buffer.
252 /// * Panics on 32-bit platforms if the requested capacity exceeds
253 /// `isize::MAX` bytes.
262 /// # #![feature(raw_vec_internals)]
263 /// # extern crate alloc;
265 /// # use alloc::raw_vec::RawVec;
266 /// struct MyVec<T> {
271 /// impl<T> MyVec<T> {
272 /// pub fn push(&mut self, elem: T) {
273 /// if self.len == self.buf.capacity() { self.buf.double(); }
274 /// // double would have aborted or panicked if the len exceeded
275 /// // `isize::MAX` so this is safe to do unchecked now.
277 /// ptr::write(self.buf.ptr().add(self.len), elem);
283 /// # let mut vec = MyVec { buf: RawVec::new(), len: 0 };
289 pub fn double(&mut self) {
291 let elem_size = mem::size_of::<T>();
293 // Since we set the capacity to `usize::MAX` when `elem_size` is
294 // 0, getting to here necessarily means the `RawVec` is overfull.
295 assert!(elem_size != 0, "capacity overflow");
297 let (new_cap, uniq) = match self.current_layout() {
299 // Since we guarantee that we never allocate more than
300 // `isize::MAX` bytes, `elem_size * self.cap <= isize::MAX` as
301 // a precondition, so this can't overflow. Additionally the
302 // alignment will never be too large as to "not be
303 // satisfiable", so `Layout::from_size_align` will always
306 // TL;DR, we bypass runtime checks due to dynamic assertions
307 // in this module, allowing us to use
308 // `from_size_align_unchecked`.
309 let new_cap = 2 * self.cap;
310 let new_size = new_cap * elem_size;
311 alloc_guard(new_size).unwrap_or_else(|_| capacity_overflow());
312 let ptr_res = self.a.realloc(NonNull::from(self.ptr).cast(),
316 Ok(ptr) => (new_cap, ptr.cast().into()),
317 Err(_) => handle_alloc_error(
318 Layout::from_size_align_unchecked(new_size, cur.align())
323 // Skip to 4 because tiny `Vec`'s are dumb; but not if that
324 // would cause overflow.
325 let new_cap = if elem_size > (!0) / 8 { 1 } else { 4 };
326 match self.a.alloc_array::<T>(new_cap) {
327 Ok(ptr) => (new_cap, ptr.into()),
328 Err(_) => handle_alloc_error(Layout::array::<T>(new_cap).unwrap()),
337 /// Attempts to double the size of the type's backing allocation in place. This is common
338 /// enough to want to do that it's easiest to just have a dedicated method. Slightly
339 /// more efficient logic can be provided for this than the general case.
341 /// Returns `true` if the reallocation attempt has succeeded.
345 /// * Panics if `T` is zero-sized on the assumption that you managed to exhaust
346 /// all `usize::MAX` slots in your imaginary buffer.
347 /// * Panics on 32-bit platforms if the requested capacity exceeds
348 /// `isize::MAX` bytes.
351 pub fn double_in_place(&mut self) -> bool {
353 let elem_size = mem::size_of::<T>();
354 let old_layout = match self.current_layout() {
355 Some(layout) => layout,
356 None => return false, // nothing to double
359 // Since we set the capacity to `usize::MAX` when `elem_size` is
360 // 0, getting to here necessarily means the `RawVec` is overfull.
361 assert!(elem_size != 0, "capacity overflow");
363 // Since we guarantee that we never allocate more than `isize::MAX`
364 // bytes, `elem_size * self.cap <= isize::MAX` as a precondition, so
365 // this can't overflow.
367 // Similarly to with `double` above, we can go straight to
368 // `Layout::from_size_align_unchecked` as we know this won't
369 // overflow and the alignment is sufficiently small.
370 let new_cap = 2 * self.cap;
371 let new_size = new_cap * elem_size;
372 alloc_guard(new_size).unwrap_or_else(|_| capacity_overflow());
373 match self.a.grow_in_place(NonNull::from(self.ptr).cast(), old_layout, new_size) {
375 // We can't directly divide `size`.
386 /// The same as `reserve_exact`, but returns on errors instead of panicking or aborting.
387 pub fn try_reserve_exact(&mut self, used_capacity: usize, needed_extra_capacity: usize)
388 -> Result<(), TryReserveError> {
390 self.reserve_internal(used_capacity, needed_extra_capacity, Fallible, Exact)
393 /// Ensures that the buffer contains at least enough space to hold
394 /// `used_capacity + needed_extra_capacity` elements. If it doesn't already,
395 /// will reallocate the minimum possible amount of memory necessary.
396 /// Generally this will be exactly the amount of memory necessary,
397 /// but in principle the allocator is free to give back more than
400 /// If `used_capacity` exceeds `self.capacity()`, this may fail to actually allocate
401 /// the requested space. This is not really unsafe, but the unsafe
402 /// code *you* write that relies on the behavior of this function may break.
406 /// * Panics if the requested capacity exceeds `usize::MAX` bytes.
407 /// * Panics on 32-bit platforms if the requested capacity exceeds
408 /// `isize::MAX` bytes.
413 pub fn reserve_exact(&mut self, used_capacity: usize, needed_extra_capacity: usize) {
414 match self.reserve_internal(used_capacity, needed_extra_capacity, Infallible, Exact) {
415 Err(CapacityOverflow) => capacity_overflow(),
416 Err(AllocError { .. }) => unreachable!(),
417 Ok(()) => { /* yay */ }
421 /// Calculates the buffer's new size given that it'll hold `used_capacity +
422 /// needed_extra_capacity` elements. This logic is used in amortized reserve methods.
423 /// Returns `(new_capacity, new_alloc_size)`.
424 fn amortized_new_size(&self, used_capacity: usize, needed_extra_capacity: usize)
425 -> Result<usize, TryReserveError> {
427 // Nothing we can really do about these checks, sadly.
428 let required_cap = used_capacity.checked_add(needed_extra_capacity)
429 .ok_or(CapacityOverflow)?;
430 // Cannot overflow, because `cap <= isize::MAX`, and type of `cap` is `usize`.
431 let double_cap = self.cap * 2;
432 // `double_cap` guarantees exponential growth.
433 Ok(cmp::max(double_cap, required_cap))
436 /// The same as `reserve`, but returns on errors instead of panicking or aborting.
437 pub fn try_reserve(&mut self, used_capacity: usize, needed_extra_capacity: usize)
438 -> Result<(), TryReserveError> {
439 self.reserve_internal(used_capacity, needed_extra_capacity, Fallible, Amortized)
442 /// Ensures that the buffer contains at least enough space to hold
443 /// `used_capacity + needed_extra_capacity` elements. If it doesn't already have
444 /// enough capacity, will reallocate enough space plus comfortable slack
445 /// space to get amortized `O(1)` behavior. Will limit this behavior
446 /// if it would needlessly cause itself to panic.
448 /// If `used_capacity` exceeds `self.capacity()`, this may fail to actually allocate
449 /// the requested space. This is not really unsafe, but the unsafe
450 /// code *you* write that relies on the behavior of this function may break.
452 /// This is ideal for implementing a bulk-push operation like `extend`.
456 /// * Panics if the requested capacity exceeds `usize::MAX` bytes.
457 /// * Panics on 32-bit platforms if the requested capacity exceeds
458 /// `isize::MAX` bytes.
467 /// # #![feature(raw_vec_internals)]
468 /// # extern crate alloc;
470 /// # use alloc::raw_vec::RawVec;
471 /// struct MyVec<T> {
476 /// impl<T: Clone> MyVec<T> {
477 /// pub fn push_all(&mut self, elems: &[T]) {
478 /// self.buf.reserve(self.len, elems.len());
479 /// // reserve would have aborted or panicked if the len exceeded
480 /// // `isize::MAX` so this is safe to do unchecked now.
483 /// ptr::write(self.buf.ptr().add(self.len), x.clone());
490 /// # let mut vector = MyVec { buf: RawVec::new(), len: 0 };
491 /// # vector.push_all(&[1, 3, 5, 7, 9]);
494 pub fn reserve(&mut self, used_capacity: usize, needed_extra_capacity: usize) {
495 match self.reserve_internal(used_capacity, needed_extra_capacity, Infallible, Amortized) {
496 Err(CapacityOverflow) => capacity_overflow(),
497 Err(AllocError { .. }) => unreachable!(),
498 Ok(()) => { /* yay */ }
501 /// Attempts to ensure that the buffer contains at least enough space to hold
502 /// `used_capacity + needed_extra_capacity` elements. If it doesn't already have
503 /// enough capacity, will reallocate in place enough space plus comfortable slack
504 /// space to get amortized `O(1)` behavior. Will limit this behaviour
505 /// if it would needlessly cause itself to panic.
507 /// If `used_capacity` exceeds `self.capacity()`, this may fail to actually allocate
508 /// the requested space. This is not really unsafe, but the unsafe
509 /// code *you* write that relies on the behavior of this function may break.
511 /// Returns `true` if the reallocation attempt has succeeded.
515 /// * Panics if the requested capacity exceeds `usize::MAX` bytes.
516 /// * Panics on 32-bit platforms if the requested capacity exceeds
517 /// `isize::MAX` bytes.
518 pub fn reserve_in_place(&mut self, used_capacity: usize, needed_extra_capacity: usize) -> bool {
520 // NOTE: we don't early branch on ZSTs here because we want this
521 // to actually catch "asking for more than usize::MAX" in that case.
522 // If we make it past the first branch then we are guaranteed to
525 // Don't actually need any more capacity. If the current `cap` is 0, we can't
526 // reallocate in place.
527 // Wrapping in case they give a bad `used_capacity`
528 let old_layout = match self.current_layout() {
529 Some(layout) => layout,
530 None => return false,
532 if self.capacity().wrapping_sub(used_capacity) >= needed_extra_capacity {
536 let new_cap = self.amortized_new_size(used_capacity, needed_extra_capacity)
537 .unwrap_or_else(|_| capacity_overflow());
539 // Here, `cap < used_capacity + needed_extra_capacity <= new_cap`
540 // (regardless of whether `self.cap - used_capacity` wrapped).
541 // Therefore, we can safely call `grow_in_place`.
543 let new_layout = Layout::new::<T>().repeat(new_cap).unwrap().0;
544 // FIXME: may crash and burn on over-reserve
545 alloc_guard(new_layout.size()).unwrap_or_else(|_| capacity_overflow());
546 match self.a.grow_in_place(
547 NonNull::from(self.ptr).cast(), old_layout, new_layout.size(),
560 /// Shrinks the allocation down to the specified amount. If the given amount
561 /// is 0, actually completely deallocates.
565 /// Panics if the given amount is *larger* than the current capacity.
570 pub fn shrink_to_fit(&mut self, amount: usize) {
571 let elem_size = mem::size_of::<T>();
573 // Set the `cap` because they might be about to promote to a `Box<[T]>`
579 // This check is my waterloo; it's the only thing `Vec` wouldn't have to do.
580 assert!(self.cap >= amount, "Tried to shrink to a larger capacity");
583 // We want to create a new zero-length vector within the
584 // same allocator. We use `ptr::write` to avoid an
585 // erroneous attempt to drop the contents, and we use
586 // `ptr::read` to sidestep condition against destructuring
587 // types that implement Drop.
590 let a = ptr::read(&self.a as *const A);
591 self.dealloc_buffer();
592 ptr::write(self, RawVec::new_in(a));
594 } else if self.cap != amount {
596 // We know here that our `amount` is greater than zero. This
597 // implies, via the assert above, that capacity is also greater
598 // than zero, which means that we've got a current layout that
601 // We also know that `self.cap` is greater than `amount`, and
602 // consequently we don't need runtime checks for creating either
604 let old_size = elem_size * self.cap;
605 let new_size = elem_size * amount;
606 let align = mem::align_of::<T>();
607 let old_layout = Layout::from_size_align_unchecked(old_size, align);
608 match self.a.realloc(NonNull::from(self.ptr).cast(),
611 Ok(p) => self.ptr = p.cast().into(),
612 Err(_) => handle_alloc_error(
613 Layout::from_size_align_unchecked(new_size, align)
629 enum ReserveStrategy {
634 use ReserveStrategy::*;
636 impl<T, A: Alloc> RawVec<T, A> {
639 used_capacity: usize,
640 needed_extra_capacity: usize,
641 fallibility: Fallibility,
642 strategy: ReserveStrategy,
643 ) -> Result<(), TryReserveError> {
645 // NOTE: we don't early branch on ZSTs here because we want this
646 // to actually catch "asking for more than usize::MAX" in that case.
647 // If we make it past the first branch then we are guaranteed to
650 // Don't actually need any more capacity.
651 // Wrapping in case they gave a bad `used_capacity`.
652 if self.capacity().wrapping_sub(used_capacity) >= needed_extra_capacity {
656 // Nothing we can really do about these checks, sadly.
657 let new_cap = match strategy {
658 Exact => used_capacity.checked_add(needed_extra_capacity).ok_or(CapacityOverflow)?,
659 Amortized => self.amortized_new_size(used_capacity, needed_extra_capacity)?,
661 let new_layout = Layout::array::<T>(new_cap).map_err(|_| CapacityOverflow)?;
663 alloc_guard(new_layout.size())?;
665 let res = match self.current_layout() {
667 debug_assert!(new_layout.align() == layout.align());
668 self.a.realloc(NonNull::from(self.ptr).cast(), layout, new_layout.size())
670 None => self.a.alloc(new_layout),
673 let ptr = match (res, fallibility) {
674 (Err(AllocErr), Infallible) => handle_alloc_error(new_layout),
675 (Err(AllocErr), Fallible) => return Err(TryReserveError::AllocError {
682 self.ptr = ptr.cast().into();
691 impl<T> RawVec<T, Global> {
692 /// Converts the entire buffer into `Box<[T]>`.
694 /// Note that this will correctly reconstitute any `cap` changes
695 /// that may have been performed. (See description of type for details.)
697 /// # Undefined Behavior
699 /// All elements of `RawVec<T, Global>` must be initialized. Notice that
700 /// the rules around uninitialized boxed values are not finalized yet,
701 /// but until they are, it is advisable to avoid them.
702 pub unsafe fn into_box(self) -> Box<[T]> {
703 // NOTE: not calling `capacity()` here; actually using the real `cap` field!
704 let slice = slice::from_raw_parts_mut(self.ptr(), self.cap);
705 let output: Box<[T]> = Box::from_raw(slice);
711 impl<T, A: Alloc> RawVec<T, A> {
712 /// Frees the memory owned by the `RawVec` *without* trying to drop its contents.
713 pub unsafe fn dealloc_buffer(&mut self) {
714 let elem_size = mem::size_of::<T>();
716 if let Some(layout) = self.current_layout() {
717 self.a.dealloc(NonNull::from(self.ptr).cast(), layout);
723 unsafe impl<#[may_dangle] T, A: Alloc> Drop for RawVec<T, A> {
724 /// Frees the memory owned by the `RawVec` *without* trying to drop its contents.
726 unsafe { self.dealloc_buffer(); }
730 // We need to guarantee the following:
731 // * We don't ever allocate `> isize::MAX` byte-size objects.
732 // * We don't overflow `usize::MAX` and actually allocate too little.
734 // On 64-bit we just need to check for overflow since trying to allocate
735 // `> isize::MAX` bytes will surely fail. On 32-bit and 16-bit we need to add
736 // an extra guard for this in case we're running on a platform which can use
737 // all 4GB in user-space, e.g., PAE or x32.
740 fn alloc_guard(alloc_size: usize) -> Result<(), TryReserveError> {
741 if mem::size_of::<usize>() < 8 && alloc_size > core::isize::MAX as usize {
742 Err(CapacityOverflow)
748 // One central function responsible for reporting capacity overflows. This'll
749 // ensure that the code generation related to these panics is minimal as there's
750 // only one location which panics rather than a bunch throughout the module.
751 fn capacity_overflow() -> ! {
752 panic!("capacity overflow");