5 use crate::alloc
::AllocErr
;
7 // Writing a test of integration between third-party
8 // allocators and `RawVec` is a little tricky because the `RawVec`
9 // API does not expose fallible allocation methods, so we
10 // cannot check what happens when allocator is exhausted
11 // (beyond detecting a panic).
13 // Instead, this just checks that the `RawVec` methods do at
14 // least go through the Allocator API when it reserves
17 // A dumb allocator that consumes a fixed amount of fuel
18 // before allocation attempts start failing.
22 unsafe impl Alloc
for BoundedAlloc
{
23 unsafe fn alloc(&mut self, layout
: Layout
) -> Result
<NonNull
<u8>, AllocErr
> {
24 let size
= layout
.size();
28 match Global
.alloc(layout
) {
36 unsafe fn dealloc(&mut self, ptr
: NonNull
<u8>, layout
: Layout
) {
37 Global
.dealloc(ptr
, layout
)
41 let a
= BoundedAlloc { fuel: 500 }
;
42 let mut v
: RawVec
<u8, _
> = RawVec
::with_capacity_in(50, a
);
43 assert_eq
!(v
.a
.fuel
, 450);
44 v
.reserve(50, 150); // (causes a realloc, thus using 50 + 150 = 200 units of fuel)
45 assert_eq
!(v
.a
.fuel
, 250);
49 fn reserve_does_not_overallocate() {
51 let mut v
: RawVec
<u32> = RawVec
::new();
52 // First, `reserve` allocates like `reserve_exact`.
54 assert_eq
!(9, v
.capacity());
58 let mut v
: RawVec
<u32> = RawVec
::new();
60 assert_eq
!(7, v
.capacity());
61 // 97 if more than double of 7, so `reserve` should work
62 // like `reserve_exact`.
64 assert_eq
!(97, v
.capacity());
68 let mut v
: RawVec
<u32> = RawVec
::new();
70 assert_eq
!(12, v
.capacity());
72 // 3 is less than half of 12, so `reserve` must grow
73 // exponentially. At the time of writing this test grow
74 // factor is 2, so new capacity is 24, however, grow factor
75 // of 1.5 is OK too. Hence `>= 18` in assert.
76 assert
!(v
.capacity() >= 12 + 12 / 2);