1 #![unstable(feature = "raw_vec_internals", reason = "implementation detail", issue = "0")]
7 use core::ptr::{self, NonNull, Unique};
10 use alloc::{Alloc, Layout, Global, handle_alloc_error};
11 use collections::CollectionAllocErr;
12 use collections::CollectionAllocErr::*;
15 /// A low-level utility for more ergonomically allocating, reallocating, and deallocating
16 /// a buffer of memory on the heap without having to worry about all the corner cases
17 /// involved. This type is excellent for building your own data structures like Vec and VecDeque.
20 /// * Produces Unique::empty() on zero-sized types
21 /// * Produces Unique::empty() on zero-length allocations
22 /// * Catches all overflows in capacity computations (promotes them to "capacity overflow" panics)
23 /// * Guards against 32-bit systems allocating more than isize::MAX bytes
24 /// * Guards against overflowing your length
25 /// * Aborts on OOM or calls handle_alloc_error as applicable
26 /// * Avoids freeing Unique::empty()
27 /// * Contains a ptr::Unique and thus endows the user with all related benefits
29 /// This type does not in anyway inspect the memory that it manages. When dropped it *will*
30 /// free its memory, but it *won't* try to Drop its contents. It is up to the user of RawVec
31 /// to handle the actual things *stored* inside of a RawVec.
33 /// Note that a RawVec always forces its capacity to be usize::MAX for zero-sized types.
34 /// This enables you to use capacity growing logic catch the overflows in your length
35 /// that might occur with zero-sized types.
37 /// However this means that you need to be careful when round-tripping this type
38 /// with a `Box<[T]>`: `cap()` won't yield the len. However `with_capacity`,
39 /// `shrink_to_fit`, and `from_box` will actually set RawVec's private capacity
40 /// field. This allows zero-sized types to not be special-cased by consumers of
42 #[allow(missing_debug_implementations)]
43 pub struct RawVec<T, A: Alloc = Global> {
49 impl<T, A: Alloc> RawVec<T, A> {
50 /// Like `new` but parameterized over the choice of allocator for
51 /// the returned RawVec.
52 pub const fn new_in(a: A) -> Self {
53 // !0 is usize::MAX. This branch should be stripped at compile time.
54 // FIXME(mark-i-m): use this line when `if`s are allowed in `const`
55 //let cap = if mem::size_of::<T>() == 0 { !0 } else { 0 };
57 // Unique::empty() doubles as "unallocated" and "zero-sized allocation"
60 // FIXME(mark-i-m): use `cap` when ifs are allowed in const
61 cap: [0, !0][(mem::size_of::<T>() == 0) as usize],
66 /// Like `with_capacity` but parameterized over the choice of
67 /// allocator for the returned RawVec.
69 pub fn with_capacity_in(cap: usize, a: A) -> Self {
70 RawVec::allocate_in(cap, false, a)
73 /// Like `with_capacity_zeroed` but parameterized over the choice
74 /// of allocator for the returned RawVec.
76 pub fn with_capacity_zeroed_in(cap: usize, a: A) -> Self {
77 RawVec::allocate_in(cap, true, a)
80 fn allocate_in(cap: usize, zeroed: bool, mut a: A) -> Self {
82 let elem_size = mem::size_of::<T>();
84 let alloc_size = cap.checked_mul(elem_size).unwrap_or_else(|| capacity_overflow());
85 alloc_guard(alloc_size).unwrap_or_else(|_| capacity_overflow());
87 // handles ZSTs and `cap = 0` alike
88 let ptr = if alloc_size == 0 {
89 NonNull::<T>::dangling()
91 let align = mem::align_of::<T>();
92 let layout = Layout::from_size_align(alloc_size, align).unwrap();
93 let result = if zeroed {
94 a.alloc_zeroed(layout)
99 Ok(ptr) => ptr.cast(),
100 Err(_) => handle_alloc_error(layout),
113 impl<T> RawVec<T, Global> {
114 /// Creates the biggest possible RawVec (on the system heap)
115 /// without allocating. If T has positive size, then this makes a
116 /// RawVec with capacity 0. If T has 0 size, then it makes a
117 /// RawVec with capacity `usize::MAX`. Useful for implementing
118 /// delayed allocation.
119 pub const fn new() -> Self {
123 /// Creates a RawVec (on the system heap) with exactly the
124 /// capacity and alignment requirements for a `[T; cap]`. This is
125 /// equivalent to calling RawVec::new when `cap` is 0 or T is
126 /// zero-sized. Note that if `T` is zero-sized this means you will
127 /// *not* get a RawVec with the requested capacity!
131 /// * Panics if the requested capacity exceeds `usize::MAX` bytes.
132 /// * Panics on 32-bit platforms if the requested capacity exceeds
133 /// `isize::MAX` bytes.
139 pub fn with_capacity(cap: usize) -> Self {
140 RawVec::allocate_in(cap, false, Global)
143 /// Like `with_capacity` but guarantees the buffer is zeroed.
145 pub fn with_capacity_zeroed(cap: usize) -> Self {
146 RawVec::allocate_in(cap, true, Global)
150 impl<T, A: Alloc> RawVec<T, A> {
151 /// Reconstitutes a RawVec from a pointer, capacity, and allocator.
153 /// # Undefined Behavior
155 /// The ptr must be allocated (via the given allocator `a`), and with the given capacity. The
156 /// capacity cannot exceed `isize::MAX` (only a concern on 32-bit systems).
157 /// If the ptr and capacity come from a RawVec created via `a`, then this is guaranteed.
158 pub unsafe fn from_raw_parts_in(ptr: *mut T, cap: usize, a: A) -> Self {
160 ptr: Unique::new_unchecked(ptr),
167 impl<T> RawVec<T, Global> {
168 /// Reconstitutes a RawVec from a pointer, capacity.
170 /// # Undefined Behavior
172 /// The ptr must be allocated (on the system heap), and with the given capacity. The
173 /// capacity cannot exceed `isize::MAX` (only a concern on 32-bit systems).
174 /// If the ptr and capacity come from a RawVec, then this is guaranteed.
175 pub unsafe fn from_raw_parts(ptr: *mut T, cap: usize) -> Self {
177 ptr: Unique::new_unchecked(ptr),
183 /// Converts a `Box<[T]>` into a `RawVec<T>`.
184 pub fn from_box(mut slice: Box<[T]>) -> Self {
186 let result = RawVec::from_raw_parts(slice.as_mut_ptr(), slice.len());
193 impl<T, A: Alloc> RawVec<T, A> {
194 /// Gets a raw pointer to the start of the allocation. Note that this is
195 /// Unique::empty() if `cap = 0` or T is zero-sized. In the former case, you must
197 pub fn ptr(&self) -> *mut T {
201 /// Gets the capacity of the allocation.
203 /// This will always be `usize::MAX` if `T` is zero-sized.
205 pub fn cap(&self) -> usize {
206 if mem::size_of::<T>() == 0 {
213 /// Returns a shared reference to the allocator backing this RawVec.
214 pub fn alloc(&self) -> &A {
218 /// Returns a mutable reference to the allocator backing this RawVec.
219 pub fn alloc_mut(&mut self) -> &mut A {
223 fn current_layout(&self) -> Option<Layout> {
227 // We have an allocated chunk of memory, so we can bypass runtime
228 // checks to get our current layout.
230 let align = mem::align_of::<T>();
231 let size = mem::size_of::<T>() * self.cap;
232 Some(Layout::from_size_align_unchecked(size, align))
237 /// Doubles the size of the type's backing allocation. This is common enough
238 /// to want to do that it's easiest to just have a dedicated method. Slightly
239 /// more efficient logic can be provided for this than the general case.
241 /// This function is ideal for when pushing elements one-at-a-time because
242 /// you don't need to incur the costs of the more general computations
243 /// reserve needs to do to guard against overflow. You do however need to
244 /// manually check if your `len == cap`.
248 /// * Panics if T is zero-sized on the assumption that you managed to exhaust
249 /// all `usize::MAX` slots in your imaginary buffer.
250 /// * Panics on 32-bit platforms if the requested capacity exceeds
251 /// `isize::MAX` bytes.
260 /// # #![feature(alloc, raw_vec_internals)]
261 /// # extern crate alloc;
263 /// # use alloc::raw_vec::RawVec;
264 /// struct MyVec<T> {
269 /// impl<T> MyVec<T> {
270 /// pub fn push(&mut self, elem: T) {
271 /// if self.len == self.buf.cap() { self.buf.double(); }
272 /// // double would have aborted or panicked if the len exceeded
273 /// // `isize::MAX` so this is safe to do unchecked now.
275 /// ptr::write(self.buf.ptr().add(self.len), elem);
281 /// # let mut vec = MyVec { buf: RawVec::new(), len: 0 };
287 pub fn double(&mut self) {
289 let elem_size = mem::size_of::<T>();
291 // since we set the capacity to usize::MAX when elem_size is
292 // 0, getting to here necessarily means the RawVec is overfull.
293 assert!(elem_size != 0, "capacity overflow");
295 let (new_cap, uniq) = match self.current_layout() {
297 // Since we guarantee that we never allocate more than
298 // isize::MAX bytes, `elem_size * self.cap <= isize::MAX` as
299 // a precondition, so this can't overflow. Additionally the
300 // alignment will never be too large as to "not be
301 // satisfiable", so `Layout::from_size_align` will always
304 // tl;dr; we bypass runtime checks due to dynamic assertions
305 // in this module, allowing us to use
306 // `from_size_align_unchecked`.
307 let new_cap = 2 * self.cap;
308 let new_size = new_cap * elem_size;
309 alloc_guard(new_size).unwrap_or_else(|_| capacity_overflow());
310 let ptr_res = self.a.realloc(NonNull::from(self.ptr).cast(),
314 Ok(ptr) => (new_cap, ptr.cast().into()),
315 Err(_) => handle_alloc_error(
316 Layout::from_size_align_unchecked(new_size, cur.align())
321 // skip to 4 because tiny Vec's are dumb; but not if that
322 // would cause overflow
323 let new_cap = if elem_size > (!0) / 8 { 1 } else { 4 };
324 match self.a.alloc_array::<T>(new_cap) {
325 Ok(ptr) => (new_cap, ptr.into()),
326 Err(_) => handle_alloc_error(Layout::array::<T>(new_cap).unwrap()),
335 /// Attempts to double the size of the type's backing allocation in place. This is common
336 /// enough to want to do that it's easiest to just have a dedicated method. Slightly
337 /// more efficient logic can be provided for this than the general case.
339 /// Returns true if the reallocation attempt has succeeded, or false otherwise.
343 /// * Panics if T is zero-sized on the assumption that you managed to exhaust
344 /// all `usize::MAX` slots in your imaginary buffer.
345 /// * Panics on 32-bit platforms if the requested capacity exceeds
346 /// `isize::MAX` bytes.
349 pub fn double_in_place(&mut self) -> bool {
351 let elem_size = mem::size_of::<T>();
352 let old_layout = match self.current_layout() {
353 Some(layout) => layout,
354 None => return false, // nothing to double
357 // since we set the capacity to usize::MAX when elem_size is
358 // 0, getting to here necessarily means the RawVec is overfull.
359 assert!(elem_size != 0, "capacity overflow");
361 // Since we guarantee that we never allocate more than isize::MAX
362 // bytes, `elem_size * self.cap <= isize::MAX` as a precondition, so
363 // this can't overflow.
365 // Similarly like with `double` above we can go straight to
366 // `Layout::from_size_align_unchecked` as we know this won't
367 // overflow and the alignment is sufficiently small.
368 let new_cap = 2 * self.cap;
369 let new_size = new_cap * elem_size;
370 alloc_guard(new_size).unwrap_or_else(|_| capacity_overflow());
371 match self.a.grow_in_place(NonNull::from(self.ptr).cast(), old_layout, new_size) {
373 // We can't directly divide `size`.
384 /// The same as `reserve_exact`, but returns on errors instead of panicking or aborting.
385 pub fn try_reserve_exact(&mut self, used_cap: usize, needed_extra_cap: usize)
386 -> Result<(), CollectionAllocErr> {
388 self.reserve_internal(used_cap, needed_extra_cap, Fallible, Exact)
391 /// Ensures that the buffer contains at least enough space to hold
392 /// `used_cap + needed_extra_cap` elements. If it doesn't already,
393 /// will reallocate the minimum possible amount of memory necessary.
394 /// Generally this will be exactly the amount of memory necessary,
395 /// but in principle the allocator is free to give back more than
398 /// If `used_cap` exceeds `self.cap()`, this may fail to actually allocate
399 /// the requested space. This is not really unsafe, but the unsafe
400 /// code *you* write that relies on the behavior of this function may break.
404 /// * Panics if the requested capacity exceeds `usize::MAX` bytes.
405 /// * Panics on 32-bit platforms if the requested capacity exceeds
406 /// `isize::MAX` bytes.
411 pub fn reserve_exact(&mut self, used_cap: usize, needed_extra_cap: usize) {
412 match self.reserve_internal(used_cap, needed_extra_cap, Infallible, Exact) {
413 Err(CapacityOverflow) => capacity_overflow(),
414 Err(AllocErr) => unreachable!(),
415 Ok(()) => { /* yay */ }
419 /// Calculates the buffer's new size given that it'll hold `used_cap +
420 /// needed_extra_cap` elements. This logic is used in amortized reserve methods.
421 /// Returns `(new_capacity, new_alloc_size)`.
422 fn amortized_new_size(&self, used_cap: usize, needed_extra_cap: usize)
423 -> Result<usize, CollectionAllocErr> {
425 // Nothing we can really do about these checks :(
426 let required_cap = used_cap.checked_add(needed_extra_cap).ok_or(CapacityOverflow)?;
427 // Cannot overflow, because `cap <= isize::MAX`, and type of `cap` is `usize`.
428 let double_cap = self.cap * 2;
429 // `double_cap` guarantees exponential growth.
430 Ok(cmp::max(double_cap, required_cap))
433 /// The same as `reserve`, but returns on errors instead of panicking or aborting.
434 pub fn try_reserve(&mut self, used_cap: usize, needed_extra_cap: usize)
435 -> Result<(), CollectionAllocErr> {
436 self.reserve_internal(used_cap, needed_extra_cap, Fallible, Amortized)
439 /// Ensures that the buffer contains at least enough space to hold
440 /// `used_cap + needed_extra_cap` elements. If it doesn't already have
441 /// enough capacity, will reallocate enough space plus comfortable slack
442 /// space to get amortized `O(1)` behavior. Will limit this behavior
443 /// if it would needlessly cause itself to panic.
445 /// If `used_cap` exceeds `self.cap()`, this may fail to actually allocate
446 /// the requested space. This is not really unsafe, but the unsafe
447 /// code *you* write that relies on the behavior of this function may break.
449 /// This is ideal for implementing a bulk-push operation like `extend`.
453 /// * Panics if the requested capacity exceeds `usize::MAX` bytes.
454 /// * Panics on 32-bit platforms if the requested capacity exceeds
455 /// `isize::MAX` bytes.
464 /// # #![feature(alloc, raw_vec_internals)]
465 /// # extern crate alloc;
467 /// # use alloc::raw_vec::RawVec;
468 /// struct MyVec<T> {
473 /// impl<T: Clone> MyVec<T> {
474 /// pub fn push_all(&mut self, elems: &[T]) {
475 /// self.buf.reserve(self.len, elems.len());
476 /// // reserve would have aborted or panicked if the len exceeded
477 /// // `isize::MAX` so this is safe to do unchecked now.
480 /// ptr::write(self.buf.ptr().add(self.len), x.clone());
487 /// # let mut vector = MyVec { buf: RawVec::new(), len: 0 };
488 /// # vector.push_all(&[1, 3, 5, 7, 9]);
491 pub fn reserve(&mut self, used_cap: usize, needed_extra_cap: usize) {
492 match self.reserve_internal(used_cap, needed_extra_cap, Infallible, Amortized) {
493 Err(CapacityOverflow) => capacity_overflow(),
494 Err(AllocErr) => unreachable!(),
495 Ok(()) => { /* yay */ }
498 /// Attempts to ensure that the buffer contains at least enough space to hold
499 /// `used_cap + needed_extra_cap` elements. If it doesn't already have
500 /// enough capacity, will reallocate in place enough space plus comfortable slack
501 /// space to get amortized `O(1)` behavior. Will limit this behaviour
502 /// if it would needlessly cause itself to panic.
504 /// If `used_cap` exceeds `self.cap()`, this may fail to actually allocate
505 /// the requested space. This is not really unsafe, but the unsafe
506 /// code *you* write that relies on the behavior of this function may break.
508 /// Returns true if the reallocation attempt has succeeded, or false otherwise.
512 /// * Panics if the requested capacity exceeds `usize::MAX` bytes.
513 /// * Panics on 32-bit platforms if the requested capacity exceeds
514 /// `isize::MAX` bytes.
515 pub fn reserve_in_place(&mut self, used_cap: usize, needed_extra_cap: usize) -> bool {
517 // NOTE: we don't early branch on ZSTs here because we want this
518 // to actually catch "asking for more than usize::MAX" in that case.
519 // If we make it past the first branch then we are guaranteed to
522 // Don't actually need any more capacity. If the current `cap` is 0, we can't
523 // reallocate in place.
524 // Wrapping in case they give a bad `used_cap`
525 let old_layout = match self.current_layout() {
526 Some(layout) => layout,
527 None => return false,
529 if self.cap().wrapping_sub(used_cap) >= needed_extra_cap {
533 let new_cap = self.amortized_new_size(used_cap, needed_extra_cap)
534 .unwrap_or_else(|_| capacity_overflow());
536 // Here, `cap < used_cap + needed_extra_cap <= new_cap`
537 // (regardless of whether `self.cap - used_cap` wrapped).
538 // Therefore we can safely call grow_in_place.
540 let new_layout = Layout::new::<T>().repeat(new_cap).unwrap().0;
541 // FIXME: may crash and burn on over-reserve
542 alloc_guard(new_layout.size()).unwrap_or_else(|_| capacity_overflow());
543 match self.a.grow_in_place(
544 NonNull::from(self.ptr).cast(), old_layout, new_layout.size(),
557 /// Shrinks the allocation down to the specified amount. If the given amount
558 /// is 0, actually completely deallocates.
562 /// Panics if the given amount is *larger* than the current capacity.
567 pub fn shrink_to_fit(&mut self, amount: usize) {
568 let elem_size = mem::size_of::<T>();
570 // Set the `cap` because they might be about to promote to a `Box<[T]>`
576 // This check is my waterloo; it's the only thing Vec wouldn't have to do.
577 assert!(self.cap >= amount, "Tried to shrink to a larger capacity");
580 // We want to create a new zero-length vector within the
581 // same allocator. We use ptr::write to avoid an
582 // erroneous attempt to drop the contents, and we use
583 // ptr::read to sidestep condition against destructuring
584 // types that implement Drop.
587 let a = ptr::read(&self.a as *const A);
588 self.dealloc_buffer();
589 ptr::write(self, RawVec::new_in(a));
591 } else if self.cap != amount {
593 // We know here that our `amount` is greater than zero. This
594 // implies, via the assert above, that capacity is also greater
595 // than zero, which means that we've got a current layout that
598 // We also know that `self.cap` is greater than `amount`, and
599 // consequently we don't need runtime checks for creating either
601 let old_size = elem_size * self.cap;
602 let new_size = elem_size * amount;
603 let align = mem::align_of::<T>();
604 let old_layout = Layout::from_size_align_unchecked(old_size, align);
605 match self.a.realloc(NonNull::from(self.ptr).cast(),
608 Ok(p) => self.ptr = p.cast().into(),
609 Err(_) => handle_alloc_error(
610 Layout::from_size_align_unchecked(new_size, align)
624 use self::Fallibility::*;
626 enum ReserveStrategy {
631 use self::ReserveStrategy::*;
633 impl<T, A: Alloc> RawVec<T, A> {
637 needed_extra_cap: usize,
638 fallibility: Fallibility,
639 strategy: ReserveStrategy,
640 ) -> Result<(), CollectionAllocErr> {
644 // NOTE: we don't early branch on ZSTs here because we want this
645 // to actually catch "asking for more than usize::MAX" in that case.
646 // If we make it past the first branch then we are guaranteed to
649 // Don't actually need any more capacity.
650 // Wrapping in case they gave a bad `used_cap`.
651 if self.cap().wrapping_sub(used_cap) >= needed_extra_cap {
655 // Nothing we can really do about these checks :(
656 let new_cap = match strategy {
657 Exact => used_cap.checked_add(needed_extra_cap).ok_or(CapacityOverflow)?,
658 Amortized => self.amortized_new_size(used_cap, needed_extra_cap)?,
660 let new_layout = Layout::array::<T>(new_cap).map_err(|_| CapacityOverflow)?;
662 alloc_guard(new_layout.size())?;
664 let res = match self.current_layout() {
666 debug_assert!(new_layout.align() == layout.align());
667 self.a.realloc(NonNull::from(self.ptr).cast(), layout, new_layout.size())
669 None => self.a.alloc(new_layout),
672 match (&res, fallibility) {
673 (Err(AllocErr), Infallible) => handle_alloc_error(new_layout),
677 self.ptr = res?.cast().into();
686 impl<T> RawVec<T, Global> {
687 /// Converts the entire buffer into `Box<[T]>`.
689 /// While it is not *strictly* Undefined Behavior to call
690 /// this procedure while some of the RawVec is uninitialized,
691 /// it certainly makes it trivial to trigger it.
693 /// Note that this will correctly reconstitute any `cap` changes
694 /// that may have been performed. (see description of type for details)
695 pub unsafe fn into_box(self) -> Box<[T]> {
696 // NOTE: not calling `cap()` here, actually using the real `cap` field!
697 let slice = slice::from_raw_parts_mut(self.ptr(), self.cap);
698 let output: Box<[T]> = Box::from_raw(slice);
704 impl<T, A: Alloc> RawVec<T, A> {
705 /// Frees the memory owned by the RawVec *without* trying to Drop its contents.
706 pub unsafe fn dealloc_buffer(&mut self) {
707 let elem_size = mem::size_of::<T>();
709 if let Some(layout) = self.current_layout() {
710 self.a.dealloc(NonNull::from(self.ptr).cast(), layout);
716 unsafe impl<#[may_dangle] T, A: Alloc> Drop for RawVec<T, A> {
717 /// Frees the memory owned by the RawVec *without* trying to Drop its contents.
719 unsafe { self.dealloc_buffer(); }
725 // We need to guarantee the following:
726 // * We don't ever allocate `> isize::MAX` byte-size objects
727 // * We don't overflow `usize::MAX` and actually allocate too little
729 // On 64-bit we just need to check for overflow since trying to allocate
730 // `> isize::MAX` bytes will surely fail. On 32-bit and 16-bit we need to add
731 // an extra guard for this in case we're running on a platform which can use
732 // all 4GB in user-space. e.g., PAE or x32
735 fn alloc_guard(alloc_size: usize) -> Result<(), CollectionAllocErr> {
736 if mem::size_of::<usize>() < 8 && alloc_size > ::core::isize::MAX as usize {
737 Err(CapacityOverflow)
743 // One central function responsible for reporting capacity overflows. This'll
744 // ensure that the code generation related to these panics is minimal as there's
745 // only one location which panics rather than a bunch throughout the module.
746 fn capacity_overflow() -> ! {
747 panic!("capacity overflow")
755 fn allocator_param() {
758 // Writing a test of integration between third-party
759 // allocators and RawVec is a little tricky because the RawVec
760 // API does not expose fallible allocation methods, so we
761 // cannot check what happens when allocator is exhausted
762 // (beyond detecting a panic).
764 // Instead, this just checks that the RawVec methods do at
765 // least go through the Allocator API when it reserves
768 // A dumb allocator that consumes a fixed amount of fuel
769 // before allocation attempts start failing.
770 struct BoundedAlloc { fuel: usize }
771 unsafe impl Alloc for BoundedAlloc {
772 unsafe fn alloc(&mut self, layout: Layout) -> Result<NonNull<u8>, AllocErr> {
773 let size = layout.size();
774 if size > self.fuel {
775 return Err(AllocErr);
777 match Global.alloc(layout) {
778 ok @ Ok(_) => { self.fuel -= size; ok }
782 unsafe fn dealloc(&mut self, ptr: NonNull<u8>, layout: Layout) {
783 Global.dealloc(ptr, layout)
787 let a = BoundedAlloc { fuel: 500 };
788 let mut v: RawVec<u8, _> = RawVec::with_capacity_in(50, a);
789 assert_eq!(v.a.fuel, 450);
790 v.reserve(50, 150); // (causes a realloc, thus using 50 + 150 = 200 units of fuel)
791 assert_eq!(v.a.fuel, 250);
795 fn reserve_does_not_overallocate() {
797 let mut v: RawVec<u32> = RawVec::new();
798 // First `reserve` allocates like `reserve_exact`
800 assert_eq!(9, v.cap());
804 let mut v: RawVec<u32> = RawVec::new();
806 assert_eq!(7, v.cap());
807 // 97 if more than double of 7, so `reserve` should work
808 // like `reserve_exact`.
810 assert_eq!(97, v.cap());
814 let mut v: RawVec<u32> = RawVec::new();
816 assert_eq!(12, v.cap());
818 // 3 is less than half of 12, so `reserve` must grow
819 // exponentially. At the time of writing this test grow
820 // factor is 2, so new capacity is 24, however, grow factor
821 // of 1.5 is OK too. Hence `>= 18` in assert.
822 assert!(v.cap() >= 12 + 12 / 2);