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.
19 struct BoundedAlloc { fuel: usize }
20 unsafe impl Alloc for BoundedAlloc {
21 unsafe fn alloc(&mut self, layout: Layout) -> Result<NonNull<u8>, AllocErr> {
22 let size = layout.size();
26 match Global.alloc(layout) {
27 ok @ Ok(_) => { self.fuel -= size; ok }
31 unsafe fn dealloc(&mut self, ptr: NonNull<u8>, layout: Layout) {
32 Global.dealloc(ptr, layout)
36 let a = BoundedAlloc { fuel: 500 };
37 let mut v: RawVec<u8, _> = RawVec::with_capacity_in(50, a);
38 assert_eq!(v.a.fuel, 450);
39 v.reserve(50, 150); // (causes a realloc, thus using 50 + 150 = 200 units of fuel)
40 assert_eq!(v.a.fuel, 250);
44 fn reserve_does_not_overallocate() {
46 let mut v: RawVec<u32> = RawVec::new();
47 // First, `reserve` allocates like `reserve_exact`.
49 assert_eq!(9, v.capacity());
53 let mut v: RawVec<u32> = RawVec::new();
55 assert_eq!(7, v.capacity());
56 // 97 if more than double of 7, so `reserve` should work
57 // like `reserve_exact`.
59 assert_eq!(97, v.capacity());
63 let mut v: RawVec<u32> = RawVec::new();
65 assert_eq!(12, v.capacity());
67 // 3 is less than half of 12, so `reserve` must grow
68 // exponentially. At the time of writing this test grow
69 // factor is 2, so new capacity is 24, however, grow factor
70 // of 1.5 is OK too. Hence `>= 18` in assert.
71 assert!(v.capacity() >= 12 + 12 / 2);