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