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.
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.
11 #![unstable(feature = "raw_vec_internals", reason = "implementation detail", issue = "0")]
17 use core::ptr::{self, NonNull, Unique};
20 use alloc::{Alloc, Layout, Global, handle_alloc_error};
21 use collections::CollectionAllocErr;
22 use collections::CollectionAllocErr::*;
25 /// A low-level utility for more ergonomically allocating, reallocating, and deallocating
26 /// a buffer of memory on the heap without having to worry about all the corner cases
27 /// involved. This type is excellent for building your own data structures like Vec and VecDeque.
30 /// * Produces Unique::empty() on zero-sized types
31 /// * Produces Unique::empty() on zero-length allocations
32 /// * Catches all overflows in capacity computations (promotes them to "capacity overflow" panics)
33 /// * Guards against 32-bit systems allocating more than isize::MAX bytes
34 /// * Guards against overflowing your length
36 /// * Avoids freeing Unique::empty()
37 /// * Contains a ptr::Unique and thus endows the user with all related benefits
39 /// This type does not in anyway inspect the memory that it manages. When dropped it *will*
40 /// free its memory, but it *won't* try to Drop its contents. It is up to the user of RawVec
41 /// to handle the actual things *stored* inside of a RawVec.
43 /// Note that a RawVec always forces its capacity to be usize::MAX for zero-sized types.
44 /// This enables you to use capacity growing logic catch the overflows in your length
45 /// that might occur with zero-sized types.
47 /// However this means that you need to be careful when round-tripping this type
48 /// with a `Box<[T]>`: `cap()` won't yield the len. However `with_capacity`,
49 /// `shrink_to_fit`, and `from_box` will actually set RawVec's private capacity
50 /// field. This allows zero-sized types to not be special-cased by consumers of
52 #[allow(missing_debug_implementations)]
53 pub struct RawVec<T, A: Alloc = Global> {
59 impl<T, A: Alloc> RawVec<T, A> {
60 /// Like `new` but parameterized over the choice of allocator for
61 /// the returned RawVec.
62 pub const fn new_in(a: A) -> Self {
63 // !0 is usize::MAX. This branch should be stripped at compile time.
64 // FIXME(mark-i-m): use this line when `if`s are allowed in `const`
65 //let cap = if mem::size_of::<T>() == 0 { !0 } else { 0 };
67 // Unique::empty() doubles as "unallocated" and "zero-sized allocation"
70 // FIXME(mark-i-m): use `cap` when ifs are allowed in const
71 cap: [0, !0][(mem::size_of::<T>() == 0) as usize],
76 /// Like `with_capacity` but parameterized over the choice of
77 /// allocator for the returned RawVec.
79 pub fn with_capacity_in(cap: usize, a: A) -> Self {
80 RawVec::allocate_in(cap, false, a)
83 /// Like `with_capacity_zeroed` but parameterized over the choice
84 /// of allocator for the returned RawVec.
86 pub fn with_capacity_zeroed_in(cap: usize, a: A) -> Self {
87 RawVec::allocate_in(cap, true, a)
90 fn allocate_in(cap: usize, zeroed: bool, mut a: A) -> Self {
92 let elem_size = mem::size_of::<T>();
94 let alloc_size = cap.checked_mul(elem_size).unwrap_or_else(|| capacity_overflow());
95 alloc_guard(alloc_size).unwrap_or_else(|_| capacity_overflow());
97 // handles ZSTs and `cap = 0` alike
98 let ptr = if alloc_size == 0 {
99 NonNull::<T>::dangling()
101 let align = mem::align_of::<T>();
102 let layout = Layout::from_size_align(alloc_size, align).unwrap();
103 let result = if zeroed {
104 a.alloc_zeroed(layout)
109 Ok(ptr) => ptr.cast(),
110 Err(_) => handle_alloc_error(layout),
123 impl<T> RawVec<T, Global> {
124 /// Creates the biggest possible RawVec (on the system heap)
125 /// without allocating. If T has positive size, then this makes a
126 /// RawVec with capacity 0. If T has 0 size, then it makes a
127 /// RawVec with capacity `usize::MAX`. Useful for implementing
128 /// delayed allocation.
129 pub const fn new() -> Self {
133 /// Creates a RawVec (on the system heap) with exactly the
134 /// capacity and alignment requirements for a `[T; cap]`. This is
135 /// equivalent to calling RawVec::new when `cap` is 0 or T is
136 /// zero-sized. Note that if `T` is zero-sized this means you will
137 /// *not* get a RawVec with the requested capacity!
141 /// * Panics if the requested capacity exceeds `usize::MAX` bytes.
142 /// * Panics on 32-bit platforms if the requested capacity exceeds
143 /// `isize::MAX` bytes.
149 pub fn with_capacity(cap: usize) -> Self {
150 RawVec::allocate_in(cap, false, Global)
153 /// Like `with_capacity` but guarantees the buffer is zeroed.
155 pub fn with_capacity_zeroed(cap: usize) -> Self {
156 RawVec::allocate_in(cap, true, Global)
160 impl<T, A: Alloc> RawVec<T, A> {
161 /// Reconstitutes a RawVec from a pointer, capacity, and allocator.
163 /// # Undefined Behavior
165 /// The ptr must be allocated (via the given allocator `a`), and with the given capacity. The
166 /// capacity cannot exceed `isize::MAX` (only a concern on 32-bit systems).
167 /// If the ptr and capacity come from a RawVec created via `a`, then this is guaranteed.
168 pub unsafe fn from_raw_parts_in(ptr: *mut T, cap: usize, a: A) -> Self {
170 ptr: Unique::new_unchecked(ptr),
177 impl<T> RawVec<T, Global> {
178 /// Reconstitutes a RawVec from a pointer, capacity.
180 /// # Undefined Behavior
182 /// The ptr must be allocated (on the system heap), and with the given capacity. The
183 /// capacity cannot exceed `isize::MAX` (only a concern on 32-bit systems).
184 /// If the ptr and capacity come from a RawVec, then this is guaranteed.
185 pub unsafe fn from_raw_parts(ptr: *mut T, cap: usize) -> Self {
187 ptr: Unique::new_unchecked(ptr),
193 /// Converts a `Box<[T]>` into a `RawVec<T>`.
194 pub fn from_box(mut slice: Box<[T]>) -> Self {
196 let result = RawVec::from_raw_parts(slice.as_mut_ptr(), slice.len());
203 impl<T, A: Alloc> RawVec<T, A> {
204 /// Gets a raw pointer to the start of the allocation. Note that this is
205 /// Unique::empty() if `cap = 0` or T is zero-sized. In the former case, you must
207 pub fn ptr(&self) -> *mut T {
211 /// Gets the capacity of the allocation.
213 /// This will always be `usize::MAX` if `T` is zero-sized.
215 pub fn cap(&self) -> usize {
216 if mem::size_of::<T>() == 0 {
223 /// Returns a shared reference to the allocator backing this RawVec.
224 pub fn alloc(&self) -> &A {
228 /// Returns a mutable reference to the allocator backing this RawVec.
229 pub fn alloc_mut(&mut self) -> &mut A {
233 fn current_layout(&self) -> Option<Layout> {
237 // We have an allocated chunk of memory, so we can bypass runtime
238 // checks to get our current layout.
240 let align = mem::align_of::<T>();
241 let size = mem::size_of::<T>() * self.cap;
242 Some(Layout::from_size_align_unchecked(size, align))
247 /// Doubles the size of the type's backing allocation. This is common enough
248 /// to want to do that it's easiest to just have a dedicated method. Slightly
249 /// more efficient logic can be provided for this than the general case.
251 /// This function is ideal for when pushing elements one-at-a-time because
252 /// you don't need to incur the costs of the more general computations
253 /// reserve needs to do to guard against overflow. You do however need to
254 /// manually check if your `len == cap`.
258 /// * Panics if T is zero-sized on the assumption that you managed to exhaust
259 /// all `usize::MAX` slots in your imaginary buffer.
260 /// * Panics on 32-bit platforms if the requested capacity exceeds
261 /// `isize::MAX` bytes.
270 /// # #![feature(alloc, raw_vec_internals)]
271 /// # extern crate alloc;
273 /// # use alloc::raw_vec::RawVec;
274 /// struct MyVec<T> {
279 /// impl<T> MyVec<T> {
280 /// pub fn push(&mut self, elem: T) {
281 /// if self.len == self.buf.cap() { self.buf.double(); }
282 /// // double would have aborted or panicked if the len exceeded
283 /// // `isize::MAX` so this is safe to do unchecked now.
285 /// ptr::write(self.buf.ptr().add(self.len), elem);
291 /// # let mut vec = MyVec { buf: RawVec::new(), len: 0 };
297 pub fn double(&mut self) {
299 let elem_size = mem::size_of::<T>();
301 // since we set the capacity to usize::MAX when elem_size is
302 // 0, getting to here necessarily means the RawVec is overfull.
303 assert!(elem_size != 0, "capacity overflow");
305 let (new_cap, uniq) = match self.current_layout() {
307 // Since we guarantee that we never allocate more than
308 // isize::MAX bytes, `elem_size * self.cap <= isize::MAX` as
309 // a precondition, so this can't overflow. Additionally the
310 // alignment will never be too large as to "not be
311 // satisfiable", so `Layout::from_size_align` will always
314 // tl;dr; we bypass runtime checks due to dynamic assertions
315 // in this module, allowing us to use
316 // `from_size_align_unchecked`.
317 let new_cap = 2 * self.cap;
318 let new_size = new_cap * elem_size;
319 alloc_guard(new_size).unwrap_or_else(|_| capacity_overflow());
320 let ptr_res = self.a.realloc(NonNull::from(self.ptr).cast(),
324 Ok(ptr) => (new_cap, ptr.cast().into()),
325 Err(_) => handle_alloc_error(
326 Layout::from_size_align_unchecked(new_size, cur.align())
331 // skip to 4 because tiny Vec's are dumb; but not if that
332 // would cause overflow
333 let new_cap = if elem_size > (!0) / 8 { 1 } else { 4 };
334 match self.a.alloc_array::<T>(new_cap) {
335 Ok(ptr) => (new_cap, ptr.into()),
336 Err(_) => handle_alloc_error(Layout::array::<T>(new_cap).unwrap()),
345 /// Attempts to double the size of the type's backing allocation in place. This is common
346 /// enough to want to do that it's easiest to just have a dedicated method. Slightly
347 /// more efficient logic can be provided for this than the general case.
349 /// Returns true if the reallocation attempt has succeeded, or false otherwise.
353 /// * Panics if T is zero-sized on the assumption that you managed to exhaust
354 /// all `usize::MAX` slots in your imaginary buffer.
355 /// * Panics on 32-bit platforms if the requested capacity exceeds
356 /// `isize::MAX` bytes.
359 pub fn double_in_place(&mut self) -> bool {
361 let elem_size = mem::size_of::<T>();
362 let old_layout = match self.current_layout() {
363 Some(layout) => layout,
364 None => return false, // nothing to double
367 // since we set the capacity to usize::MAX when elem_size is
368 // 0, getting to here necessarily means the RawVec is overfull.
369 assert!(elem_size != 0, "capacity overflow");
371 // Since we guarantee that we never allocate more than isize::MAX
372 // bytes, `elem_size * self.cap <= isize::MAX` as a precondition, so
373 // this can't overflow.
375 // Similarly like with `double` above we can go straight to
376 // `Layout::from_size_align_unchecked` as we know this won't
377 // overflow and the alignment is sufficiently small.
378 let new_cap = 2 * self.cap;
379 let new_size = new_cap * elem_size;
380 alloc_guard(new_size).unwrap_or_else(|_| capacity_overflow());
381 match self.a.grow_in_place(NonNull::from(self.ptr).cast(), old_layout, new_size) {
383 // We can't directly divide `size`.
394 /// The same as `reserve_exact`, but returns on errors instead of panicking or aborting.
395 pub fn try_reserve_exact(&mut self, used_cap: usize, needed_extra_cap: usize)
396 -> Result<(), CollectionAllocErr> {
398 self.reserve_internal(used_cap, needed_extra_cap, Fallible, Exact)
401 /// Ensures that the buffer contains at least enough space to hold
402 /// `used_cap + needed_extra_cap` elements. If it doesn't already,
403 /// will reallocate the minimum possible amount of memory necessary.
404 /// Generally this will be exactly the amount of memory necessary,
405 /// but in principle the allocator is free to give back more than
408 /// If `used_cap` exceeds `self.cap()`, this may fail to actually allocate
409 /// the requested space. This is not really unsafe, but the unsafe
410 /// code *you* write that relies on the behavior of this function may break.
414 /// * Panics if the requested capacity exceeds `usize::MAX` bytes.
415 /// * Panics on 32-bit platforms if the requested capacity exceeds
416 /// `isize::MAX` bytes.
421 pub fn reserve_exact(&mut self, used_cap: usize, needed_extra_cap: usize) {
422 match self.reserve_internal(used_cap, needed_extra_cap, Infallible, Exact) {
423 Err(CapacityOverflow) => capacity_overflow(),
424 Err(AllocErr) => unreachable!(),
425 Ok(()) => { /* yay */ }
429 /// Calculates the buffer's new size given that it'll hold `used_cap +
430 /// needed_extra_cap` elements. This logic is used in amortized reserve methods.
431 /// Returns `(new_capacity, new_alloc_size)`.
432 fn amortized_new_size(&self, used_cap: usize, needed_extra_cap: usize)
433 -> Result<usize, CollectionAllocErr> {
435 // Nothing we can really do about these checks :(
436 let required_cap = used_cap.checked_add(needed_extra_cap).ok_or(CapacityOverflow)?;
437 // Cannot overflow, because `cap <= isize::MAX`, and type of `cap` is `usize`.
438 let double_cap = self.cap * 2;
439 // `double_cap` guarantees exponential growth.
440 Ok(cmp::max(double_cap, required_cap))
443 /// The same as `reserve`, but returns on errors instead of panicking or aborting.
444 pub fn try_reserve(&mut self, used_cap: usize, needed_extra_cap: usize)
445 -> Result<(), CollectionAllocErr> {
446 self.reserve_internal(used_cap, needed_extra_cap, Fallible, Amortized)
449 /// Ensures that the buffer contains at least enough space to hold
450 /// `used_cap + needed_extra_cap` elements. If it doesn't already have
451 /// enough capacity, will reallocate enough space plus comfortable slack
452 /// space to get amortized `O(1)` behavior. Will limit this behavior
453 /// if it would needlessly cause itself to panic.
455 /// If `used_cap` exceeds `self.cap()`, this may fail to actually allocate
456 /// the requested space. This is not really unsafe, but the unsafe
457 /// code *you* write that relies on the behavior of this function may break.
459 /// This is ideal for implementing a bulk-push operation like `extend`.
463 /// * Panics if the requested capacity exceeds `usize::MAX` bytes.
464 /// * Panics on 32-bit platforms if the requested capacity exceeds
465 /// `isize::MAX` bytes.
474 /// # #![feature(alloc, raw_vec_internals)]
475 /// # extern crate alloc;
477 /// # use alloc::raw_vec::RawVec;
478 /// struct MyVec<T> {
483 /// impl<T: Clone> MyVec<T> {
484 /// pub fn push_all(&mut self, elems: &[T]) {
485 /// self.buf.reserve(self.len, elems.len());
486 /// // reserve would have aborted or panicked if the len exceeded
487 /// // `isize::MAX` so this is safe to do unchecked now.
490 /// ptr::write(self.buf.ptr().add(self.len), x.clone());
497 /// # let mut vector = MyVec { buf: RawVec::new(), len: 0 };
498 /// # vector.push_all(&[1, 3, 5, 7, 9]);
501 pub fn reserve(&mut self, used_cap: usize, needed_extra_cap: usize) {
502 match self.reserve_internal(used_cap, needed_extra_cap, Infallible, Amortized) {
503 Err(CapacityOverflow) => capacity_overflow(),
504 Err(AllocErr) => unreachable!(),
505 Ok(()) => { /* yay */ }
508 /// Attempts to ensure that the buffer contains at least enough space to hold
509 /// `used_cap + needed_extra_cap` elements. If it doesn't already have
510 /// enough capacity, will reallocate in place enough space plus comfortable slack
511 /// space to get amortized `O(1)` behavior. Will limit this behaviour
512 /// if it would needlessly cause itself to panic.
514 /// If `used_cap` exceeds `self.cap()`, this may fail to actually allocate
515 /// the requested space. This is not really unsafe, but the unsafe
516 /// code *you* write that relies on the behavior of this function may break.
518 /// Returns true if the reallocation attempt has succeeded, or false otherwise.
522 /// * Panics if the requested capacity exceeds `usize::MAX` bytes.
523 /// * Panics on 32-bit platforms if the requested capacity exceeds
524 /// `isize::MAX` bytes.
525 pub fn reserve_in_place(&mut self, used_cap: usize, needed_extra_cap: usize) -> bool {
527 // NOTE: we don't early branch on ZSTs here because we want this
528 // to actually catch "asking for more than usize::MAX" in that case.
529 // If we make it past the first branch then we are guaranteed to
532 // Don't actually need any more capacity. If the current `cap` is 0, we can't
533 // reallocate in place.
534 // Wrapping in case they give a bad `used_cap`
535 let old_layout = match self.current_layout() {
536 Some(layout) => layout,
537 None => return false,
539 if self.cap().wrapping_sub(used_cap) >= needed_extra_cap {
543 let new_cap = self.amortized_new_size(used_cap, needed_extra_cap)
544 .unwrap_or_else(|_| capacity_overflow());
546 // Here, `cap < used_cap + needed_extra_cap <= new_cap`
547 // (regardless of whether `self.cap - used_cap` wrapped).
548 // Therefore we can safely call grow_in_place.
550 let new_layout = Layout::new::<T>().repeat(new_cap).unwrap().0;
551 // FIXME: may crash and burn on over-reserve
552 alloc_guard(new_layout.size()).unwrap_or_else(|_| capacity_overflow());
553 match self.a.grow_in_place(
554 NonNull::from(self.ptr).cast(), old_layout, new_layout.size(),
567 /// Shrinks the allocation down to the specified amount. If the given amount
568 /// is 0, actually completely deallocates.
572 /// Panics if the given amount is *larger* than the current capacity.
577 pub fn shrink_to_fit(&mut self, amount: usize) {
578 let elem_size = mem::size_of::<T>();
580 // Set the `cap` because they might be about to promote to a `Box<[T]>`
586 // This check is my waterloo; it's the only thing Vec wouldn't have to do.
587 assert!(self.cap >= amount, "Tried to shrink to a larger capacity");
590 // We want to create a new zero-length vector within the
591 // same allocator. We use ptr::write to avoid an
592 // erroneous attempt to drop the contents, and we use
593 // ptr::read to sidestep condition against destructuring
594 // types that implement Drop.
597 let a = ptr::read(&self.a as *const A);
598 self.dealloc_buffer();
599 ptr::write(self, RawVec::new_in(a));
601 } else if self.cap != amount {
603 // We know here that our `amount` is greater than zero. This
604 // implies, via the assert above, that capacity is also greater
605 // than zero, which means that we've got a current layout that
608 // We also know that `self.cap` is greater than `amount`, and
609 // consequently we don't need runtime checks for creating either
611 let old_size = elem_size * self.cap;
612 let new_size = elem_size * amount;
613 let align = mem::align_of::<T>();
614 let old_layout = Layout::from_size_align_unchecked(old_size, align);
615 match self.a.realloc(NonNull::from(self.ptr).cast(),
618 Ok(p) => self.ptr = p.cast().into(),
619 Err(_) => handle_alloc_error(
620 Layout::from_size_align_unchecked(new_size, align)
634 use self::Fallibility::*;
636 enum ReserveStrategy {
641 use self::ReserveStrategy::*;
643 impl<T, A: Alloc> RawVec<T, A> {
647 needed_extra_cap: usize,
648 fallibility: Fallibility,
649 strategy: ReserveStrategy,
650 ) -> Result<(), CollectionAllocErr> {
654 // NOTE: we don't early branch on ZSTs here because we want this
655 // to actually catch "asking for more than usize::MAX" in that case.
656 // If we make it past the first branch then we are guaranteed to
659 // Don't actually need any more capacity.
660 // Wrapping in case they gave a bad `used_cap`.
661 if self.cap().wrapping_sub(used_cap) >= needed_extra_cap {
665 // Nothing we can really do about these checks :(
666 let new_cap = match strategy {
667 Exact => used_cap.checked_add(needed_extra_cap).ok_or(CapacityOverflow)?,
668 Amortized => self.amortized_new_size(used_cap, needed_extra_cap)?,
670 let new_layout = Layout::array::<T>(new_cap).map_err(|_| CapacityOverflow)?;
672 alloc_guard(new_layout.size())?;
674 let res = match self.current_layout() {
676 debug_assert!(new_layout.align() == layout.align());
677 self.a.realloc(NonNull::from(self.ptr).cast(), layout, new_layout.size())
679 None => self.a.alloc(new_layout),
682 match (&res, fallibility) {
683 (Err(AllocErr), Infallible) => handle_alloc_error(new_layout),
687 self.ptr = res?.cast().into();
696 impl<T> RawVec<T, Global> {
697 /// Converts the entire buffer into `Box<[T]>`.
699 /// While it is not *strictly* Undefined Behavior to call
700 /// this procedure while some of the RawVec is uninitialized,
701 /// it certainly makes it trivial to trigger it.
703 /// Note that this will correctly reconstitute any `cap` changes
704 /// that may have been performed. (see description of type for details)
705 pub unsafe fn into_box(self) -> Box<[T]> {
706 // NOTE: not calling `cap()` here, actually using the real `cap` field!
707 let slice = slice::from_raw_parts_mut(self.ptr(), self.cap);
708 let output: Box<[T]> = Box::from_raw(slice);
714 impl<T, A: Alloc> RawVec<T, A> {
715 /// Frees the memory owned by the RawVec *without* trying to Drop its contents.
716 pub unsafe fn dealloc_buffer(&mut self) {
717 let elem_size = mem::size_of::<T>();
719 if let Some(layout) = self.current_layout() {
720 self.a.dealloc(NonNull::from(self.ptr).cast(), layout);
726 unsafe impl<#[may_dangle] T, A: Alloc> Drop for RawVec<T, A> {
727 /// Frees the memory owned by the RawVec *without* trying to Drop its contents.
729 unsafe { self.dealloc_buffer(); }
735 // We need to guarantee the following:
736 // * We don't ever allocate `> isize::MAX` byte-size objects
737 // * We don't overflow `usize::MAX` and actually allocate too little
739 // On 64-bit we just need to check for overflow since trying to allocate
740 // `> isize::MAX` bytes will surely fail. On 32-bit and 16-bit we need to add
741 // an extra guard for this in case we're running on a platform which can use
742 // all 4GB in user-space. e.g. PAE or x32
745 fn alloc_guard(alloc_size: usize) -> Result<(), CollectionAllocErr> {
746 if mem::size_of::<usize>() < 8 && alloc_size > ::core::isize::MAX as usize {
747 Err(CapacityOverflow)
753 // One central function responsible for reporting capacity overflows. This'll
754 // ensure that the code generation related to these panics is minimal as there's
755 // only one location which panics rather than a bunch throughout the module.
756 fn capacity_overflow() -> ! {
757 panic!("capacity overflow")
765 fn allocator_param() {
768 // Writing a test of integration between third-party
769 // allocators and RawVec is a little tricky because the RawVec
770 // API does not expose fallible allocation methods, so we
771 // cannot check what happens when allocator is exhausted
772 // (beyond detecting a panic).
774 // Instead, this just checks that the RawVec methods do at
775 // least go through the Allocator API when it reserves
778 // A dumb allocator that consumes a fixed amount of fuel
779 // before allocation attempts start failing.
780 struct BoundedAlloc { fuel: usize }
781 unsafe impl Alloc for BoundedAlloc {
782 unsafe fn alloc(&mut self, layout: Layout) -> Result<NonNull<u8>, AllocErr> {
783 let size = layout.size();
784 if size > self.fuel {
785 return Err(AllocErr);
787 match Global.alloc(layout) {
788 ok @ Ok(_) => { self.fuel -= size; ok }
792 unsafe fn dealloc(&mut self, ptr: NonNull<u8>, layout: Layout) {
793 Global.dealloc(ptr, layout)
797 let a = BoundedAlloc { fuel: 500 };
798 let mut v: RawVec<u8, _> = RawVec::with_capacity_in(50, a);
799 assert_eq!(v.a.fuel, 450);
800 v.reserve(50, 150); // (causes a realloc, thus using 50 + 150 = 200 units of fuel)
801 assert_eq!(v.a.fuel, 250);
805 fn reserve_does_not_overallocate() {
807 let mut v: RawVec<u32> = RawVec::new();
808 // First `reserve` allocates like `reserve_exact`
810 assert_eq!(9, v.cap());
814 let mut v: RawVec<u32> = RawVec::new();
816 assert_eq!(7, v.cap());
817 // 97 if more than double of 7, so `reserve` should work
818 // like `reserve_exact`.
820 assert_eq!(97, v.cap());
824 let mut v: RawVec<u32> = RawVec::new();
826 assert_eq!(12, v.cap());
828 // 3 is less than half of 12, so `reserve` must grow
829 // exponentially. At the time of writing this test grow
830 // factor is 2, so new capacity is 24, however, grow factor
831 // of 1.5 is OK too. Hence `>= 18` in assert.
832 assert!(v.cap() >= 12 + 12 / 2);