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