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