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