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