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