]> git.lizzy.rs Git - rust.git/blob - src/liballoc/raw_vec.rs
bug on ty::GeneratorWitness
[rust.git] / src / liballoc / raw_vec.rs
1 #![unstable(feature = "raw_vec_internals", reason = "implementation detail", issue = "none")]
2 #![doc(hidden)]
3
4 use core::cmp;
5 use core::mem;
6 use core::ops::Drop;
7 use core::ptr::{self, NonNull, Unique};
8 use core::slice;
9
10 use crate::alloc::{handle_alloc_error, AllocErr, AllocRef, Global, Layout};
11 use crate::boxed::Box;
12 use crate::collections::TryReserveError::{self, *};
13
14 #[cfg(test)]
15 mod tests;
16
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.
20 /// In particular:
21 ///
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.
30 ///
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`.
34 ///
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.
38 ///
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
43 /// this type.
44 #[allow(missing_debug_implementations)]
45 pub struct RawVec<T, A: AllocRef = Global> {
46     ptr: Unique<T>,
47     cap: usize,
48     a: A,
49 }
50
51 impl<T, A: AllocRef> 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         let cap = if mem::size_of::<T>() == 0 { core::usize::MAX } else { 0 };
56
57         // `Unique::empty()` doubles as "unallocated" and "zero-sized allocation".
58         RawVec { ptr: Unique::empty(), cap, a }
59     }
60
61     /// Like `with_capacity`, but parameterized over the choice of
62     /// allocator for the returned `RawVec`.
63     #[inline]
64     pub fn with_capacity_in(capacity: usize, a: A) -> Self {
65         RawVec::allocate_in(capacity, false, a)
66     }
67
68     /// Like `with_capacity_zeroed`, but parameterized over the choice
69     /// of allocator for the returned `RawVec`.
70     #[inline]
71     pub fn with_capacity_zeroed_in(capacity: usize, a: A) -> Self {
72         RawVec::allocate_in(capacity, true, a)
73     }
74
75     fn allocate_in(mut capacity: usize, zeroed: bool, mut a: A) -> Self {
76         unsafe {
77             let elem_size = mem::size_of::<T>();
78
79             let alloc_size = capacity.checked_mul(elem_size).unwrap_or_else(|| capacity_overflow());
80             alloc_guard(alloc_size).unwrap_or_else(|_| capacity_overflow());
81
82             // Handles ZSTs and `capacity == 0` alike.
83             let ptr = if alloc_size == 0 {
84                 NonNull::<T>::dangling()
85             } else {
86                 let align = mem::align_of::<T>();
87                 let layout = Layout::from_size_align(alloc_size, align).unwrap();
88                 let result = if zeroed { a.alloc_zeroed(layout) } else { a.alloc(layout) };
89                 match result {
90                     Ok((ptr, size)) => {
91                         capacity = size / elem_size;
92                         ptr.cast()
93                     }
94                     Err(_) => handle_alloc_error(layout),
95                 }
96             };
97
98             RawVec { ptr: ptr.into(), cap: capacity, a }
99         }
100     }
101 }
102
103 impl<T> RawVec<T, Global> {
104     /// HACK(Centril): This exists because `#[unstable]` `const fn`s needn't conform
105     /// to `min_const_fn` and so they cannot be called in `min_const_fn`s either.
106     ///
107     /// If you change `RawVec<T>::new` or dependencies, please take care to not
108     /// introduce anything that would truly violate `min_const_fn`.
109     ///
110     /// NOTE: We could avoid this hack and check conformance with some
111     /// `#[rustc_force_min_const_fn]` attribute which requires conformance
112     /// with `min_const_fn` but does not necessarily allow calling it in
113     /// `stable(...) const fn` / user code not enabling `foo` when
114     /// `#[rustc_const_unstable(feature = "foo", ..)]` is present.
115     pub const NEW: Self = Self::new();
116
117     /// Creates the biggest possible `RawVec` (on the system heap)
118     /// without allocating. If `T` has positive size, then this makes a
119     /// `RawVec` with capacity `0`. If `T` is zero-sized, then it makes a
120     /// `RawVec` with capacity `usize::MAX`. Useful for implementing
121     /// delayed allocation.
122     pub const fn new() -> Self {
123         Self::new_in(Global)
124     }
125
126     /// Creates a `RawVec` (on the system heap) with exactly the
127     /// capacity and alignment requirements for a `[T; capacity]`. This is
128     /// equivalent to calling `RawVec::new` when `capacity` is `0` or `T` is
129     /// zero-sized. Note that if `T` is zero-sized this means you will
130     /// *not* get a `RawVec` with the requested capacity.
131     ///
132     /// # Panics
133     ///
134     /// * Panics if the requested capacity exceeds `usize::MAX` bytes.
135     /// * Panics on 32-bit platforms if the requested capacity exceeds
136     ///   `isize::MAX` bytes.
137     ///
138     /// # Aborts
139     ///
140     /// Aborts on OOM.
141     #[inline]
142     pub fn with_capacity(capacity: usize) -> Self {
143         RawVec::allocate_in(capacity, false, Global)
144     }
145
146     /// Like `with_capacity`, but guarantees the buffer is zeroed.
147     #[inline]
148     pub fn with_capacity_zeroed(capacity: usize) -> Self {
149         RawVec::allocate_in(capacity, true, Global)
150     }
151 }
152
153 impl<T, A: AllocRef> RawVec<T, A> {
154     /// Reconstitutes a `RawVec` from a pointer, capacity, and allocator.
155     ///
156     /// # Undefined Behavior
157     ///
158     /// The `ptr` must be allocated (via the given allocator `a`), and with the given `capacity`.
159     /// The `capacity` cannot exceed `isize::MAX` (only a concern on 32-bit systems).
160     /// If the `ptr` and `capacity` come from a `RawVec` created via `a`, then this is guaranteed.
161     pub unsafe fn from_raw_parts_in(ptr: *mut T, capacity: usize, a: A) -> Self {
162         RawVec { ptr: Unique::new_unchecked(ptr), cap: capacity, a }
163     }
164 }
165
166 impl<T> RawVec<T, Global> {
167     /// Reconstitutes a `RawVec` from a pointer and capacity.
168     ///
169     /// # Undefined Behavior
170     ///
171     /// The `ptr` must be allocated (on the system heap), and with the given `capacity`.
172     /// The `capacity` cannot exceed `isize::MAX` (only a concern on 32-bit systems).
173     /// If the `ptr` and `capacity` come from a `RawVec`, then this is guaranteed.
174     pub unsafe fn from_raw_parts(ptr: *mut T, capacity: usize) -> Self {
175         RawVec { ptr: Unique::new_unchecked(ptr), cap: capacity, a: Global }
176     }
177
178     /// Converts a `Box<[T]>` into a `RawVec<T>`.
179     pub fn from_box(mut slice: Box<[T]>) -> Self {
180         unsafe {
181             let result = RawVec::from_raw_parts(slice.as_mut_ptr(), slice.len());
182             mem::forget(slice);
183             result
184         }
185     }
186 }
187
188 impl<T, A: AllocRef> RawVec<T, A> {
189     /// Gets a raw pointer to the start of the allocation. Note that this is
190     /// `Unique::empty()` if `capacity == 0` or `T` is zero-sized. In the former case, you must
191     /// be careful.
192     pub fn ptr(&self) -> *mut T {
193         self.ptr.as_ptr()
194     }
195
196     /// Gets the capacity of the allocation.
197     ///
198     /// This will always be `usize::MAX` if `T` is zero-sized.
199     #[inline(always)]
200     pub fn capacity(&self) -> usize {
201         if mem::size_of::<T>() == 0 { !0 } else { self.cap }
202     }
203
204     /// Returns a shared reference to the allocator backing this `RawVec`.
205     pub fn alloc(&self) -> &A {
206         &self.a
207     }
208
209     /// Returns a mutable reference to the allocator backing this `RawVec`.
210     pub fn alloc_mut(&mut self) -> &mut A {
211         &mut self.a
212     }
213
214     fn current_layout(&self) -> Option<Layout> {
215         if self.cap == 0 {
216             None
217         } else {
218             // We have an allocated chunk of memory, so we can bypass runtime
219             // checks to get our current layout.
220             unsafe {
221                 let align = mem::align_of::<T>();
222                 let size = mem::size_of::<T>() * self.cap;
223                 Some(Layout::from_size_align_unchecked(size, align))
224             }
225         }
226     }
227
228     /// Doubles the size of the type's backing allocation. This is common enough
229     /// to want to do that it's easiest to just have a dedicated method. Slightly
230     /// more efficient logic can be provided for this than the general case.
231     ///
232     /// This function is ideal for when pushing elements one-at-a-time because
233     /// you don't need to incur the costs of the more general computations
234     /// reserve needs to do to guard against overflow. You do however need to
235     /// manually check if your `len == capacity`.
236     ///
237     /// # Panics
238     ///
239     /// * Panics if `T` is zero-sized on the assumption that you managed to exhaust
240     ///   all `usize::MAX` slots in your imaginary buffer.
241     /// * Panics on 32-bit platforms if the requested capacity exceeds
242     ///   `isize::MAX` bytes.
243     ///
244     /// # Aborts
245     ///
246     /// Aborts on OOM
247     ///
248     /// # Examples
249     ///
250     /// ```
251     /// # #![feature(raw_vec_internals)]
252     /// # extern crate alloc;
253     /// # use std::ptr;
254     /// # use alloc::raw_vec::RawVec;
255     /// struct MyVec<T> {
256     ///     buf: RawVec<T>,
257     ///     len: usize,
258     /// }
259     ///
260     /// impl<T> MyVec<T> {
261     ///     pub fn push(&mut self, elem: T) {
262     ///         if self.len == self.buf.capacity() { self.buf.double(); }
263     ///         // double would have aborted or panicked if the len exceeded
264     ///         // `isize::MAX` so this is safe to do unchecked now.
265     ///         unsafe {
266     ///             ptr::write(self.buf.ptr().add(self.len), elem);
267     ///         }
268     ///         self.len += 1;
269     ///     }
270     /// }
271     /// # fn main() {
272     /// #   let mut vec = MyVec { buf: RawVec::new(), len: 0 };
273     /// #   vec.push(1);
274     /// # }
275     /// ```
276     #[inline(never)]
277     #[cold]
278     pub fn double(&mut self) {
279         unsafe {
280             let elem_size = mem::size_of::<T>();
281
282             // Since we set the capacity to `usize::MAX` when `elem_size` is
283             // 0, getting to here necessarily means the `RawVec` is overfull.
284             assert!(elem_size != 0, "capacity overflow");
285
286             let (ptr, new_cap) = match self.current_layout() {
287                 Some(cur) => {
288                     // Since we guarantee that we never allocate more than
289                     // `isize::MAX` bytes, `elem_size * self.cap <= isize::MAX` as
290                     // a precondition, so this can't overflow. Additionally the
291                     // alignment will never be too large as to "not be
292                     // satisfiable", so `Layout::from_size_align` will always
293                     // return `Some`.
294                     //
295                     // TL;DR, we bypass runtime checks due to dynamic assertions
296                     // in this module, allowing us to use
297                     // `from_size_align_unchecked`.
298                     let new_cap = 2 * self.cap;
299                     let new_size = new_cap * elem_size;
300                     alloc_guard(new_size).unwrap_or_else(|_| capacity_overflow());
301                     let ptr_res = self.a.realloc(NonNull::from(self.ptr).cast(), cur, new_size);
302                     match ptr_res {
303                         Ok((ptr, new_size)) => (ptr, new_size / elem_size),
304                         Err(_) => handle_alloc_error(Layout::from_size_align_unchecked(
305                             new_size,
306                             cur.align(),
307                         )),
308                     }
309                 }
310                 None => {
311                     // Skip to 4 because tiny `Vec`'s are dumb; but not if that
312                     // would cause overflow.
313                     let new_cap = if elem_size > (!0) / 8 { 1 } else { 4 };
314                     let layout = Layout::array::<T>(new_cap).unwrap();
315                     match self.a.alloc(layout) {
316                         Ok((ptr, new_size)) => (ptr, new_size / elem_size),
317                         Err(_) => handle_alloc_error(layout),
318                     }
319                 }
320             };
321             self.ptr = ptr.cast().into();
322             self.cap = new_cap;
323         }
324     }
325
326     /// Attempts to double the size of the type's backing allocation in place. This is common
327     /// enough to want to do that it's easiest to just have a dedicated method. Slightly
328     /// more efficient logic can be provided for this than the general case.
329     ///
330     /// Returns `true` if the reallocation attempt has succeeded.
331     ///
332     /// # Panics
333     ///
334     /// * Panics if `T` is zero-sized on the assumption that you managed to exhaust
335     ///   all `usize::MAX` slots in your imaginary buffer.
336     /// * Panics on 32-bit platforms if the requested capacity exceeds
337     ///   `isize::MAX` bytes.
338     #[inline(never)]
339     #[cold]
340     pub fn double_in_place(&mut self) -> bool {
341         unsafe {
342             let elem_size = mem::size_of::<T>();
343             let old_layout = match self.current_layout() {
344                 Some(layout) => layout,
345                 None => return false, // nothing to double
346             };
347
348             // Since we set the capacity to `usize::MAX` when `elem_size` is
349             // 0, getting to here necessarily means the `RawVec` is overfull.
350             assert!(elem_size != 0, "capacity overflow");
351
352             // Since we guarantee that we never allocate more than `isize::MAX`
353             // bytes, `elem_size * self.cap <= isize::MAX` as a precondition, so
354             // this can't overflow.
355             //
356             // Similarly to with `double` above, we can go straight to
357             // `Layout::from_size_align_unchecked` as we know this won't
358             // overflow and the alignment is sufficiently small.
359             let new_cap = 2 * self.cap;
360             let new_size = new_cap * elem_size;
361             alloc_guard(new_size).unwrap_or_else(|_| capacity_overflow());
362             match self.a.grow_in_place(NonNull::from(self.ptr).cast(), old_layout, new_size) {
363                 Ok(_) => {
364                     // We can't directly divide `size`.
365                     self.cap = new_cap;
366                     true
367                 }
368                 Err(_) => false,
369             }
370         }
371     }
372
373     /// The same as `reserve_exact`, but returns on errors instead of panicking or aborting.
374     pub fn try_reserve_exact(
375         &mut self,
376         used_capacity: usize,
377         needed_extra_capacity: usize,
378     ) -> Result<(), TryReserveError> {
379         self.reserve_internal(used_capacity, needed_extra_capacity, Fallible, Exact)
380     }
381
382     /// Ensures that the buffer contains at least enough space to hold
383     /// `used_capacity + needed_extra_capacity` elements. If it doesn't already,
384     /// will reallocate the minimum possible amount of memory necessary.
385     /// Generally this will be exactly the amount of memory necessary,
386     /// but in principle the allocator is free to give back more than
387     /// we asked for.
388     ///
389     /// If `used_capacity` exceeds `self.capacity()`, this may fail to actually allocate
390     /// the requested space. This is not really unsafe, but the unsafe
391     /// code *you* write that relies on the behavior of this function may break.
392     ///
393     /// # Panics
394     ///
395     /// * Panics if the requested capacity exceeds `usize::MAX` bytes.
396     /// * Panics on 32-bit platforms if the requested capacity exceeds
397     ///   `isize::MAX` bytes.
398     ///
399     /// # Aborts
400     ///
401     /// Aborts on OOM.
402     pub fn reserve_exact(&mut self, used_capacity: usize, needed_extra_capacity: usize) {
403         match self.reserve_internal(used_capacity, needed_extra_capacity, Infallible, Exact) {
404             Err(CapacityOverflow) => capacity_overflow(),
405             Err(AllocError { .. }) => unreachable!(),
406             Ok(()) => { /* yay */ }
407         }
408     }
409
410     /// Calculates the buffer's new size given that it'll hold `used_capacity +
411     /// needed_extra_capacity` elements. This logic is used in amortized reserve methods.
412     /// Returns `(new_capacity, new_alloc_size)`.
413     fn amortized_new_size(
414         &self,
415         used_capacity: usize,
416         needed_extra_capacity: usize,
417     ) -> Result<usize, TryReserveError> {
418         // Nothing we can really do about these checks, sadly.
419         let required_cap =
420             used_capacity.checked_add(needed_extra_capacity).ok_or(CapacityOverflow)?;
421         // Cannot overflow, because `cap <= isize::MAX`, and type of `cap` is `usize`.
422         let double_cap = self.cap * 2;
423         // `double_cap` guarantees exponential growth.
424         Ok(cmp::max(double_cap, required_cap))
425     }
426
427     /// The same as `reserve`, but returns on errors instead of panicking or aborting.
428     pub fn try_reserve(
429         &mut self,
430         used_capacity: usize,
431         needed_extra_capacity: usize,
432     ) -> Result<(), TryReserveError> {
433         self.reserve_internal(used_capacity, needed_extra_capacity, Fallible, Amortized)
434     }
435
436     /// Ensures that the buffer contains at least enough space to hold
437     /// `used_capacity + needed_extra_capacity` elements. If it doesn't already have
438     /// enough capacity, will reallocate enough space plus comfortable slack
439     /// space to get amortized `O(1)` behavior. Will limit this behavior
440     /// if it would needlessly cause itself to panic.
441     ///
442     /// If `used_capacity` exceeds `self.capacity()`, this may fail to actually allocate
443     /// the requested space. This is not really unsafe, but the unsafe
444     /// code *you* write that relies on the behavior of this function may break.
445     ///
446     /// This is ideal for implementing a bulk-push operation like `extend`.
447     ///
448     /// # Panics
449     ///
450     /// * Panics if the requested capacity exceeds `usize::MAX` bytes.
451     /// * Panics on 32-bit platforms if the requested capacity exceeds
452     ///   `isize::MAX` bytes.
453     ///
454     /// # Aborts
455     ///
456     /// Aborts on OOM.
457     ///
458     /// # Examples
459     ///
460     /// ```
461     /// # #![feature(raw_vec_internals)]
462     /// # extern crate alloc;
463     /// # use std::ptr;
464     /// # use alloc::raw_vec::RawVec;
465     /// struct MyVec<T> {
466     ///     buf: RawVec<T>,
467     ///     len: usize,
468     /// }
469     ///
470     /// impl<T: Clone> MyVec<T> {
471     ///     pub fn push_all(&mut self, elems: &[T]) {
472     ///         self.buf.reserve(self.len, elems.len());
473     ///         // reserve would have aborted or panicked if the len exceeded
474     ///         // `isize::MAX` so this is safe to do unchecked now.
475     ///         for x in elems {
476     ///             unsafe {
477     ///                 ptr::write(self.buf.ptr().add(self.len), x.clone());
478     ///             }
479     ///             self.len += 1;
480     ///         }
481     ///     }
482     /// }
483     /// # fn main() {
484     /// #   let mut vector = MyVec { buf: RawVec::new(), len: 0 };
485     /// #   vector.push_all(&[1, 3, 5, 7, 9]);
486     /// # }
487     /// ```
488     pub fn reserve(&mut self, used_capacity: usize, needed_extra_capacity: usize) {
489         match self.reserve_internal(used_capacity, needed_extra_capacity, Infallible, Amortized) {
490             Err(CapacityOverflow) => capacity_overflow(),
491             Err(AllocError { .. }) => unreachable!(),
492             Ok(()) => { /* yay */ }
493         }
494     }
495     /// Attempts to ensure that the buffer contains at least enough space to hold
496     /// `used_capacity + needed_extra_capacity` elements. If it doesn't already have
497     /// enough capacity, will reallocate in place enough space plus comfortable slack
498     /// space to get amortized `O(1)` behavior. Will limit this behaviour
499     /// if it would needlessly cause itself to panic.
500     ///
501     /// If `used_capacity` exceeds `self.capacity()`, this may fail to actually allocate
502     /// the requested space. This is not really unsafe, but the unsafe
503     /// code *you* write that relies on the behavior of this function may break.
504     ///
505     /// Returns `true` if the reallocation attempt has succeeded.
506     ///
507     /// # Panics
508     ///
509     /// * Panics if the requested capacity exceeds `usize::MAX` bytes.
510     /// * Panics on 32-bit platforms if the requested capacity exceeds
511     ///   `isize::MAX` bytes.
512     pub fn reserve_in_place(&mut self, used_capacity: usize, needed_extra_capacity: usize) -> bool {
513         unsafe {
514             // NOTE: we don't early branch on ZSTs here because we want this
515             // to actually catch "asking for more than usize::MAX" in that case.
516             // If we make it past the first branch then we are guaranteed to
517             // panic.
518
519             // Don't actually need any more capacity. If the current `cap` is 0, we can't
520             // reallocate in place.
521             // Wrapping in case they give a bad `used_capacity`
522             let old_layout = match self.current_layout() {
523                 Some(layout) => layout,
524                 None => return false,
525             };
526             if self.capacity().wrapping_sub(used_capacity) >= needed_extra_capacity {
527                 return false;
528             }
529
530             let new_cap = self
531                 .amortized_new_size(used_capacity, needed_extra_capacity)
532                 .unwrap_or_else(|_| capacity_overflow());
533
534             // Here, `cap < used_capacity + needed_extra_capacity <= new_cap`
535             // (regardless of whether `self.cap - used_capacity` wrapped).
536             // Therefore, we can safely call `grow_in_place`.
537
538             let new_layout = Layout::new::<T>().repeat(new_cap).unwrap().0;
539             // FIXME: may crash and burn on over-reserve
540             alloc_guard(new_layout.size()).unwrap_or_else(|_| capacity_overflow());
541             match self.a.grow_in_place(
542                 NonNull::from(self.ptr).cast(),
543                 old_layout,
544                 new_layout.size(),
545             ) {
546                 Ok(_) => {
547                     self.cap = new_cap;
548                     true
549                 }
550                 Err(_) => false,
551             }
552         }
553     }
554
555     /// Shrinks the allocation down to the specified amount. If the given amount
556     /// is 0, actually completely deallocates.
557     ///
558     /// # Panics
559     ///
560     /// Panics if the given amount is *larger* than the current capacity.
561     ///
562     /// # Aborts
563     ///
564     /// Aborts on OOM.
565     pub fn shrink_to_fit(&mut self, amount: usize) {
566         let elem_size = mem::size_of::<T>();
567
568         // Set the `cap` because they might be about to promote to a `Box<[T]>`
569         if elem_size == 0 {
570             self.cap = amount;
571             return;
572         }
573
574         // This check is my waterloo; it's the only thing `Vec` wouldn't have to do.
575         assert!(self.cap >= amount, "Tried to shrink to a larger capacity");
576
577         if amount == 0 {
578             // We want to create a new zero-length vector within the
579             // same allocator. We use `ptr::write` to avoid an
580             // erroneous attempt to drop the contents, and we use
581             // `ptr::read` to sidestep condition against destructuring
582             // types that implement Drop.
583
584             unsafe {
585                 let a = ptr::read(&self.a as *const A);
586                 self.dealloc_buffer();
587                 ptr::write(self, RawVec::new_in(a));
588             }
589         } else if self.cap != amount {
590             unsafe {
591                 // We know here that our `amount` is greater than zero. This
592                 // implies, via the assert above, that capacity is also greater
593                 // than zero, which means that we've got a current layout that
594                 // "fits"
595                 //
596                 // We also know that `self.cap` is greater than `amount`, and
597                 // consequently we don't need runtime checks for creating either
598                 // layout.
599                 let old_size = elem_size * self.cap;
600                 let new_size = elem_size * amount;
601                 let align = mem::align_of::<T>();
602                 let old_layout = Layout::from_size_align_unchecked(old_size, align);
603                 match self.a.realloc(NonNull::from(self.ptr).cast(), old_layout, new_size) {
604                     Ok((ptr, _)) => self.ptr = ptr.cast().into(),
605                     Err(_) => {
606                         handle_alloc_error(Layout::from_size_align_unchecked(new_size, align))
607                     }
608                 }
609             }
610             self.cap = amount;
611         }
612     }
613 }
614
615 enum Fallibility {
616     Fallible,
617     Infallible,
618 }
619
620 use Fallibility::*;
621
622 enum ReserveStrategy {
623     Exact,
624     Amortized,
625 }
626
627 use ReserveStrategy::*;
628
629 impl<T, A: AllocRef> RawVec<T, A> {
630     fn reserve_internal(
631         &mut self,
632         used_capacity: usize,
633         needed_extra_capacity: usize,
634         fallibility: Fallibility,
635         strategy: ReserveStrategy,
636     ) -> Result<(), TryReserveError> {
637         let elem_size = mem::size_of::<T>();
638
639         unsafe {
640             // NOTE: we don't early branch on ZSTs here because we want this
641             // to actually catch "asking for more than usize::MAX" in that case.
642             // If we make it past the first branch then we are guaranteed to
643             // panic.
644
645             // Don't actually need any more capacity.
646             // Wrapping in case they gave a bad `used_capacity`.
647             if self.capacity().wrapping_sub(used_capacity) >= needed_extra_capacity {
648                 return Ok(());
649             }
650
651             // Nothing we can really do about these checks, sadly.
652             let new_cap = match strategy {
653                 Exact => {
654                     used_capacity.checked_add(needed_extra_capacity).ok_or(CapacityOverflow)?
655                 }
656                 Amortized => self.amortized_new_size(used_capacity, needed_extra_capacity)?,
657             };
658             let new_layout = Layout::array::<T>(new_cap).map_err(|_| CapacityOverflow)?;
659
660             alloc_guard(new_layout.size())?;
661
662             let res = match self.current_layout() {
663                 Some(layout) => {
664                     debug_assert!(new_layout.align() == layout.align());
665                     self.a.realloc(NonNull::from(self.ptr).cast(), layout, new_layout.size())
666                 }
667                 None => self.a.alloc(new_layout),
668             };
669
670             let (ptr, new_cap) = match (res, fallibility) {
671                 (Err(AllocErr), Infallible) => handle_alloc_error(new_layout),
672                 (Err(AllocErr), Fallible) => {
673                     return Err(TryReserveError::AllocError {
674                         layout: new_layout,
675                         non_exhaustive: (),
676                     });
677                 }
678                 (Ok((ptr, new_size)), _) => (ptr, new_size / elem_size),
679             };
680
681             self.ptr = ptr.cast().into();
682             self.cap = new_cap;
683
684             Ok(())
685         }
686     }
687 }
688
689 impl<T> RawVec<T, Global> {
690     /// Converts the entire buffer into `Box<[T]>`.
691     ///
692     /// Note that this will correctly reconstitute any `cap` changes
693     /// that may have been performed. (See description of type for details.)
694     ///
695     /// # Undefined Behavior
696     ///
697     /// All elements of `RawVec<T, Global>` must be initialized. Notice that
698     /// the rules around uninitialized boxed values are not finalized yet,
699     /// but until they are, it is advisable to avoid them.
700     pub unsafe fn into_box(self) -> Box<[T]> {
701         // NOTE: not calling `capacity()` here; actually using the real `cap` field!
702         let slice = slice::from_raw_parts_mut(self.ptr(), self.cap);
703         let output: Box<[T]> = Box::from_raw(slice);
704         mem::forget(self);
705         output
706     }
707 }
708
709 impl<T, A: AllocRef> RawVec<T, A> {
710     /// Frees the memory owned by the `RawVec` *without* trying to drop its contents.
711     pub unsafe fn dealloc_buffer(&mut self) {
712         let elem_size = mem::size_of::<T>();
713         if elem_size != 0 {
714             if let Some(layout) = self.current_layout() {
715                 self.a.dealloc(NonNull::from(self.ptr).cast(), layout);
716             }
717         }
718     }
719 }
720
721 unsafe impl<#[may_dangle] T, A: AllocRef> Drop for RawVec<T, A> {
722     /// Frees the memory owned by the `RawVec` *without* trying to drop its contents.
723     fn drop(&mut self) {
724         unsafe {
725             self.dealloc_buffer();
726         }
727     }
728 }
729
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.
733 //
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.
738
739 #[inline]
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)
743     } else {
744         Ok(())
745     }
746 }
747
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");
753 }