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.
14 use core
::ptr
::{self, Unique}
;
16 use heap
::{Alloc, Layout, Heap}
;
17 use super::boxed
::Box
;
19 /// A low-level utility for more ergonomically allocating, reallocating, and deallocating
20 /// a buffer of memory on the heap without having to worry about all the corner cases
21 /// involved. This type is excellent for building your own data structures like Vec and VecDeque.
24 /// * Produces Unique::empty() on zero-sized types
25 /// * Produces Unique::empty() on zero-length allocations
26 /// * Catches all overflows in capacity computations (promotes them to "capacity overflow" panics)
27 /// * Guards against 32-bit systems allocating more than isize::MAX bytes
28 /// * Guards against overflowing your length
30 /// * Avoids freeing Unique::empty()
31 /// * Contains a ptr::Unique and thus endows the user with all related benefits
33 /// This type does not in anyway inspect the memory that it manages. When dropped it *will*
34 /// free its memory, but it *won't* try to Drop its contents. It is up to the user of RawVec
35 /// to handle the actual things *stored* inside of a RawVec.
37 /// Note that a RawVec always forces its capacity to be usize::MAX for zero-sized types.
38 /// This enables you to use capacity growing logic catch the overflows in your length
39 /// that might occur with zero-sized types.
41 /// However this means that you need to be careful when roundtripping this type
42 /// with a `Box<[T]>`: `cap()` won't yield the len. However `with_capacity`,
43 /// `shrink_to_fit`, and `from_box` will actually set RawVec's private capacity
44 /// field. This allows zero-sized types to not be special-cased by consumers of
46 #[allow(missing_debug_implementations)]
47 pub struct RawVec
<T
, A
: Alloc
= Heap
> {
53 impl<T
, A
: Alloc
> RawVec
<T
, A
> {
54 /// Like `new` but parameterized over the choice of allocator for
55 /// the returned RawVec.
56 pub fn new_in(a
: A
) -> Self {
57 // !0 is usize::MAX. This branch should be stripped at compile time.
58 let cap
= if mem
::size_of
::<T
>() == 0 { !0 }
else { 0 }
;
60 // Unique::empty() doubles as "unallocated" and "zero-sized allocation"
68 /// Like `with_capacity` but parameterized over the choice of
69 /// allocator for the returned RawVec.
71 pub fn with_capacity_in(cap
: usize, a
: A
) -> Self {
72 RawVec
::allocate_in(cap
, false, a
)
75 /// Like `with_capacity_zeroed` but parameterized over the choice
76 /// of allocator for the returned RawVec.
78 pub fn with_capacity_zeroed_in(cap
: usize, a
: A
) -> Self {
79 RawVec
::allocate_in(cap
, true, a
)
82 fn allocate_in(cap
: usize, zeroed
: bool
, mut a
: A
) -> Self {
84 let elem_size
= mem
::size_of
::<T
>();
86 let alloc_size
= cap
.checked_mul(elem_size
).expect("capacity overflow");
87 alloc_guard(alloc_size
);
89 // handles ZSTs and `cap = 0` alike
90 let ptr
= if alloc_size
== 0 {
91 mem
::align_of
::<T
>() as *mut u8
93 let align
= mem
::align_of
::<T
>();
94 let result
= if zeroed
{
95 a
.alloc_zeroed(Layout
::from_size_align(alloc_size
, align
).unwrap())
97 a
.alloc(Layout
::from_size_align(alloc_size
, align
).unwrap())
101 Err(err
) => a
.oom(err
),
106 ptr
: Unique
::new_unchecked(ptr
as *mut _
),
114 impl<T
> RawVec
<T
, Heap
> {
115 /// Creates the biggest possible RawVec (on the system heap)
116 /// without allocating. If T has positive size, then this makes a
117 /// RawVec with capacity 0. If T has 0 size, then it makes a
118 /// RawVec with capacity `usize::MAX`. Useful for implementing
119 /// delayed allocation.
120 pub fn new() -> Self {
124 /// Creates a RawVec (on the system heap) with exactly the
125 /// capacity and alignment requirements for a `[T; cap]`. This is
126 /// equivalent to calling RawVec::new when `cap` is 0 or T is
127 /// zero-sized. Note that if `T` is zero-sized this means you will
128 /// *not* get a RawVec with the requested capacity!
132 /// * Panics if the requested capacity exceeds `usize::MAX` bytes.
133 /// * Panics on 32-bit platforms if the requested capacity exceeds
134 /// `isize::MAX` bytes.
140 pub fn with_capacity(cap
: usize) -> Self {
141 RawVec
::allocate_in(cap
, false, Heap
)
144 /// Like `with_capacity` but guarantees the buffer is zeroed.
146 pub fn with_capacity_zeroed(cap
: usize) -> Self {
147 RawVec
::allocate_in(cap
, true, Heap
)
151 impl<T
, A
: Alloc
> RawVec
<T
, A
> {
152 /// Reconstitutes a RawVec from a pointer, capacity, and allocator.
154 /// # Undefined Behavior
156 /// The ptr must be allocated (via the given allocator `a`), and with the given capacity. The
157 /// capacity cannot exceed `isize::MAX` (only a concern on 32-bit systems).
158 /// If the ptr and capacity come from a RawVec created via `a`, then this is guaranteed.
159 pub unsafe fn from_raw_parts_in(ptr
: *mut T
, cap
: usize, a
: A
) -> Self {
161 ptr
: Unique
::new_unchecked(ptr
),
168 impl<T
> RawVec
<T
, Heap
> {
169 /// Reconstitutes a RawVec from a pointer, capacity.
171 /// # Undefined Behavior
173 /// The ptr must be allocated (on the system heap), and with the given capacity. The
174 /// capacity cannot exceed `isize::MAX` (only a concern on 32-bit systems).
175 /// If the ptr and capacity come from a RawVec, then this is guaranteed.
176 pub unsafe fn from_raw_parts(ptr
: *mut T
, cap
: usize) -> Self {
178 ptr
: Unique
::new_unchecked(ptr
),
184 /// Converts a `Box<[T]>` into a `RawVec<T>`.
185 pub fn from_box(mut slice
: Box
<[T
]>) -> Self {
187 let result
= RawVec
::from_raw_parts(slice
.as_mut_ptr(), slice
.len());
194 impl<T
, A
: Alloc
> RawVec
<T
, A
> {
195 /// Gets a raw pointer to the start of the allocation. Note that this is
196 /// Unique::empty() if `cap = 0` or T is zero-sized. In the former case, you must
198 pub fn ptr(&self) -> *mut T
{
202 /// Gets the capacity of the allocation.
204 /// This will always be `usize::MAX` if `T` is zero-sized.
206 pub fn cap(&self) -> usize {
207 if mem
::size_of
::<T
>() == 0 {
214 /// Returns a shared reference to the allocator backing this RawVec.
215 pub fn alloc(&self) -> &A
{
219 /// Returns a mutable reference to the allocator backing this RawVec.
220 pub fn alloc_mut(&mut self) -> &mut A
{
224 fn current_layout(&self) -> Option
<Layout
> {
228 // We have an allocated chunk of memory, so we can bypass runtime
229 // checks to get our current layout.
231 let align
= mem
::align_of
::<T
>();
232 let size
= mem
::size_of
::<T
>() * self.cap
;
233 Some(Layout
::from_size_align_unchecked(size
, align
))
238 /// Doubles the size of the type's backing allocation. This is common enough
239 /// to want to do that it's easiest to just have a dedicated method. Slightly
240 /// more efficient logic can be provided for this than the general case.
242 /// This function is ideal for when pushing elements one-at-a-time because
243 /// you don't need to incur the costs of the more general computations
244 /// reserve needs to do to guard against overflow. You do however need to
245 /// manually check if your `len == cap`.
249 /// * Panics if T is zero-sized on the assumption that you managed to exhaust
250 /// all `usize::MAX` slots in your imaginary buffer.
251 /// * Panics on 32-bit platforms if the requested capacity exceeds
252 /// `isize::MAX` bytes.
261 /// # #![feature(alloc)]
262 /// # extern crate alloc;
264 /// # use alloc::raw_vec::RawVec;
265 /// struct MyVec<T> {
270 /// impl<T> MyVec<T> {
271 /// pub fn push(&mut self, elem: T) {
272 /// if self.len == self.buf.cap() { self.buf.double(); }
273 /// // double would have aborted or panicked if the len exceeded
274 /// // `isize::MAX` so this is safe to do unchecked now.
276 /// ptr::write(self.buf.ptr().offset(self.len as isize), elem);
282 /// # let mut vec = MyVec { buf: RawVec::new(), len: 0 };
288 pub fn double(&mut self) {
290 let elem_size
= mem
::size_of
::<T
>();
292 // since we set the capacity to usize::MAX when elem_size is
293 // 0, getting to here necessarily means the RawVec is overfull.
294 assert
!(elem_size
!= 0, "capacity overflow");
296 let (new_cap
, uniq
) = match self.current_layout() {
298 // Since we guarantee that we never allocate more than
299 // isize::MAX bytes, `elem_size * self.cap <= isize::MAX` as
300 // a precondition, so this can't overflow. Additionally the
301 // alignment will never be too large as to "not be
302 // satisfiable", so `Layout::from_size_align` will always
305 // tl;dr; we bypass runtime checks due to dynamic assertions
306 // in this module, allowing us to use
307 // `from_size_align_unchecked`.
308 let new_cap
= 2 * self.cap
;
309 let new_size
= new_cap
* elem_size
;
310 let new_layout
= Layout
::from_size_align_unchecked(new_size
, cur
.align());
311 alloc_guard(new_size
);
312 let ptr_res
= self.a
.realloc(self.ptr
.as_ptr() as *mut u8,
316 Ok(ptr
) => (new_cap
, Unique
::new_unchecked(ptr
as *mut T
)),
317 Err(e
) => self.a
.oom(e
),
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
),
326 Err(e
) => self.a
.oom(e
),
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
);
371 let ptr
= self.ptr() as *mut _
;
372 let new_layout
= Layout
::from_size_align_unchecked(new_size
, old_layout
.align());
373 match self.a
.grow_in_place(ptr
, old_layout
, new_layout
) {
375 // We can't directly divide `size`.
386 /// Ensures that the buffer contains at least enough space to hold
387 /// `used_cap + needed_extra_cap` elements. If it doesn't already,
388 /// will reallocate the minimum possible amount of memory necessary.
389 /// Generally this will be exactly the amount of memory necessary,
390 /// but in principle the allocator is free to give back more than
393 /// If `used_cap` exceeds `self.cap()`, this may fail to actually allocate
394 /// the requested space. This is not really unsafe, but the unsafe
395 /// code *you* write that relies on the behavior of this function may break.
399 /// * Panics if the requested capacity exceeds `usize::MAX` bytes.
400 /// * Panics on 32-bit platforms if the requested capacity exceeds
401 /// `isize::MAX` bytes.
406 pub fn reserve_exact(&mut self, used_cap
: usize, needed_extra_cap
: usize) {
408 // NOTE: we don't early branch on ZSTs here because we want this
409 // to actually catch "asking for more than usize::MAX" in that case.
410 // If we make it past the first branch then we are guaranteed to
413 // Don't actually need any more capacity.
414 // Wrapping in case they gave a bad `used_cap`.
415 if self.cap().wrapping_sub(used_cap
) >= needed_extra_cap
{
419 // Nothing we can really do about these checks :(
420 let new_cap
= used_cap
.checked_add(needed_extra_cap
).expect("capacity overflow");
421 let new_layout
= match Layout
::array
::<T
>(new_cap
) {
422 Some(layout
) => layout
,
423 None
=> panic
!("capacity overflow"),
425 alloc_guard(new_layout
.size());
426 let res
= match self.current_layout() {
428 let old_ptr
= self.ptr
.as_ptr() as *mut u8;
429 self.a
.realloc(old_ptr
, layout
, new_layout
)
431 None
=> self.a
.alloc(new_layout
),
433 let uniq
= match res
{
434 Ok(ptr
) => Unique
::new_unchecked(ptr
as *mut T
),
435 Err(e
) => self.a
.oom(e
),
442 /// Calculates the buffer's new size given that it'll hold `used_cap +
443 /// needed_extra_cap` elements. This logic is used in amortized reserve methods.
444 /// Returns `(new_capacity, new_alloc_size)`.
445 fn amortized_new_size(&self, used_cap
: usize, needed_extra_cap
: usize) -> usize {
446 // Nothing we can really do about these checks :(
447 let required_cap
= used_cap
.checked_add(needed_extra_cap
)
448 .expect("capacity overflow");
449 // Cannot overflow, because `cap <= isize::MAX`, and type of `cap` is `usize`.
450 let double_cap
= self.cap
* 2;
451 // `double_cap` guarantees exponential growth.
452 cmp
::max(double_cap
, required_cap
)
455 /// Ensures that the buffer contains at least enough space to hold
456 /// `used_cap + needed_extra_cap` elements. If it doesn't already have
457 /// enough capacity, will reallocate enough space plus comfortable slack
458 /// space to get amortized `O(1)` behavior. Will limit this behavior
459 /// if it would needlessly cause itself to panic.
461 /// If `used_cap` exceeds `self.cap()`, this may fail to actually allocate
462 /// the requested space. This is not really unsafe, but the unsafe
463 /// code *you* write that relies on the behavior of this function may break.
465 /// This is ideal for implementing a bulk-push operation like `extend`.
469 /// * Panics if the requested capacity exceeds `usize::MAX` bytes.
470 /// * Panics on 32-bit platforms if the requested capacity exceeds
471 /// `isize::MAX` bytes.
480 /// # #![feature(alloc)]
481 /// # extern crate alloc;
483 /// # use alloc::raw_vec::RawVec;
484 /// struct MyVec<T> {
489 /// impl<T: Clone> MyVec<T> {
490 /// pub fn push_all(&mut self, elems: &[T]) {
491 /// self.buf.reserve(self.len, elems.len());
492 /// // reserve would have aborted or panicked if the len exceeded
493 /// // `isize::MAX` so this is safe to do unchecked now.
496 /// ptr::write(self.buf.ptr().offset(self.len as isize), x.clone());
503 /// # let mut vector = MyVec { buf: RawVec::new(), len: 0 };
504 /// # vector.push_all(&[1, 3, 5, 7, 9]);
507 pub fn reserve(&mut self, used_cap
: usize, needed_extra_cap
: usize) {
509 // NOTE: we don't early branch on ZSTs here because we want this
510 // to actually catch "asking for more than usize::MAX" in that case.
511 // If we make it past the first branch then we are guaranteed to
514 // Don't actually need any more capacity.
515 // Wrapping in case they give a bad `used_cap`
516 if self.cap().wrapping_sub(used_cap
) >= needed_extra_cap
{
520 let new_cap
= self.amortized_new_size(used_cap
, needed_extra_cap
);
522 let new_layout
= match Layout
::array
::<T
>(new_cap
) {
523 Some(layout
) => layout
,
524 None
=> panic
!("capacity overflow"),
526 // FIXME: may crash and burn on over-reserve
527 alloc_guard(new_layout
.size());
528 let res
= match self.current_layout() {
530 let old_ptr
= self.ptr
.as_ptr() as *mut u8;
531 self.a
.realloc(old_ptr
, layout
, new_layout
)
533 None
=> self.a
.alloc(new_layout
),
535 let uniq
= match res
{
536 Ok(ptr
) => Unique
::new_unchecked(ptr
as *mut T
),
537 Err(e
) => self.a
.oom(e
),
544 /// Attempts to ensure that the buffer contains at least enough space to hold
545 /// `used_cap + needed_extra_cap` elements. If it doesn't already have
546 /// enough capacity, will reallocate in place enough space plus comfortable slack
547 /// space to get amortized `O(1)` behavior. Will limit this behaviour
548 /// if it would needlessly cause itself to panic.
550 /// If `used_cap` exceeds `self.cap()`, this may fail to actually allocate
551 /// the requested space. This is not really unsafe, but the unsafe
552 /// code *you* write that relies on the behavior of this function may break.
554 /// Returns true if the reallocation attempt has succeeded, or false otherwise.
558 /// * Panics if the requested capacity exceeds `usize::MAX` bytes.
559 /// * Panics on 32-bit platforms if the requested capacity exceeds
560 /// `isize::MAX` bytes.
561 pub fn reserve_in_place(&mut self, used_cap
: usize, needed_extra_cap
: usize) -> bool
{
563 // NOTE: we don't early branch on ZSTs here because we want this
564 // to actually catch "asking for more than usize::MAX" in that case.
565 // If we make it past the first branch then we are guaranteed to
568 // Don't actually need any more capacity. If the current `cap` is 0, we can't
569 // reallocate in place.
570 // Wrapping in case they give a bad `used_cap`
571 let old_layout
= match self.current_layout() {
572 Some(layout
) => layout
,
573 None
=> return false,
575 if self.cap().wrapping_sub(used_cap
) >= needed_extra_cap
{
579 let new_cap
= self.amortized_new_size(used_cap
, needed_extra_cap
);
581 // Here, `cap < used_cap + needed_extra_cap <= new_cap`
582 // (regardless of whether `self.cap - used_cap` wrapped).
583 // Therefore we can safely call grow_in_place.
585 let ptr
= self.ptr() as *mut _
;
586 let new_layout
= Layout
::new
::<T
>().repeat(new_cap
).unwrap().0;
587 // FIXME: may crash and burn on over-reserve
588 alloc_guard(new_layout
.size());
589 match self.a
.grow_in_place(ptr
, old_layout
, new_layout
) {
601 /// Shrinks the allocation down to the specified amount. If the given amount
602 /// is 0, actually completely deallocates.
606 /// Panics if the given amount is *larger* than the current capacity.
611 pub fn shrink_to_fit(&mut self, amount
: usize) {
612 let elem_size
= mem
::size_of
::<T
>();
614 // Set the `cap` because they might be about to promote to a `Box<[T]>`
620 // This check is my waterloo; it's the only thing Vec wouldn't have to do.
621 assert
!(self.cap
>= amount
, "Tried to shrink to a larger capacity");
624 // We want to create a new zero-length vector within the
625 // same allocator. We use ptr::write to avoid an
626 // erroneous attempt to drop the contents, and we use
627 // ptr::read to sidestep condition against destructuring
628 // types that implement Drop.
631 let a
= ptr
::read(&self.a
as *const A
);
632 self.dealloc_buffer();
633 ptr
::write(self, RawVec
::new_in(a
));
635 } else if self.cap
!= amount
{
637 // We know here that our `amount` is greater than zero. This
638 // implies, via the assert above, that capacity is also greater
639 // than zero, which means that we've got a current layout that
642 // We also know that `self.cap` is greater than `amount`, and
643 // consequently we don't need runtime checks for creating either
645 let old_size
= elem_size
* self.cap
;
646 let new_size
= elem_size
* amount
;
647 let align
= mem
::align_of
::<T
>();
648 let old_layout
= Layout
::from_size_align_unchecked(old_size
, align
);
649 let new_layout
= Layout
::from_size_align_unchecked(new_size
, align
);
650 match self.a
.realloc(self.ptr
.as_ptr() as *mut u8,
653 Ok(p
) => self.ptr
= Unique
::new_unchecked(p
as *mut T
),
654 Err(err
) => self.a
.oom(err
),
662 impl<T
> RawVec
<T
, Heap
> {
663 /// Converts the entire buffer into `Box<[T]>`.
665 /// While it is not *strictly* Undefined Behavior to call
666 /// this procedure while some of the RawVec is uninitialized,
667 /// it certainly makes it trivial to trigger it.
669 /// Note that this will correctly reconstitute any `cap` changes
670 /// that may have been performed. (see description of type for details)
671 pub unsafe fn into_box(self) -> Box
<[T
]> {
672 // NOTE: not calling `cap()` here, actually using the real `cap` field!
673 let slice
= slice
::from_raw_parts_mut(self.ptr(), self.cap
);
674 let output
: Box
<[T
]> = Box
::from_raw(slice
);
680 impl<T
, A
: Alloc
> RawVec
<T
, A
> {
681 /// Frees the memory owned by the RawVec *without* trying to Drop its contents.
682 pub unsafe fn dealloc_buffer(&mut self) {
683 let elem_size
= mem
::size_of
::<T
>();
685 if let Some(layout
) = self.current_layout() {
686 let ptr
= self.ptr() as *mut u8;
687 self.a
.dealloc(ptr
, layout
);
693 unsafe impl<#[may_dangle] T, A: Alloc> Drop for RawVec<T, A> {
694 /// Frees the memory owned by the RawVec *without* trying to Drop its contents.
696 unsafe { self.dealloc_buffer(); }
702 // We need to guarantee the following:
703 // * We don't ever allocate `> isize::MAX` byte-size objects
704 // * We don't overflow `usize::MAX` and actually allocate too little
706 // On 64-bit we just need to check for overflow since trying to allocate
707 // `> isize::MAX` bytes will surely fail. On 32-bit and 16-bit we need to add
708 // an extra guard for this in case we're running on a platform which can use
709 // all 4GB in user-space. e.g. PAE or x32
712 fn alloc_guard(alloc_size
: usize) {
713 if mem
::size_of
::<usize>() < 8 {
714 assert
!(alloc_size
<= ::core
::isize::MAX
as usize,
715 "capacity overflow");
725 fn allocator_param() {
726 use allocator
::{Alloc, AllocErr}
;
728 // Writing a test of integration between third-party
729 // allocators and RawVec is a little tricky because the RawVec
730 // API does not expose fallible allocation methods, so we
731 // cannot check what happens when allocator is exhausted
732 // (beyond detecting a panic).
734 // Instead, this just checks that the RawVec methods do at
735 // least go through the Allocator API when it reserves
738 // A dumb allocator that consumes a fixed amount of fuel
739 // before allocation attempts start failing.
740 struct BoundedAlloc { fuel: usize }
741 unsafe impl Alloc
for BoundedAlloc
{
742 unsafe fn alloc(&mut self, layout
: Layout
) -> Result
<*mut u8, AllocErr
> {
743 let size
= layout
.size();
744 if size
> self.fuel
{
745 return Err(AllocErr
::Unsupported { details: "fuel exhausted" }
);
747 match Heap
.alloc(layout
) {
748 ok @
Ok(_
) => { self.fuel -= size; ok }
752 unsafe fn dealloc(&mut self, ptr
: *mut u8, layout
: Layout
) {
753 Heap
.dealloc(ptr
, layout
)
757 let a
= BoundedAlloc { fuel: 500 }
;
758 let mut v
: RawVec
<u8, _
> = RawVec
::with_capacity_in(50, a
);
759 assert_eq
!(v
.a
.fuel
, 450);
760 v
.reserve(50, 150); // (causes a realloc, thus using 50 + 150 = 200 units of fuel)
761 assert_eq
!(v
.a
.fuel
, 250);
765 fn reserve_does_not_overallocate() {
767 let mut v
: RawVec
<u32> = RawVec
::new();
768 // First `reserve` allocates like `reserve_exact`
770 assert_eq
!(9, v
.cap());
774 let mut v
: RawVec
<u32> = RawVec
::new();
776 assert_eq
!(7, v
.cap());
777 // 97 if more than double of 7, so `reserve` should work
778 // like `reserve_exact`.
780 assert_eq
!(97, v
.cap());
784 let mut v
: RawVec
<u32> = RawVec
::new();
786 assert_eq
!(12, v
.cap());
788 // 3 is less than half of 12, so `reserve` must grow
789 // exponentially. At the time of writing this test grow
790 // factor is 2, so new capacity is 24, however, grow factor
791 // of 1.5 is OK too. Hence `>= 18` in assert.
792 assert
!(v
.cap() >= 12 + 12 / 2);